title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Boxplot using Seaborn in Python | 10 Nov, 2020
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas.
A box plot helps to maintain the distribution of quantitative data in such a way that it facilitates the comparisons between variables or across levels of a categorical variable. The main body of the box plot showing the quartiles and the median’s confidence intervals if enabled. The medians have horizontal lines at the median of each box and while whiskers have the vertical lines extending to the most extreme, non-outlier data points and caps are the horizontal lines at the ends of the whiskers.
Syntax: seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, fliersize=5, linewidth=None, whis=1.5, ax=None, **kwargs)
Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. If x and y are absent, this is interpreted as wide-form. color: Color for all of the elements.
Returns: It returns the Axes object with the plot drawn onto it.
Example 1: Basic visualization of “fmri” dataset using violinplot()
Python3
import seaborn seaborn.set(style='whitegrid')fmri = seaborn.load_dataset("fmri") seaborn.boxplot(x="timepoint", y="signal", data=fmri)
Output:
Example 2: Basic visualization of “tips” dataset using boxplot()
Python3
import seaborn seaborn.set(style='whitegrid')tip = seaborn.load_dataset('tips') seaborn.boxplot(x='day', y='tip', data=tip)
Output:
1. Draw a single horizontal box plot using only one axis:
If we use only one data variable instead of two data variables then it means that the axis denotes each of these data variables as an axis.
X denotes an x-axis and y denote a y-axis.
Syntax:
seaborn.boxplot(x)
Python3
# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settip = seaborn.load_dataset("tips") seaborn.boxplot(x =tip['total_bill'])
Output:
2. Draw horizontal boxplot:
In the above example we see how to plot a single horizontal boxplot and here can perform multiple horizontal box plots with exchange of the data variable with another axis.
Python3
# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settip = seaborn.load_dataset("tips")seaborn.boxplot(x ='tip', y ='day', data = tip)
Output:
3. Using hue parameter:
While the points are plotted in two dimensions, another dimension can be added to the plot by coloring the points according to a third variable.
Syntax:
seaborn.boxplot(x, y, hue, data);
Python3
# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settip = seaborn.load_dataset("fmri") seaborn.boxplot(x ="timepoint", y ="signal", hue ="region", data = fmri)
Output:
4. Draw outlines around the data points using linewidth:
Width of the gray lines that frame the plot elements. Whenever we increase linewidth than the point also will increase automatically.
Syntax:
seaborn.boxplot(x, y, data, linewidth)
Python3
# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settip = seaborn.load_dataset("tips")seaborn.boxplot(x = 'day', y = 'tip', data = tip, linewidth=2.5)
Output:
5. Draw each level of the hue variable at different locations on the major categorical axis:
When using hue nesting, setting dodge should be True will separate the point for different hue levels along the categorical axis. And Palette is used for the different levels of the hue variable.
Syntax:
seaborn.boxplot(x, y, data, hue, palette, dodge)
Python3
# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settip = seaborn.load_dataset("tips")seaborn.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set2", dodge=True)
Output:
Possible values of palette are:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r,
GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r,
Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r,
Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1,
Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr,
YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r,
cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth,
gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern,
6. Control orientation of the plot (vertical or horizontal):
When we use orient as “h” then it plots the vertical and if we use “V” then it refers to the vertical.
Syntax:
seaborn.boxplot( data, orient )
Python3
# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settip = seaborn.load_dataset("tips")seaborn.boxplot(data = tip,orient="h")
Output:
Let’s check for vertical orient:
Python3
seaborn.boxplot(data = tip,orient="v")
Output:
7. Using color attributes for Color for all the elements.:
Python3
# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settip = seaborn.load_dataset("tips")seaborn.boxplot(x = 'day', y = 'tip', data = tip,color = "green")
Output:
kumar_satyam
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Nov, 2020"
},
{
"code": null,
"e": 352,
"s": 53,
"text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas."
},
{
"code": null,
"e": 855,
"s": 352,
"text": "A box plot helps to maintain the distribution of quantitative data in such a way that it facilitates the comparisons between variables or across levels of a categorical variable. The main body of the box plot showing the quartiles and the median’s confidence intervals if enabled. The medians have horizontal lines at the median of each box and while whiskers have the vertical lines extending to the most extreme, non-outlier data points and caps are the horizontal lines at the ends of the whiskers. "
},
{
"code": null,
"e": 1081,
"s": 855,
"text": "Syntax: seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, fliersize=5, linewidth=None, whis=1.5, ax=None, **kwargs)"
},
{
"code": null,
"e": 1263,
"s": 1081,
"text": "Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. If x and y are absent, this is interpreted as wide-form. color: Color for all of the elements."
},
{
"code": null,
"e": 1329,
"s": 1263,
"text": "Returns: It returns the Axes object with the plot drawn onto it. "
},
{
"code": null,
"e": 1398,
"s": 1329,
"text": "Example 1: Basic visualization of “fmri” dataset using violinplot() "
},
{
"code": null,
"e": 1406,
"s": 1398,
"text": "Python3"
},
{
"code": "import seaborn seaborn.set(style='whitegrid')fmri = seaborn.load_dataset(\"fmri\") seaborn.boxplot(x=\"timepoint\", y=\"signal\", data=fmri)",
"e": 1572,
"s": 1406,
"text": null
},
{
"code": null,
"e": 1580,
"s": 1572,
"text": "Output:"
},
{
"code": null,
"e": 1646,
"s": 1580,
"text": "Example 2: Basic visualization of “tips” dataset using boxplot() "
},
{
"code": null,
"e": 1654,
"s": 1646,
"text": "Python3"
},
{
"code": "import seaborn seaborn.set(style='whitegrid')tip = seaborn.load_dataset('tips') seaborn.boxplot(x='day', y='tip', data=tip)",
"e": 1779,
"s": 1654,
"text": null
},
{
"code": null,
"e": 1788,
"s": 1779,
"text": "Output: "
},
{
"code": null,
"e": 1846,
"s": 1788,
"text": "1. Draw a single horizontal box plot using only one axis:"
},
{
"code": null,
"e": 1986,
"s": 1846,
"text": "If we use only one data variable instead of two data variables then it means that the axis denotes each of these data variables as an axis."
},
{
"code": null,
"e": 2029,
"s": 1986,
"text": "X denotes an x-axis and y denote a y-axis."
},
{
"code": null,
"e": 2038,
"s": 2029,
"text": "Syntax: "
},
{
"code": null,
"e": 2058,
"s": 2038,
"text": "seaborn.boxplot(x)\n"
},
{
"code": null,
"e": 2066,
"s": 2058,
"text": "Python3"
},
{
"code": "# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settip = seaborn.load_dataset(\"tips\") seaborn.boxplot(x =tip['total_bill'])",
"e": 2356,
"s": 2066,
"text": null
},
{
"code": null,
"e": 2364,
"s": 2356,
"text": "Output:"
},
{
"code": null,
"e": 2392,
"s": 2364,
"text": "2. Draw horizontal boxplot:"
},
{
"code": null,
"e": 2565,
"s": 2392,
"text": "In the above example we see how to plot a single horizontal boxplot and here can perform multiple horizontal box plots with exchange of the data variable with another axis."
},
{
"code": null,
"e": 2573,
"s": 2565,
"text": "Python3"
},
{
"code": "# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settip = seaborn.load_dataset(\"tips\")seaborn.boxplot(x ='tip', y ='day', data = tip)",
"e": 2872,
"s": 2573,
"text": null
},
{
"code": null,
"e": 2880,
"s": 2872,
"text": "Output:"
},
{
"code": null,
"e": 2904,
"s": 2880,
"text": "3. Using hue parameter:"
},
{
"code": null,
"e": 3049,
"s": 2904,
"text": "While the points are plotted in two dimensions, another dimension can be added to the plot by coloring the points according to a third variable."
},
{
"code": null,
"e": 3057,
"s": 3049,
"text": "Syntax:"
},
{
"code": null,
"e": 3091,
"s": 3057,
"text": "seaborn.boxplot(x, y, hue, data);"
},
{
"code": null,
"e": 3099,
"s": 3091,
"text": "Python3"
},
{
"code": "# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settip = seaborn.load_dataset(\"fmri\") seaborn.boxplot(x =\"timepoint\", y =\"signal\", hue =\"region\", data = fmri)",
"e": 3460,
"s": 3099,
"text": null
},
{
"code": null,
"e": 3468,
"s": 3460,
"text": "Output:"
},
{
"code": null,
"e": 3525,
"s": 3468,
"text": "4. Draw outlines around the data points using linewidth:"
},
{
"code": null,
"e": 3659,
"s": 3525,
"text": "Width of the gray lines that frame the plot elements. Whenever we increase linewidth than the point also will increase automatically."
},
{
"code": null,
"e": 3667,
"s": 3659,
"text": "Syntax:"
},
{
"code": null,
"e": 3706,
"s": 3667,
"text": "seaborn.boxplot(x, y, data, linewidth)"
},
{
"code": null,
"e": 3714,
"s": 3706,
"text": "Python3"
},
{
"code": "# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settip = seaborn.load_dataset(\"tips\")seaborn.boxplot(x = 'day', y = 'tip', data = tip, linewidth=2.5)",
"e": 4060,
"s": 3714,
"text": null
},
{
"code": null,
"e": 4068,
"s": 4060,
"text": "Output:"
},
{
"code": null,
"e": 4161,
"s": 4068,
"text": "5. Draw each level of the hue variable at different locations on the major categorical axis:"
},
{
"code": null,
"e": 4357,
"s": 4161,
"text": "When using hue nesting, setting dodge should be True will separate the point for different hue levels along the categorical axis. And Palette is used for the different levels of the hue variable."
},
{
"code": null,
"e": 4365,
"s": 4357,
"text": "Syntax:"
},
{
"code": null,
"e": 4414,
"s": 4365,
"text": "seaborn.boxplot(x, y, data, hue, palette, dodge)"
},
{
"code": null,
"e": 4422,
"s": 4414,
"text": "Python3"
},
{
"code": "# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settip = seaborn.load_dataset(\"tips\")seaborn.boxplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", data=tips, palette=\"Set2\", dodge=True)",
"e": 4812,
"s": 4422,
"text": null
},
{
"code": null,
"e": 4820,
"s": 4812,
"text": "Output:"
},
{
"code": null,
"e": 4852,
"s": 4820,
"text": "Possible values of palette are:"
},
{
"code": null,
"e": 4962,
"s": 4852,
"text": "Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r,"
},
{
"code": null,
"e": 5076,
"s": 4962,
"text": "GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r,"
},
{
"code": null,
"e": 5190,
"s": 5076,
"text": "Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r,"
},
{
"code": null,
"e": 5308,
"s": 5190,
"text": "Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1,"
},
{
"code": null,
"e": 5424,
"s": 5308,
"text": "Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr,"
},
{
"code": null,
"e": 5544,
"s": 5424,
"text": "YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r,"
},
{
"code": null,
"e": 5668,
"s": 5544,
"text": "cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth,"
},
{
"code": null,
"e": 5797,
"s": 5668,
"text": "gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, "
},
{
"code": null,
"e": 5858,
"s": 5797,
"text": "6. Control orientation of the plot (vertical or horizontal):"
},
{
"code": null,
"e": 5961,
"s": 5858,
"text": "When we use orient as “h” then it plots the vertical and if we use “V” then it refers to the vertical."
},
{
"code": null,
"e": 5969,
"s": 5961,
"text": "Syntax:"
},
{
"code": null,
"e": 6001,
"s": 5969,
"text": "seaborn.boxplot( data, orient )"
},
{
"code": null,
"e": 6009,
"s": 6001,
"text": "Python3"
},
{
"code": "# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settip = seaborn.load_dataset(\"tips\")seaborn.boxplot(data = tip,orient=\"h\")",
"e": 6299,
"s": 6009,
"text": null
},
{
"code": null,
"e": 6307,
"s": 6299,
"text": "Output:"
},
{
"code": null,
"e": 6340,
"s": 6307,
"text": "Let’s check for vertical orient:"
},
{
"code": null,
"e": 6348,
"s": 6340,
"text": "Python3"
},
{
"code": "seaborn.boxplot(data = tip,orient=\"v\")",
"e": 6387,
"s": 6348,
"text": null
},
{
"code": null,
"e": 6395,
"s": 6387,
"text": "Output:"
},
{
"code": null,
"e": 6454,
"s": 6395,
"text": "7. Using color attributes for Color for all the elements.:"
},
{
"code": null,
"e": 6462,
"s": 6454,
"text": "Python3"
},
{
"code": "# Python program to illustrate# boxplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settip = seaborn.load_dataset(\"tips\")seaborn.boxplot(x = 'day', y = 'tip', data = tip,color = \"green\")",
"e": 6779,
"s": 6462,
"text": null
},
{
"code": null,
"e": 6787,
"s": 6779,
"text": "Output:"
},
{
"code": null,
"e": 6802,
"s": 6789,
"text": "kumar_satyam"
},
{
"code": null,
"e": 6817,
"s": 6802,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 6824,
"s": 6817,
"text": "Python"
},
{
"code": null,
"e": 6922,
"s": 6824,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6950,
"s": 6922,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6972,
"s": 6950,
"text": "Python map() function"
},
{
"code": null,
"e": 7022,
"s": 6972,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 7040,
"s": 7022,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7084,
"s": 7040,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 7126,
"s": 7084,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7149,
"s": 7126,
"text": "Taking input in Python"
},
{
"code": null,
"e": 7171,
"s": 7149,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7206,
"s": 7171,
"text": "Read a file line by line in Python"
}
] |
JUnit - Using Assertion | All the assertions are in the Assert class.
public class Assert extends java.lang.Object
This class provides a set of assertion methods, useful for writing tests. Only failed assertions are recorded. Some of the important methods of Assert class are as follows −
void assertEquals(boolean expected, boolean actual)
Checks that two primitives/objects are equal.
void assertTrue(boolean condition)
Checks that a condition is true.
void assertFalse(boolean condition)
Checks that a condition is false.
void assertNotNull(Object object)
Checks that an object isn't null.
void assertNull(Object object)
Checks that an object is null.
void assertSame(object1, object2)
The assertSame() method tests if two object references point to the same object.
void assertNotSame(object1, object2)
The assertNotSame() method tests if two object references do not point to the same object.
void assertArrayEquals(expectedArray, resultArray);
The assertArrayEquals() method will test whether two arrays are equal to each other.
Let's use some of the above-mentioned methods in an example. Create a java class file named TestAssertions.java in C:\>JUNIT_WORKSPACE.
import org.junit.Test;
import static org.junit.Assert.*;
public class TestAssertions {
@Test
public void testAssertions() {
//test data
String str1 = new String ("abc");
String str2 = new String ("abc");
String str3 = null;
String str4 = "abc";
String str5 = "abc";
int val1 = 5;
int val2 = 6;
String[] expectedArray = {"one", "two", "three"};
String[] resultArray = {"one", "two", "three"};
//Check that two objects are equal
assertEquals(str1, str2);
//Check that a condition is true
assertTrue (val1 < val2);
//Check that a condition is false
assertFalse(val1 > val2);
//Check that an object isn't null
assertNotNull(str1);
//Check that an object is null
assertNull(str3);
//Check if two object references point to the same object
assertSame(str4,str5);
//Check if two object references not point to the same object
assertNotSame(str1,str3);
//Check whether two arrays are equal to each other.
assertArrayEquals(expectedArray, resultArray);
}
}
Next, create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s).
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner2 {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestAssertions.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac TestAssertions.java TestRunner.java
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
true
Annotations are like meta-tags that you can add to your code, and apply them to methods or in class. These annotations in JUnit provide the following information about test methods −
which methods are going to run before and after test methods.
which methods run before and after all the methods, and.
which methods or classes will be ignored during the execution.
The following table provides a list of annotations and their meaning in JUnit −
@Test
The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case.
@Before
Several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before each Test method.
@After
If you allocate external resources in a Before method, you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method.
@BeforeClass
Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class.
@AfterClass
This will perform the method after all tests have finished. This can be used to perform clean-up activities.
@Ignore
The Ignore annotation is used to ignore the test and that test will not be executed.
Create a java class file named JunitAnnotation.java in C:\>JUNIT_WORKSPACE to test annotation.
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class JunitAnnotation {
//execute before class
@BeforeClass
public static void beforeClass() {
System.out.println("in before class");
}
//execute after class
@AfterClass
public static void afterClass() {
System.out.println("in after class");
}
//execute before test
@Before
public void before() {
System.out.println("in before");
}
//execute after test
@After
public void after() {
System.out.println("in after");
}
//test case
@Test
public void test() {
System.out.println("in test");
}
//test case ignore and will not execute
@Ignore
public void ignoreTest() {
System.out.println("in ignore test");
}
}
Next, create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute annotations.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitAnnotation.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac JunitAnnotation.java TestRunner.java
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
in before class
in before
in test
in after
in after class | [
{
"code": null,
"e": 2150,
"s": 2106,
"text": "All the assertions are in the Assert class."
},
{
"code": null,
"e": 2196,
"s": 2150,
"text": "public class Assert extends java.lang.Object\n"
},
{
"code": null,
"e": 2370,
"s": 2196,
"text": "This class provides a set of assertion methods, useful for writing tests. Only failed assertions are recorded. Some of the important methods of Assert class are as follows −"
},
{
"code": null,
"e": 2422,
"s": 2370,
"text": "void assertEquals(boolean expected, boolean actual)"
},
{
"code": null,
"e": 2468,
"s": 2422,
"text": "Checks that two primitives/objects are equal."
},
{
"code": null,
"e": 2503,
"s": 2468,
"text": "void assertTrue(boolean condition)"
},
{
"code": null,
"e": 2536,
"s": 2503,
"text": "Checks that a condition is true."
},
{
"code": null,
"e": 2572,
"s": 2536,
"text": "void assertFalse(boolean condition)"
},
{
"code": null,
"e": 2606,
"s": 2572,
"text": "Checks that a condition is false."
},
{
"code": null,
"e": 2640,
"s": 2606,
"text": "void assertNotNull(Object object)"
},
{
"code": null,
"e": 2674,
"s": 2640,
"text": "Checks that an object isn't null."
},
{
"code": null,
"e": 2705,
"s": 2674,
"text": "void assertNull(Object object)"
},
{
"code": null,
"e": 2736,
"s": 2705,
"text": "Checks that an object is null."
},
{
"code": null,
"e": 2770,
"s": 2736,
"text": "void assertSame(object1, object2)"
},
{
"code": null,
"e": 2851,
"s": 2770,
"text": "The assertSame() method tests if two object references point to the same object."
},
{
"code": null,
"e": 2888,
"s": 2851,
"text": "void assertNotSame(object1, object2)"
},
{
"code": null,
"e": 2979,
"s": 2888,
"text": "The assertNotSame() method tests if two object references do not point to the same object."
},
{
"code": null,
"e": 3031,
"s": 2979,
"text": "void assertArrayEquals(expectedArray, resultArray);"
},
{
"code": null,
"e": 3116,
"s": 3031,
"text": "The assertArrayEquals() method will test whether two arrays are equal to each other."
},
{
"code": null,
"e": 3252,
"s": 3116,
"text": "Let's use some of the above-mentioned methods in an example. Create a java class file named TestAssertions.java in C:\\>JUNIT_WORKSPACE."
},
{
"code": null,
"e": 4380,
"s": 3252,
"text": "import org.junit.Test;\nimport static org.junit.Assert.*;\n\npublic class TestAssertions {\n\n @Test\n public void testAssertions() {\n //test data\n String str1 = new String (\"abc\");\n String str2 = new String (\"abc\");\n String str3 = null;\n String str4 = \"abc\";\n String str5 = \"abc\";\n\t\t\n int val1 = 5;\n int val2 = 6;\n\n String[] expectedArray = {\"one\", \"two\", \"three\"};\n String[] resultArray = {\"one\", \"two\", \"three\"};\n\n //Check that two objects are equal\n assertEquals(str1, str2);\n\n //Check that a condition is true\n assertTrue (val1 < val2);\n\n //Check that a condition is false\n assertFalse(val1 > val2);\n\n //Check that an object isn't null\n assertNotNull(str1);\n\n //Check that an object is null\n assertNull(str3);\n\n //Check if two object references point to the same object\n assertSame(str4,str5);\n\n //Check if two object references not point to the same object\n assertNotSame(str1,str3);\n\n //Check whether two arrays are equal to each other.\n assertArrayEquals(expectedArray, resultArray);\n }\n}"
},
{
"code": null,
"e": 4481,
"s": 4380,
"text": "Next, create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)."
},
{
"code": null,
"e": 4906,
"s": 4481,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner2 {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestAssertions.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} "
},
{
"code": null,
"e": 4965,
"s": 4906,
"text": "Compile the Test case and Test Runner classes using javac."
},
{
"code": null,
"e": 5027,
"s": 4965,
"text": "C:\\JUNIT_WORKSPACE>javac TestAssertions.java TestRunner.java\n"
},
{
"code": null,
"e": 5122,
"s": 5027,
"text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class."
},
{
"code": null,
"e": 5158,
"s": 5122,
"text": "C:\\JUNIT_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 5177,
"s": 5158,
"text": "Verify the output."
},
{
"code": null,
"e": 5183,
"s": 5177,
"text": "true\n"
},
{
"code": null,
"e": 5366,
"s": 5183,
"text": "Annotations are like meta-tags that you can add to your code, and apply them to methods or in class. These annotations in JUnit provide the following information about test methods −"
},
{
"code": null,
"e": 5428,
"s": 5366,
"text": "which methods are going to run before and after test methods."
},
{
"code": null,
"e": 5485,
"s": 5428,
"text": "which methods run before and after all the methods, and."
},
{
"code": null,
"e": 5548,
"s": 5485,
"text": "which methods or classes will be ignored during the execution."
},
{
"code": null,
"e": 5628,
"s": 5548,
"text": "The following table provides a list of annotations and their meaning in JUnit −"
},
{
"code": null,
"e": 5634,
"s": 5628,
"text": "@Test"
},
{
"code": null,
"e": 5745,
"s": 5634,
"text": "The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case."
},
{
"code": null,
"e": 5753,
"s": 5745,
"text": "@Before"
},
{
"code": null,
"e": 5916,
"s": 5753,
"text": "Several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before each Test method."
},
{
"code": null,
"e": 5923,
"s": 5916,
"text": "@After"
},
{
"code": null,
"e": 6120,
"s": 5923,
"text": "If you allocate external resources in a Before method, you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method."
},
{
"code": null,
"e": 6133,
"s": 6120,
"text": "@BeforeClass"
},
{
"code": null,
"e": 6260,
"s": 6133,
"text": "Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class."
},
{
"code": null,
"e": 6272,
"s": 6260,
"text": "@AfterClass"
},
{
"code": null,
"e": 6381,
"s": 6272,
"text": "This will perform the method after all tests have finished. This can be used to perform clean-up activities."
},
{
"code": null,
"e": 6389,
"s": 6381,
"text": "@Ignore"
},
{
"code": null,
"e": 6474,
"s": 6389,
"text": "The Ignore annotation is used to ignore the test and that test will not be executed."
},
{
"code": null,
"e": 6569,
"s": 6474,
"text": "Create a java class file named JunitAnnotation.java in C:\\>JUNIT_WORKSPACE to test annotation."
},
{
"code": null,
"e": 7459,
"s": 6569,
"text": "import org.junit.After;\nimport org.junit.AfterClass;\n\nimport org.junit.Before;\nimport org.junit.BeforeClass;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\n\npublic class JunitAnnotation {\n\t\n //execute before class\n @BeforeClass\n public static void beforeClass() {\n System.out.println(\"in before class\");\n }\n\n //execute after class\n @AfterClass\n public static void afterClass() {\n System.out.println(\"in after class\");\n }\n\n //execute before test\n @Before\n public void before() {\n System.out.println(\"in before\");\n }\n\t\n //execute after test\n @After\n public void after() {\n System.out.println(\"in after\");\n }\n\t\n //test case\n @Test\n public void test() {\n System.out.println(\"in test\");\n }\n\t\n //test case ignore and will not execute\n @Ignore\n public void ignoreTest() {\n System.out.println(\"in ignore test\");\n }\n}"
},
{
"code": null,
"e": 7559,
"s": 7459,
"text": "Next, create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute annotations."
},
{
"code": null,
"e": 7984,
"s": 7559,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(JunitAnnotation.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} "
},
{
"code": null,
"e": 8043,
"s": 7984,
"text": "Compile the Test case and Test Runner classes using javac."
},
{
"code": null,
"e": 8106,
"s": 8043,
"text": "C:\\JUNIT_WORKSPACE>javac JunitAnnotation.java TestRunner.java\n"
},
{
"code": null,
"e": 8201,
"s": 8106,
"text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class."
},
{
"code": null,
"e": 8237,
"s": 8201,
"text": "C:\\JUNIT_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 8256,
"s": 8237,
"text": "Verify the output."
}
] |
String matching with * (that matches with any) in any of the two strings | 06 May, 2021
You are given two strings A and B. Strings also contains special character * . you can replace * with any alphabetic character. Finally, you have to tell whether it is possible to make both string same or not.Examples:
Input : A = "gee*sforgeeks"
B = "geeksforgeeks"
Output :Yes
Input :A = "abs*"
B = "abds"
Output :No
Explanation: How we can solve above problem, Basically we three cases, Case 1: Both string contains * at particular position, at that time we can replace both * with any character make the string equal at that position. Case 2: If one string have character and other has * at that position. So, we can replace * with the same character in other string. Case 3: If both the string has a character at that position, then they must be same, otherwise we can’t make them equal.
C++
Java
Python3
C#
PHP
Javascript
// CPP program for string matching with *#include <bits/stdc++.h>using namespace std; bool doMatch(string A, string B){ for (int i = 0; i < A.length(); i++) // if the string don't have * // then character at that position // must be same. if (A[i] != '*' && B[i] != '*') if (A[i] != B[i]) return false; return true;} int main(){ string A = "gee*sforgeeks"; string B = "geeksforgeeks"; cout << doMatch(A, B); return 0;}
// Java program for string matching with *import java.util.*; public class GfG { // Function to check if the two // strings can be matched or not public static int doMatch(String A, String B) { for (int i = 0; i < A.length(); i++){ // if the string don't have * // then character at that position // must be same. if (A.charAt(i) != '*' && B.charAt(i) != '*'){ if (A.charAt(i) != B.charAt(i)) return 0; } } return 1; } // Driver code public static void main(String []args){ String A = "gee*sforgeeks"; String B = "geeksforgeeks"; System.out.println(doMatch(A, B)); }} // This code is contributed by Rituraj Jain
# Python3 program for string# matching with * def doMatch(A, B): for i in range(len(A)): # if the string don't have * # then character t that position # must be same. if A[i] != '*' and B[i] != '*': if A[i] != B[i]: return False return True #Driver codeif __name__=='__main__': A = "gee*sforgeeks" B = "geeksforgeeks" print(int(doMatch(A, B))) # this code is contributed by# Shashank_Sharma
// C# program for string matching withusing System; class GfG{ // Function to check if the two // strings can be matched or not public static int doMatch(String A, String B) { for (int i = 0; i < A.Length; i++) { // if the string don't have * // then character at that position // must be same. if (A[i] != '*' && B[i] != '*') if (A[i] != B[i]) return 0; } return 1; } // Driver code public static void Main(String []args) { String A = "gee*sforgeeks"; String B = "geeksforgeeks"; Console.WriteLine(doMatch(A, B)); }} // This code contributed by Rajput-Ji
<?php// PHP program for string matching with * function doMatch($A, $B){ for ($i = 0; $i < strlen($A); $i++) // if the string don't have * // then character at that position // must be same. if ($A[$i] != '*' && $B[$i] != '*') if ($A[$i] != $B[$i]) return false; return true;} // Driver Code$A = "gee*sforgeeks";$B = "geeksforgeeks";echo doMatch($A, $B); // This code is contributed by Tushil.?>
<script>// javascript program for string matching with * public class GfG { // Function to check if the two // strings can be matched or not function doMatch(A, B) { for (i = 0; i < A.length; i++) { // if the string don't have * // then character at that position // must be same. if (A.charAt(i) != '*' && B.charAt(i) != '*') { if (A.charAt(i) != B.charAt(i)) return 0; } } return 1; } // Driver code var A = "gee*sforgeeks"; var B = "geeksforgeeks"; document.write(doMatch(A, B)); // This code is contributed by aashish1995.</script>
1
Shashank_Sharma
jit_t
rituraj_jain
Rajput-Ji
aashish1995
C-String-Question
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find all occurrences of a given word in a matrix
Check if the given string is shuffled substring of another string
Reverse the substrings of the given String according to the given Array of indices
How to check Aadhaar number is valid or not using Regular Expression
How to validate pin code of India using Regular Expression
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 273,
"s": 52,
"text": "You are given two strings A and B. Strings also contains special character * . you can replace * with any alphabetic character. Finally, you have to tell whether it is possible to make both string same or not.Examples: "
},
{
"code": null,
"e": 389,
"s": 273,
"text": "Input : A = \"gee*sforgeeks\"\n B = \"geeksforgeeks\"\nOutput :Yes\n\nInput :A = \"abs*\"\n B = \"abds\"\nOutput :No"
},
{
"code": null,
"e": 867,
"s": 391,
"text": "Explanation: How we can solve above problem, Basically we three cases, Case 1: Both string contains * at particular position, at that time we can replace both * with any character make the string equal at that position. Case 2: If one string have character and other has * at that position. So, we can replace * with the same character in other string. Case 3: If both the string has a character at that position, then they must be same, otherwise we can’t make them equal. "
},
{
"code": null,
"e": 871,
"s": 867,
"text": "C++"
},
{
"code": null,
"e": 876,
"s": 871,
"text": "Java"
},
{
"code": null,
"e": 884,
"s": 876,
"text": "Python3"
},
{
"code": null,
"e": 887,
"s": 884,
"text": "C#"
},
{
"code": null,
"e": 891,
"s": 887,
"text": "PHP"
},
{
"code": null,
"e": 902,
"s": 891,
"text": "Javascript"
},
{
"code": "// CPP program for string matching with *#include <bits/stdc++.h>using namespace std; bool doMatch(string A, string B){ for (int i = 0; i < A.length(); i++) // if the string don't have * // then character at that position // must be same. if (A[i] != '*' && B[i] != '*') if (A[i] != B[i]) return false; return true;} int main(){ string A = \"gee*sforgeeks\"; string B = \"geeksforgeeks\"; cout << doMatch(A, B); return 0;}",
"e": 1394,
"s": 902,
"text": null
},
{
"code": "// Java program for string matching with *import java.util.*; public class GfG { // Function to check if the two // strings can be matched or not public static int doMatch(String A, String B) { for (int i = 0; i < A.length(); i++){ // if the string don't have * // then character at that position // must be same. if (A.charAt(i) != '*' && B.charAt(i) != '*'){ if (A.charAt(i) != B.charAt(i)) return 0; } } return 1; } // Driver code public static void main(String []args){ String A = \"gee*sforgeeks\"; String B = \"geeksforgeeks\"; System.out.println(doMatch(A, B)); }} // This code is contributed by Rituraj Jain",
"e": 2192,
"s": 1394,
"text": null
},
{
"code": "# Python3 program for string# matching with * def doMatch(A, B): for i in range(len(A)): # if the string don't have * # then character t that position # must be same. if A[i] != '*' and B[i] != '*': if A[i] != B[i]: return False return True #Driver codeif __name__=='__main__': A = \"gee*sforgeeks\" B = \"geeksforgeeks\" print(int(doMatch(A, B))) # this code is contributed by# Shashank_Sharma",
"e": 2666,
"s": 2192,
"text": null
},
{
"code": "// C# program for string matching withusing System; class GfG{ // Function to check if the two // strings can be matched or not public static int doMatch(String A, String B) { for (int i = 0; i < A.Length; i++) { // if the string don't have * // then character at that position // must be same. if (A[i] != '*' && B[i] != '*') if (A[i] != B[i]) return 0; } return 1; } // Driver code public static void Main(String []args) { String A = \"gee*sforgeeks\"; String B = \"geeksforgeeks\"; Console.WriteLine(doMatch(A, B)); }} // This code contributed by Rajput-Ji",
"e": 3409,
"s": 2666,
"text": null
},
{
"code": "<?php// PHP program for string matching with * function doMatch($A, $B){ for ($i = 0; $i < strlen($A); $i++) // if the string don't have * // then character at that position // must be same. if ($A[$i] != '*' && $B[$i] != '*') if ($A[$i] != $B[$i]) return false; return true;} // Driver Code$A = \"gee*sforgeeks\";$B = \"geeksforgeeks\";echo doMatch($A, $B); // This code is contributed by Tushil.?>",
"e": 3863,
"s": 3409,
"text": null
},
{
"code": "<script>// javascript program for string matching with * public class GfG { // Function to check if the two // strings can be matched or not function doMatch(A, B) { for (i = 0; i < A.length; i++) { // if the string don't have * // then character at that position // must be same. if (A.charAt(i) != '*' && B.charAt(i) != '*') { if (A.charAt(i) != B.charAt(i)) return 0; } } return 1; } // Driver code var A = \"gee*sforgeeks\"; var B = \"geeksforgeeks\"; document.write(doMatch(A, B)); // This code is contributed by aashish1995.</script>",
"e": 4571,
"s": 3863,
"text": null
},
{
"code": null,
"e": 4573,
"s": 4571,
"text": "1"
},
{
"code": null,
"e": 4591,
"s": 4575,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 4597,
"s": 4591,
"text": "jit_t"
},
{
"code": null,
"e": 4610,
"s": 4597,
"text": "rituraj_jain"
},
{
"code": null,
"e": 4620,
"s": 4610,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 4632,
"s": 4620,
"text": "aashish1995"
},
{
"code": null,
"e": 4650,
"s": 4632,
"text": "C-String-Question"
},
{
"code": null,
"e": 4668,
"s": 4650,
"text": "Pattern Searching"
},
{
"code": null,
"e": 4676,
"s": 4668,
"text": "Strings"
},
{
"code": null,
"e": 4684,
"s": 4676,
"text": "Strings"
},
{
"code": null,
"e": 4702,
"s": 4684,
"text": "Pattern Searching"
},
{
"code": null,
"e": 4800,
"s": 4702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4849,
"s": 4800,
"text": "Find all occurrences of a given word in a matrix"
},
{
"code": null,
"e": 4915,
"s": 4849,
"text": "Check if the given string is shuffled substring of another string"
},
{
"code": null,
"e": 4998,
"s": 4915,
"text": "Reverse the substrings of the given String according to the given Array of indices"
},
{
"code": null,
"e": 5067,
"s": 4998,
"text": "How to check Aadhaar number is valid or not using Regular Expression"
},
{
"code": null,
"e": 5126,
"s": 5067,
"text": "How to validate pin code of India using Regular Expression"
},
{
"code": null,
"e": 5172,
"s": 5126,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 5197,
"s": 5172,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5257,
"s": 5197,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5272,
"s": 5257,
"text": "C++ Data Types"
}
] |
PwnXSS – Automated XSS Vulnerability Scanner Tool in Kali Linux | 20 Apr, 2021
PwnXSS is a free and open-source tool available on Github. This tool is specially designed to find cross-site scripting. This tool is written in python. You must have python 3.7 installed in your Kali Linux. There are lots of websites on the internet which are vulnerable to cross-site scripting(XSS). This tool makes finding cross-site scripting easy. This tool works as a scanner. The Internet has millions of websites and web apps a question comes into mind whether your website is safe or not. Security of our websites plays an important role. Cross-site scripting or XSS is a vulnerability that can be used to hack websites. This tool helps to find such vulnerability easily.
Features of PwnXSS:
PwnXSS is a multiprocessing support tool,.
PwnXSS is a customizable tool, You can customize it.
PwnXSS supports all types of request POST and GET.
PwnXSS has a feature of error handling. If any error occurred during scanning it can handle easily.
PwnXSS is free and open source tool.
PwnXSS is written in python language.
Uses of PwnXSS:
PwnXSS is used to find cross-site scripting vulnerability in websites and webapps.
It’s an open-source tool just download it and run it to find cross-site scripting vulnerability.
This tool is available on GitHub install and starts scanning websites.
PwnXSS makes it easy to scan websites for xss.
This tool works like a scanner.
Step 1: Open your Kali Linux terminal and move to Desktop using the following command.
cd Desktop
Step 2: You are on Desktop now create a new directory called pwnxss using the following command. In this directory installation of the pwnxss tool will be done.
mkdir pwnxss
Step 3: Now move to this directory using the following command.
cd pwnxss
Step 4: You have to install the first basic requirement using the following command.
pip3 install bs4
Step 5: You have to install the second basic requirement using the following command.
pip3 install requests
Step 6: Now you have to install the tool. This means you have to clone the tool from github using the following command.
git clone https://github.com/pwn0sec/PwnXSS
Step 7: The tool has been downloaded in the pwnxss directory. To list out the contents of the tool use the following command.
ls
Step 8: You can see that a new directory of the pwnxss tool has been generated while we were downloading the tool. Move to this directory using the following command.
cd PwnXSS
Step 9: To list out the content of the tool use the following command.
ls
Step 10: You can see different files of the tool here. Now you have to give permission to the tool using the following command.
chmod 755 -R PwnXSS
Step 11: Use the following command is used to see the help index of the tool.
python3 pwnxss.py --help
The tool has been downloaded successfully using this tool you can easily check the cross-site scripting vulnerabilities of the websites and webapps. Now here are some examples to use the PwnXSS tool.
Example: python3 pwnxss.py -u http://testphp.vulnweb.com
python3 pwnxss.py -u http://testphp.vulnweb.com
The tool has started checking cross-site scripting vulnerability. These are the vulnerability that the tool has detected. The tool keeps checking the website again and again when found a vulnerable website it will show you on the terminal.
Cyber-security
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
'crontab' in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 709,
"s": 28,
"text": "PwnXSS is a free and open-source tool available on Github. This tool is specially designed to find cross-site scripting. This tool is written in python. You must have python 3.7 installed in your Kali Linux. There are lots of websites on the internet which are vulnerable to cross-site scripting(XSS). This tool makes finding cross-site scripting easy. This tool works as a scanner. The Internet has millions of websites and web apps a question comes into mind whether your website is safe or not. Security of our websites plays an important role. Cross-site scripting or XSS is a vulnerability that can be used to hack websites. This tool helps to find such vulnerability easily."
},
{
"code": null,
"e": 729,
"s": 709,
"text": "Features of PwnXSS:"
},
{
"code": null,
"e": 772,
"s": 729,
"text": "PwnXSS is a multiprocessing support tool,."
},
{
"code": null,
"e": 825,
"s": 772,
"text": "PwnXSS is a customizable tool, You can customize it."
},
{
"code": null,
"e": 876,
"s": 825,
"text": "PwnXSS supports all types of request POST and GET."
},
{
"code": null,
"e": 976,
"s": 876,
"text": "PwnXSS has a feature of error handling. If any error occurred during scanning it can handle easily."
},
{
"code": null,
"e": 1013,
"s": 976,
"text": "PwnXSS is free and open source tool."
},
{
"code": null,
"e": 1051,
"s": 1013,
"text": "PwnXSS is written in python language."
},
{
"code": null,
"e": 1067,
"s": 1051,
"text": "Uses of PwnXSS:"
},
{
"code": null,
"e": 1150,
"s": 1067,
"text": "PwnXSS is used to find cross-site scripting vulnerability in websites and webapps."
},
{
"code": null,
"e": 1247,
"s": 1150,
"text": "It’s an open-source tool just download it and run it to find cross-site scripting vulnerability."
},
{
"code": null,
"e": 1318,
"s": 1247,
"text": "This tool is available on GitHub install and starts scanning websites."
},
{
"code": null,
"e": 1365,
"s": 1318,
"text": "PwnXSS makes it easy to scan websites for xss."
},
{
"code": null,
"e": 1397,
"s": 1365,
"text": "This tool works like a scanner."
},
{
"code": null,
"e": 1485,
"s": 1397,
"text": "Step 1: Open your Kali Linux terminal and move to Desktop using the following command. "
},
{
"code": null,
"e": 1496,
"s": 1485,
"text": "cd Desktop"
},
{
"code": null,
"e": 1657,
"s": 1496,
"text": "Step 2: You are on Desktop now create a new directory called pwnxss using the following command. In this directory installation of the pwnxss tool will be done."
},
{
"code": null,
"e": 1670,
"s": 1657,
"text": "mkdir pwnxss"
},
{
"code": null,
"e": 1734,
"s": 1670,
"text": "Step 3: Now move to this directory using the following command."
},
{
"code": null,
"e": 1744,
"s": 1734,
"text": "cd pwnxss"
},
{
"code": null,
"e": 1829,
"s": 1744,
"text": "Step 4: You have to install the first basic requirement using the following command."
},
{
"code": null,
"e": 1846,
"s": 1829,
"text": "pip3 install bs4"
},
{
"code": null,
"e": 1932,
"s": 1846,
"text": "Step 5: You have to install the second basic requirement using the following command."
},
{
"code": null,
"e": 1954,
"s": 1932,
"text": "pip3 install requests"
},
{
"code": null,
"e": 2075,
"s": 1954,
"text": "Step 6: Now you have to install the tool. This means you have to clone the tool from github using the following command."
},
{
"code": null,
"e": 2119,
"s": 2075,
"text": "git clone https://github.com/pwn0sec/PwnXSS"
},
{
"code": null,
"e": 2245,
"s": 2119,
"text": "Step 7: The tool has been downloaded in the pwnxss directory. To list out the contents of the tool use the following command."
},
{
"code": null,
"e": 2248,
"s": 2245,
"text": "ls"
},
{
"code": null,
"e": 2415,
"s": 2248,
"text": "Step 8: You can see that a new directory of the pwnxss tool has been generated while we were downloading the tool. Move to this directory using the following command."
},
{
"code": null,
"e": 2425,
"s": 2415,
"text": "cd PwnXSS"
},
{
"code": null,
"e": 2496,
"s": 2425,
"text": "Step 9: To list out the content of the tool use the following command."
},
{
"code": null,
"e": 2499,
"s": 2496,
"text": "ls"
},
{
"code": null,
"e": 2627,
"s": 2499,
"text": "Step 10: You can see different files of the tool here. Now you have to give permission to the tool using the following command."
},
{
"code": null,
"e": 2647,
"s": 2627,
"text": "chmod 755 -R PwnXSS"
},
{
"code": null,
"e": 2725,
"s": 2647,
"text": "Step 11: Use the following command is used to see the help index of the tool."
},
{
"code": null,
"e": 2751,
"s": 2725,
"text": "python3 pwnxss.py --help "
},
{
"code": null,
"e": 2951,
"s": 2751,
"text": "The tool has been downloaded successfully using this tool you can easily check the cross-site scripting vulnerabilities of the websites and webapps. Now here are some examples to use the PwnXSS tool."
},
{
"code": null,
"e": 3008,
"s": 2951,
"text": "Example: python3 pwnxss.py -u http://testphp.vulnweb.com"
},
{
"code": null,
"e": 3056,
"s": 3008,
"text": "python3 pwnxss.py -u http://testphp.vulnweb.com"
},
{
"code": null,
"e": 3296,
"s": 3056,
"text": "The tool has started checking cross-site scripting vulnerability. These are the vulnerability that the tool has detected. The tool keeps checking the website again and again when found a vulnerable website it will show you on the terminal."
},
{
"code": null,
"e": 3311,
"s": 3296,
"text": "Cyber-security"
},
{
"code": null,
"e": 3322,
"s": 3311,
"text": "Kali-Linux"
},
{
"code": null,
"e": 3334,
"s": 3322,
"text": "Linux-Tools"
},
{
"code": null,
"e": 3345,
"s": 3334,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3443,
"s": 3345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3478,
"s": 3443,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 3513,
"s": 3478,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 3549,
"s": 3513,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 3590,
"s": 3549,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 3623,
"s": 3590,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 3659,
"s": 3623,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 3697,
"s": 3659,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 3735,
"s": 3697,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 3761,
"s": 3735,
"text": "Docker - COPY Instruction"
}
] |
SQL Query to Filter a Table using Another Table | 28 Oct, 2021
In this article, we will see, how to filter a table using another table. We can perform the function by using a subquery in place of the condition in WHERE Clause. A query inside another query is called subquery. It can also be called a nested query. One SQL code can have one or more than one nested query.
Syntax:
SELECT * FROM table_name WHERE
column_name=( SELECT column_name FROM table_name);
Query written after the WHERE clause is the subquery in above syntax.
Now, for the demonstration follow the below steps:
Step 1: Create a database
we can use the following command to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Use database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have two tables named ‘demo_table1’ and ‘demo_table2’ in our geek’s database.
Query(demo_table1):
CREATE TABLE demo_table1(
NAME VARCHAR(20),
AGE int,
CITY VARCHAR(10),
INCOME int);
Query(demo_table2):
CREATE TABLE demo_table2(
NAME VARCHAR(20),
AGE int,
INCOME int);
Step 4: Insert data into a table
Query (demo_table1):
INSERT INTO demo_table1 VALUES
('Romy',23,'Delhi',400000),
('Pushkar',23,'Delhi',700000),
('Nikhil',24,'Punjab',350000),
('Rinkle',23,'Punjab',600000),
('Samiksha',23,'Banglore',800000),
('Ashtha',24,'Banglore',300000),
('Satish',30,'Patna',450000),
('Girish',30,'Patna',5500000),
('Ram', 20 , 'Patna',650000),
('Raj', 12, 'Delhi',380000);
Query(demo_table2):
INSERT INTO demo_table2 VALUES
('Fanny',25,600000 ),
('Prem', 30,450000),
('Preeti',21,250000 ),
('Samita',32,440000),
('Ozymandias',34,650000);
Step 5: View the content of the table.
Execute the below query to see the content of the table.
Query:
SELECT * FROM demo_table1;
Output:
Query:
SELECT * FROM demo_table2;
Output:
Step 6: Filter table using another table
For the demonstration, we will filter demo_table1 data whose INCOME is greater than maximum INCOME in semo_table2.
To get the maximum salary from demo_table2:
Query:
SELECT MAX(INCOME) FROM demo_table2;
Above query used will be used as subquery to filter the demo_table1.
Final Query:
SELECT * FROM demo_table WHERE INCOME > (SELECT MAX(INCOME) FROM demo_table2);
Output:
From image you can see that data from demo_table1 is filtered out having INCOME more than the 650000 (maximum income value in demo_table2 ).
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 336,
"s": 28,
"text": "In this article, we will see, how to filter a table using another table. We can perform the function by using a subquery in place of the condition in WHERE Clause. A query inside another query is called subquery. It can also be called a nested query. One SQL code can have one or more than one nested query."
},
{
"code": null,
"e": 344,
"s": 336,
"text": "Syntax:"
},
{
"code": null,
"e": 426,
"s": 344,
"text": "SELECT * FROM table_name WHERE\ncolumn_name=( SELECT column_name FROM table_name);"
},
{
"code": null,
"e": 496,
"s": 426,
"text": "Query written after the WHERE clause is the subquery in above syntax."
},
{
"code": null,
"e": 547,
"s": 496,
"text": "Now, for the demonstration follow the below steps:"
},
{
"code": null,
"e": 573,
"s": 547,
"text": "Step 1: Create a database"
},
{
"code": null,
"e": 641,
"s": 573,
"text": "we can use the following command to create a database called geeks."
},
{
"code": null,
"e": 648,
"s": 641,
"text": "Query:"
},
{
"code": null,
"e": 671,
"s": 648,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 692,
"s": 671,
"text": "Step 2: Use database"
},
{
"code": null,
"e": 761,
"s": 692,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 768,
"s": 761,
"text": "Query:"
},
{
"code": null,
"e": 779,
"s": 768,
"text": "USE geeks;"
},
{
"code": null,
"e": 804,
"s": 779,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 885,
"s": 804,
"text": "We have two tables named ‘demo_table1’ and ‘demo_table2’ in our geek’s database."
},
{
"code": null,
"e": 905,
"s": 885,
"text": "Query(demo_table1):"
},
{
"code": null,
"e": 989,
"s": 905,
"text": "CREATE TABLE demo_table1(\nNAME VARCHAR(20),\nAGE int,\nCITY VARCHAR(10),\nINCOME int);"
},
{
"code": null,
"e": 1009,
"s": 989,
"text": "Query(demo_table2):"
},
{
"code": null,
"e": 1075,
"s": 1009,
"text": "CREATE TABLE demo_table2(\nNAME VARCHAR(20),\nAGE int,\nINCOME int);"
},
{
"code": null,
"e": 1108,
"s": 1075,
"text": "Step 4: Insert data into a table"
},
{
"code": null,
"e": 1129,
"s": 1108,
"text": "Query (demo_table1):"
},
{
"code": null,
"e": 1469,
"s": 1129,
"text": "INSERT INTO demo_table1 VALUES\n('Romy',23,'Delhi',400000),\n('Pushkar',23,'Delhi',700000),\n('Nikhil',24,'Punjab',350000),\n('Rinkle',23,'Punjab',600000),\n('Samiksha',23,'Banglore',800000),\n('Ashtha',24,'Banglore',300000),\n('Satish',30,'Patna',450000),\n('Girish',30,'Patna',5500000),\n('Ram', 20 , 'Patna',650000),\n('Raj', 12, 'Delhi',380000);"
},
{
"code": null,
"e": 1489,
"s": 1469,
"text": "Query(demo_table2):"
},
{
"code": null,
"e": 1634,
"s": 1489,
"text": "INSERT INTO demo_table2 VALUES\n('Fanny',25,600000 ),\n('Prem', 30,450000),\n('Preeti',21,250000 ),\n('Samita',32,440000),\n('Ozymandias',34,650000);"
},
{
"code": null,
"e": 1673,
"s": 1634,
"text": "Step 5: View the content of the table."
},
{
"code": null,
"e": 1730,
"s": 1673,
"text": "Execute the below query to see the content of the table."
},
{
"code": null,
"e": 1737,
"s": 1730,
"text": "Query:"
},
{
"code": null,
"e": 1764,
"s": 1737,
"text": "SELECT * FROM demo_table1;"
},
{
"code": null,
"e": 1772,
"s": 1764,
"text": "Output:"
},
{
"code": null,
"e": 1779,
"s": 1772,
"text": "Query:"
},
{
"code": null,
"e": 1806,
"s": 1779,
"text": "SELECT * FROM demo_table2;"
},
{
"code": null,
"e": 1814,
"s": 1806,
"text": "Output:"
},
{
"code": null,
"e": 1855,
"s": 1814,
"text": "Step 6: Filter table using another table"
},
{
"code": null,
"e": 1970,
"s": 1855,
"text": "For the demonstration, we will filter demo_table1 data whose INCOME is greater than maximum INCOME in semo_table2."
},
{
"code": null,
"e": 2015,
"s": 1970,
"text": " To get the maximum salary from demo_table2:"
},
{
"code": null,
"e": 2022,
"s": 2015,
"text": "Query:"
},
{
"code": null,
"e": 2059,
"s": 2022,
"text": "SELECT MAX(INCOME) FROM demo_table2;"
},
{
"code": null,
"e": 2128,
"s": 2059,
"text": "Above query used will be used as subquery to filter the demo_table1."
},
{
"code": null,
"e": 2141,
"s": 2128,
"text": "Final Query:"
},
{
"code": null,
"e": 2220,
"s": 2141,
"text": "SELECT * FROM demo_table WHERE INCOME > (SELECT MAX(INCOME) FROM demo_table2);"
},
{
"code": null,
"e": 2228,
"s": 2220,
"text": "Output:"
},
{
"code": null,
"e": 2369,
"s": 2228,
"text": "From image you can see that data from demo_table1 is filtered out having INCOME more than the 650000 (maximum income value in demo_table2 )."
},
{
"code": null,
"e": 2376,
"s": 2369,
"text": "Picked"
},
{
"code": null,
"e": 2386,
"s": 2376,
"text": "SQL-Query"
},
{
"code": null,
"e": 2397,
"s": 2386,
"text": "SQL-Server"
},
{
"code": null,
"e": 2401,
"s": 2397,
"text": "SQL"
},
{
"code": null,
"e": 2405,
"s": 2401,
"text": "SQL"
},
{
"code": null,
"e": 2503,
"s": 2405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2569,
"s": 2503,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2602,
"s": 2569,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2626,
"s": 2602,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2658,
"s": 2626,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2675,
"s": 2658,
"text": "SQL using Python"
},
{
"code": null,
"e": 2753,
"s": 2675,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2789,
"s": 2753,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2819,
"s": 2789,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2850,
"s": 2819,
"text": "SQL Query to Compare Two Dates"
}
] |
Run Scrapy code from Jupyter Notebook without issues | by Tamjid Ahsan | Towards Data Science | Scrapy is an open-source framework for extracting the data from websites. It is fast, simple, and extensible. Every data scientist should have familiarity with this, as they often need to gather data in this manner. Data scientists usually prefer some sort of computational notebook for managing their workflow. Jupyter Notebook is very popular amid data scientists among other options like PyCharm, zeppelin, VS Code, nteract, Google Colab, and spyder to name a few.
Scraping using Scrapy is done with a .py file often. It can be also initialized from a Notebook. The problem with that is, it throws an error `ReactorNotRestartable:` when the code block is run for the second time.
There is a work-around for this error using crochet package. ReactorNotRestartable error can be mitigated using this package. In this blog post, I am showing the steps that I took to run scrapy codes from Jupyter Notebook with out the error.
Prerequisites:
scrapy : pip install scrapy
crochet : pip install crochet
Any Notebook for python, I am using Jupyter Notebook : pip install notebook
Demo Project:
For demoing the steps, I am scraping wikiquote for quotes by Maynard James Keenan, an American rock singer, and saving the info as a .csv file, which will be overwritten every time the script is run, this is useful for a fresh start of the project. This is achieved using the custom settings and passing a nested dictionary with FEEDS as key and a dictionary with name of the output file as key and values containing different settings for the feed.
To initialize the process I run following code:
process = CrawlerProcess()process.crawl(QuotesToCsv)process.start()
It runs without issue for the first time and saves the csv file at the root, but throws following error from the next time onwards.
To run the code without issue again, the kernel must be restarted. Now with the use of crochet, this code can be used in a Jupyter Notebook without issue.
Now, I call this function to run the codes without issue.
run_spider()
Now let me go through the differences between those two approaches:
Using CrawlerRunner instead of CrawlerProcess .Importing setup and wait_for from crochet and initializing using setup() .Using @wait_for(10) decorator on the function that runs the spider from scrapy. @wait_for is used for blocking calls into Twisted Reactor thread. Click here to learn more about this.
Using CrawlerRunner instead of CrawlerProcess .
Importing setup and wait_for from crochet and initializing using setup() .
Using @wait_for(10) decorator on the function that runs the spider from scrapy. @wait_for is used for blocking calls into Twisted Reactor thread. Click here to learn more about this.
Voila! No more error. The script runs and saves output as quotes.csv .
This can also be done from a .py from Jupyter Notebook using !python scrape_webpage.py , if the file contains the script. Being said that, it is convenient to develop code from a Notebook. Also, one caveat of this approach is that there is way less log if using CrawlerRunner instead of CrawlerProcess .
Here is the GitHub repo of all the codes and notebooks that I used to test out my workflow.
Until next time!!! | [
{
"code": null,
"e": 640,
"s": 172,
"text": "Scrapy is an open-source framework for extracting the data from websites. It is fast, simple, and extensible. Every data scientist should have familiarity with this, as they often need to gather data in this manner. Data scientists usually prefer some sort of computational notebook for managing their workflow. Jupyter Notebook is very popular amid data scientists among other options like PyCharm, zeppelin, VS Code, nteract, Google Colab, and spyder to name a few."
},
{
"code": null,
"e": 855,
"s": 640,
"text": "Scraping using Scrapy is done with a .py file often. It can be also initialized from a Notebook. The problem with that is, it throws an error `ReactorNotRestartable:` when the code block is run for the second time."
},
{
"code": null,
"e": 1097,
"s": 855,
"text": "There is a work-around for this error using crochet package. ReactorNotRestartable error can be mitigated using this package. In this blog post, I am showing the steps that I took to run scrapy codes from Jupyter Notebook with out the error."
},
{
"code": null,
"e": 1112,
"s": 1097,
"text": "Prerequisites:"
},
{
"code": null,
"e": 1140,
"s": 1112,
"text": "scrapy : pip install scrapy"
},
{
"code": null,
"e": 1170,
"s": 1140,
"text": "crochet : pip install crochet"
},
{
"code": null,
"e": 1246,
"s": 1170,
"text": "Any Notebook for python, I am using Jupyter Notebook : pip install notebook"
},
{
"code": null,
"e": 1260,
"s": 1246,
"text": "Demo Project:"
},
{
"code": null,
"e": 1710,
"s": 1260,
"text": "For demoing the steps, I am scraping wikiquote for quotes by Maynard James Keenan, an American rock singer, and saving the info as a .csv file, which will be overwritten every time the script is run, this is useful for a fresh start of the project. This is achieved using the custom settings and passing a nested dictionary with FEEDS as key and a dictionary with name of the output file as key and values containing different settings for the feed."
},
{
"code": null,
"e": 1758,
"s": 1710,
"text": "To initialize the process I run following code:"
},
{
"code": null,
"e": 1826,
"s": 1758,
"text": "process = CrawlerProcess()process.crawl(QuotesToCsv)process.start()"
},
{
"code": null,
"e": 1958,
"s": 1826,
"text": "It runs without issue for the first time and saves the csv file at the root, but throws following error from the next time onwards."
},
{
"code": null,
"e": 2113,
"s": 1958,
"text": "To run the code without issue again, the kernel must be restarted. Now with the use of crochet, this code can be used in a Jupyter Notebook without issue."
},
{
"code": null,
"e": 2171,
"s": 2113,
"text": "Now, I call this function to run the codes without issue."
},
{
"code": null,
"e": 2184,
"s": 2171,
"text": "run_spider()"
},
{
"code": null,
"e": 2252,
"s": 2184,
"text": "Now let me go through the differences between those two approaches:"
},
{
"code": null,
"e": 2556,
"s": 2252,
"text": "Using CrawlerRunner instead of CrawlerProcess .Importing setup and wait_for from crochet and initializing using setup() .Using @wait_for(10) decorator on the function that runs the spider from scrapy. @wait_for is used for blocking calls into Twisted Reactor thread. Click here to learn more about this."
},
{
"code": null,
"e": 2604,
"s": 2556,
"text": "Using CrawlerRunner instead of CrawlerProcess ."
},
{
"code": null,
"e": 2679,
"s": 2604,
"text": "Importing setup and wait_for from crochet and initializing using setup() ."
},
{
"code": null,
"e": 2862,
"s": 2679,
"text": "Using @wait_for(10) decorator on the function that runs the spider from scrapy. @wait_for is used for blocking calls into Twisted Reactor thread. Click here to learn more about this."
},
{
"code": null,
"e": 2933,
"s": 2862,
"text": "Voila! No more error. The script runs and saves output as quotes.csv ."
},
{
"code": null,
"e": 3237,
"s": 2933,
"text": "This can also be done from a .py from Jupyter Notebook using !python scrape_webpage.py , if the file contains the script. Being said that, it is convenient to develop code from a Notebook. Also, one caveat of this approach is that there is way less log if using CrawlerRunner instead of CrawlerProcess ."
},
{
"code": null,
"e": 3329,
"s": 3237,
"text": "Here is the GitHub repo of all the codes and notebooks that I used to test out my workflow."
}
] |
Using Workflow Sets to Screen and Compare Model-Recipe Combinations for Bank Loan Classification | by Murray Gillin | Towards Data Science | Consider you are a data scientist at a large bank, and your CDO has instructed you to develop a means of automating bank loan decisions. You decide that this should be a binary classifier and proceed to collect several hundred data points. But what kind of model should you start off and what sort of feature engineering should you complete? Why not screen multiple combinations?
This project will use the loan prediction data set to exemplify the use of workflow_sets() within the Tidymodels machine learning ecosystem. Screening a series of models and feature engineering pipelines are important to avoid any internal bias towards a particular model type, or the “No Free Lunch” theorem. If you’re interested in learning more about the Tidymodels ecosystem before reading, please check out my previous article.
Loan Prediction Data has been taken from https://datahack.analyticsvidhya.com/contest/practice-problem-loan-prediction-iii/.
Load Packages and Data
library(tidymodels) #ML meta packageslibrary(themis) #Recipe functions to deal with class imbalanceslibrary(discrim) #Naive Bayes Modelslibrary(tidyposterior) #Bayesian Performance Comparisonlibrary(corrr) #Correlation Vizlibrary(readr) #Read Tabular Datalibrary(magrittr) #Pipe Operatorslibrary(stringr) #Work with Stringslibrary(forcats) #Work with Factorslibrary(skimr) #Data Summarylibrary(patchwork) #ggplot gridslibrary(GGally) #Scatterplot Matricestrain <- read_csv("train_ctrUa4K.csv")train %<>% rename(Applicant_Income = ApplicantIncome, CoApplicant_Income = CoapplicantIncome, Loan_Amount = LoanAmount)
Exploratory Data Analysis
Before we start screening models, complete our due diligence with some basic exploratory data analysis.
We use the skimr package to produce the below output
skim(train)
Furthermore, we can visualise these results with appropriate visualisations using the following function.
#Automated Exploratory Data Analysisviz_by_dtype <- function (x,y) { title <- str_replace_all(y,"_"," ") %>% str_to_title() if ("factor" %in% class(x)) { ggplot(train, aes(x, fill = x)) + geom_bar() + theme(legend.position = "none", axis.text.x = element_text(angle = 45, hjust = 1), axis.text = element_text(size = 8)) + theme_minimal() + scale_fill_viridis_c()+ labs(title = title, y = "", x = "") } else if ("numeric" %in% class(x)) { ggplot(train, aes(x)) + geom_histogram() + theme_minimal() + scale_fill_viridis_c()+ labs(title = title, y = "", x = "") } else if ("integer" %in% class(x)) { ggplot(train, aes(x)) + geom_histogram() + theme_minimal() + scale_fill_viridis_c()+ labs(title = title, y = "", x = "") } else if ("character" %in% class(x)) { ggplot(train, aes(x, fill = x)) + geom_bar() + theme_minimal() + scale_fill_viridis_d()+ theme(legend.position = "none", axis.text.x = element_text(angle = 45, hjust = 1), axis.text = element_text(size = 8)) + labs(title = title, y ="", x= "") }}variable_plot <- map2(train, colnames(train), viz_by_dtype) %>% wrap_plots(ncol = 3, nrow = 5)
Gender imbalance, high proportion of male applicants, with NAs present
Marital Status, almost 3:2 married applicants to unmarried, with NAs present
Majority of applicants do not have children
Majority of applicants are university graduates
Majority are not self-employed
Applicant Income is right skewed
Co-applicant Income is right skewed
Loan Amount is right skewed
Loan Amount Term is generally 360 days
Majority of applicants have a credit history, with NAs present
Mix of Property Area Types
Majority of applications had their application approved, target variable Loan Status is imbalanced 3:2
Bivariate Data Analysis
Quantitative Variables
Using GGally::ggpairs(), we generate a variable matrix plot for all numeric variables and coloured by Loan_Status.
#Correlation Matrix Plotggpairs(train %>% select(7:10,13), ggplot2::aes(color = Loan_Status, alpha = 0.3)) + theme_minimal() + scale_fill_viridis_d(aesthetics = c("color", "fill"), begin = 0.15, end = 0.85) + labs(title = "Numeric Bivariate Analysis of Loan Data")
Qualitative Variables
The below visualisation was generated iteratively using a summary dataframe generated as below, changing the desired character variable.
#Generate Summary Variables for Qualitative Variablessummary_train <- train %>% select(where(is.character), -Loan_ID) %>% drop_na() %>% mutate(Loan_Status = if_else(Loan_Status == "Y",1,0)) %>% pivot_longer(1:6, names_to = "Variables", values_to = "Values") %>% group_by(Variables, Values) %>% summarise(mean = mean(Loan_Status), conf_int = 1.96*sd(Loan_Status)/sqrt(n())) %>% pivot_wider(names_from = Variables, values_from = Values)summary_train %>% select(Married, mean, conf_int) %>% drop_na() %>% ggplot(aes(x=Married, y = mean, color = Married)) + geom_point() + geom_errorbar(aes(ymin = mean - conf_int, ymax = mean + conf_int), width = 0.1) + theme_minimal() + theme(legend.position = "none", axis.title.x = element_blank(), axis.title.y = element_blank()) + scale_colour_viridis_d(aesthetics = c("color", "fill"), begin = 0.15, end = 0.85) + labs(title="Married")
The benefit of having completed a visualisation as above is that it gives an understanding of the magnitude of difference of loan application success as well as the uncertainty, visualised by the 95% confidence intervals for each categorical variable. From this we note the following:
Married applicants tend to have a greater chance of their application being approved.
Graduate applicants have a greater chance of success, maybe because of more stable/higher incomes.
Similarly, there is far greater variation in the success of applicants who work for themselves, likely because of variation in income stability
Number of children doesn’t appear to have a great impact on loan status
Female customers have a much greater variability in the success of the application, male customers is more discrete. We need to be careful of this so as to not create ingrained bias’ in the algorithm.
Semiurban, or Suburban has the highest success proportion.
Lastly, there is a significant difference in success rates between customers with and without a Credit History.
If we wanted to, we could explore these relationships further with ANOVA/Chi Squared testing.
Data Splitting — rsamples
We’ve split the data 80:20, stratified by Loan_Status. Each split tibble can be accessed by calling training() or testing() on the mc_split object.
#Split Data for Testing and Trainingset.seed(101)loan_split <- initial_split(train, prop = 0.8, strata = Loan_Status)
Model Development — parsnip.
As noted above, we want to screen an array of models and hone in on a couple that would be good candidates. Below we’ve initialised a series of standard classification models.
#Initialise Seven Models for Screeningnb_loan <- naive_Bayes(smoothness = tune(), Laplace = tune()) %>% set_engine("klaR") %>% set_mode("classification")logistic_loan <- logistic_reg(penalty = tune(), mixture = tune()) %>% set_engine("glmnet") %>% set_mode("classification")dt_loan <- decision_tree(cost_complexity = tune(), tree_depth = tune(), min_n = tune()) %>% set_engine("rpart") %>% set_mode("classification")rf_loan <- rand_forest(mtry = tune(), trees = tune(), min_n = tune()) %>% set_engine("ranger") %>% set_mode("classification")knn_loan <- nearest_neighbor(neighbors = tune(), weight_func = tune(), dist_power = tune()) %>% set_engine("kknn") %>% set_mode("classification")svm_loan <- svm_rbf(cost = tune(), rbf_sigma = tune(), margin = tune()) %>% set_engine("kernlab") %>% set_mode("classification")xgboost_loan <- boost_tree(mtry = tune(), trees = tune(), min_n = tune(), tree_depth = tune(), learn_rate = tune(), loss_reduction = tune(), sample_size = tune()) %>% set_engine("xgboost") %>% set_mode("classification")
Feature Engineering — recipes
The below is a series of recipe configurations. How will the two different imputation methods compare against one and other, in the below note we’ve used impute_mean (for numeric), impute_mode (for character) or use impute_bag (imputation using bagged trees) which can impute both numeric and character variables.
Note with Credit_History we’ve elected not to impute this value, instead, allocated three results to an integer value, setting unknown instances to 0.
As Loan_Status is imbalanced, we’ve applied SMOTE (Synthetic Minority Overs-Sampling Technique) to recipe 2 and 4. We’ll complete workflow comparison to understand any difference in accuracy between the imputation strategies.
#Initialise Four Recipesrecipe_1 <- recipe(Loan_Status ~., data = training(loan_split)) %>% step_rm(Loan_ID) %>% step_mutate(Credit_History = if_else(Credit_History == 1, 1, -1,0)) %>% step_scale(all_numeric_predictors(), -Credit_History) %>% step_impute_bag(Gender, Married, Dependents, Self_Employed, Loan_Amount, Loan_Amount_Term) %>% step_dummy(all_nominal_predictors())recipe_2 <- recipe(Loan_Status ~., data = training(loan_split)) %>% step_rm(Loan_ID) %>% step_mutate(Credit_History = if_else(Credit_History == 1, 1, -1,0)) %>% step_scale(all_numeric_predictors(), -Credit_History) %>% step_impute_bag(Gender, Married, Dependents, Self_Employed, Loan_Amount, Loan_Amount_Term) %>% step_dummy(all_nominal_predictors()) %>% step_smote(Loan_Status) recipe_3 <- recipe(Loan_Status ~., data = training(loan_split)) %>% step_rm(Loan_ID) %>% step_mutate(Credit_History = if_else(Credit_History == 1, 1, -1,0)) %>% step_scale(all_numeric_predictors(), -Credit_History) %>% step_impute_mean(all_numeric_predictors()) %>% step_impute_mode(all_nominal_predictors()) %>% step_dummy(all_nominal_predictors()) %>% step_zv(all_predictors())recipe_4 <- recipe(Loan_Status ~., data = training(loan_split)) %>% step_rm(Loan_ID) %>% step_mutate(Credit_History = if_else(Credit_History == 1, 1, -1,0)) %>% step_scale(all_numeric_predictors(), -Credit_History) %>% step_impute_mean(all_numeric_predictors()) %>% step_impute_mode(all_nominal_predictors()) %>% step_dummy(all_nominal_predictors()) %>% step_zv(all_predictors()) %>% step_smote(Loan_Status)
Taking recipe_1, we can prepare both the training and test datasets per the transformations.
#Prep and Bake Training and Test Datasetsloan_train <- recipe_1 %>% prep() %>% bake(new_data = NULL)loan_test <- recipe_1 %>% prep() %>% bake(testing(loan_split))
Then take these transformed datasets and visualise variable correlation.
#Generate Correlation Visualisationloan_train %>% bind_rows(loan_test) %>% mutate(Loan_Status = if_else(Loan_Status == "Y",1,0)) %>% correlate() %>% rearrange() %>% shave() %>% rplot(print_cor = T,.order = "alphabet") + theme_minimal() + theme(axis.text.x = element_text(angle = 90)) + scale_color_viridis_c() + labs(title = "Correlation Plot for Trained Loan Dataset")
From the above we note a strong relationship between Loan_Status and whether an applicant has a Credit_History. This makes sense, bank’s are more inclined to give loans to customers with a credit history, evidence positive or otherwise of a customers ability to repay the loan.
Iterating Parnsip and Recipe Combinations — Workflow Sets
Workflow Sets enables us to screen all possible combinations of recipe and parnsip model specifications. As below, we’ve created two named lists, all models and recipes.
#Generate List of Recipesrecipe_list <- list(Recipe1 = recipe_1, Recipe2 = recipe_2, Recipe3 = recipe_3, Recipe4 = recipe_4)#Generate List of Model Typesmodel_list <- list(Random_Forest = rf_loan, SVM = svm_loan, Naive_Bayes = nb_loan, Decision_Tree = dt_loan, Boosted_Trees = xgboost_loan, KNN = knn_loan, Logistic_Regression = logistic_loan)
Here comes the fun part, creating a series of workflows using workflow_sets()
model_set <- workflow_set(preproc = recipe_list, models = model_list, cross = T)
Setting cross = T instructs workflow_set to create all possible combinations of parsnip model and recipe specification.
set.seed(2)train_resamples <- bootstraps(training(loan_split), strata = Loan_Status)doParallel::registerDoParallel(cores = 12)all_workflows <- model_set %>% workflow_map(resamples = train_resamples, verbose = TRUE)
We’ve initialised a boostraps resampling procedure, this is computationally more demanding, however results in less error overall. Passing the model_set object through to workflow_map, with the resampling procedure will initate a screen of all parsnip-recipe combinations showing an output like this. This is a demanding procedure, and hence why we’ve initiated parrallel compute to ease this along.
Using the resampling procedure, workflow_map will fit each workflow to the training data and compute accuracy on each resample and take the mean. Furthermore, as each of the recipes specifies that the hyperparameters should be tuned, workflow_map will perform some tuning to provide an optimal result.
Once completed, we can call the all_workflows object and collect all the metrics that were calculated in this procedure, and visualise the results.
N.B there is an autoplot() function available for workflow_set objects, however we want to be able to compare recipe and model performance so have had to re-engineer features for visualisation below.
#Visualise Performance Comparison of Workflowscollect_metrics(all_workflows) %>% separate(wflow_id, into = c("Recipe", "Model_Type"), sep = "_", remove = F, extra = "merge") %>% filter(.metric == "accuracy") %>% group_by(wflow_id) %>% filter(mean == max(mean)) %>% group_by(model) %>% select(-.config) %>% distinct() %>% ungroup() %>% mutate(Workflow_Rank = row_number(-mean), .metric = str_to_upper(.metric)) %>% ggplot(aes(x=Workflow_Rank, y = mean, shape = Recipe, color = Model_Type)) + geom_point() + geom_errorbar(aes(ymin = mean-std_err, ymax = mean+std_err)) + theme_minimal()+ scale_colour_viridis_d() + labs(title = "Performance Comparison of Workflow Sets", x = "Workflow Rank", y = "Accuracy", color = "Model Types", shape = "Recipes")
From the above we can observe:
Naive Bayes and KNN models have performed the worst
Tree-Based methods have performed very well
SMOTE has not offered an increase in performance for more complex model types, no change between recipes for decision tree model.
Whilst we’ve made very general first glance observations, given the slight difference in the mean accuracy of say the top 8 workflows, how do we discern which are distinct, or otherwise practically the same?
Post Hoc Analysis of Resampling — tidyposterior
One way to compare models is to examine the resampling results, and ask are the models actually different?The tidyposterior::perf_mod function enables comparisons of all of our workflow combinations by generating a set of posterior distributions, for a given metric, which can then be compared against each other for practical equivalence. Essentially, we can make between-workflow comparisons.
doParallel::registerDoParallel(cores = 12)set.seed(246)acc_model_eval <- perf_mod(all_workflows, metric = "accuracy", iter = 5000)
The results of perf_mod are then passed to tidy() to extract the underlying findings of the posterior analysis. Their distributions are visualised below.
#Extract Results from Posterior Analysis and Visualise Distributionsacc_model_eval %>% tidy() %>% mutate(model = fct_inorder(model)) %>% ggplot(aes(x=posterior)) + geom_histogram(bins = 50) + theme_minimal() + facet_wrap(~model, nrow = 7, ncol = 6) + labs(title = "Comparison of Posterior Distributions of Model Recipe Combinations", x = expression(paste("Posterior for Mean Accuracy")), y = "")
Looking back at our performance comparison, we observe that the two highest rank models are Boosted Trees and Decision Trees with Recipe1, models on the extreme sides of the interpretability scale for tree based models. We can seek to understand further by taking the difference in means of their respective posterior distributions.
Using contrast_models() we can conduct that analysis.
#Compare Two Models - Difference in Meansmod_compare <- contrast_models(acc_model_eval, list_1 = "Recipe1_Decision_Tree", list_2 = "Recipe1_Boosted_Trees")a1 <- mod_compare %>% as_tibble() %>% ggplot(aes(x=difference)) + geom_histogram(bins = 50, col = "white", fill = "#73D055FF")+ geom_vline(xintercept = 0, lty = 2) + theme_minimal()+ scale_fill_viridis_b()+ labs(x= "Posterior for Mean Difference in Accuracy", y="", title = "Posterior Mean Difference Recipe1_Decision_Tree & Recipe3_Boosted_Trees")a2 <- acc_model_eval %>% tidy() %>% mutate(model = fct_inorder(model)) %>% filter(model %in% c("Recipe1_Boosted_Trees", "Recipe1_Decision_Tree")) %>% ggplot(aes(x=posterior)) + geom_histogram(bins = 50, col = "white", fill = "#73D055FF") + theme_minimal()+ scale_colour_viridis_b() + facet_wrap(~model, nrow = 2, ncol = 1) + labs(title = "Comparison of Posterior Distributions of Model Recipe Combinations", x = expression(paste("Posterior for Mean Accuracy")), y = "")a2/a1
Piping the mod_compare object to summary generates the following output
mod_compare %>% summary()mean0.001371989 #Difference in means between posterior distributionsprobability0.5842 #Proportion of Posterior of Mean Difference > 0
As also evidenced by the posterior for mean difference, the mean difference is small between the respective workflow posterior distributions for mean accuracy. 58.4% of the posterior difference of means distribution is above 0, so we can infer that the positive difference is real (albeit slight).
We can investigate further, with the notion of practical equivalence.
summary(mod_compare, size = 0.02)pract_equiv0.9975
The effect size are thresholds on both sides [-0.02, 0.02] of the difference in means posterior distribution, and the pract_equiv measures how much of the diff. in means post. distribution is within these thresholds. For our comparison, Boosted_Trees is 99.75% within the posterior distribution for Decision_Tree.
We can complete this exercise for all workflows as below.
#Pluck and modify underlying tibble from autoplot()autoplot(acc_model_eval, type = "ROPE", size = 0.02) %>% pluck("data") %>% mutate(rank = row_number(-pract_equiv)) %>% arrange(rank) %>% separate(model, into = c("Recipe", "Model_Type"), sep = "_", remove = F, extra = "merge") %>% ggplot(aes(x=rank, y= pract_equiv, color = Model_Type, shape = Recipe)) + geom_point(size = 5) + theme_minimal() + scale_colour_viridis_d() + labs(y= "Practical Equivalance", x = "Workflow Rank", size = "Probability of Practical Equivalence", color = "Model Type", title = "Practical Equivalence of Workflow Sets", subtitle = "Calculated Using an Effect Size of 0.02")
We’ve taken the data that underpins the autoplot object that conducts the ROPE (Region of Practical Equivalence) calculation, so that we can engineer and display more features. In doing so we can easily compare the each of the workflows using Recipe1_Decision_Tree as a benchmark. There are a handful of workflows that would likely perform just as well as Recipe1_Decision_Tree.
The top two candidates, Boosted_Trees and Decision_Tree sit on opposite ends of the interpretability spectrum. Boosted Trees is very much a black-box method, conversely Decision Trees are more easily understood, and in this instance provides the best result, and hence we’ll finalise our workflow on the basis of using Recipe1_Decision_Tree.
#Pull Best Performing Hyperparameter Set From workflow_map Objectbest_result <- all_workflows %>% pull_workflow_set_result("Recipe1_Decision_Tree") %>% select_best(metric = "accuracy")#Finalise Workflow Object With Best Parametersdt_wf <- all_workflows %>% pull_workflow("Recipe1_Decision_Tree") %>% finalize_workflow(best_result)#Fit Workflow Object to Training Data and Predict Using Test Datasetdt_res <- dt_wf %>% fit(training(loan_split)) %>% predict(new_data = testing(loan_split)) %>% bind_cols(loan_test) %>% mutate(.pred_class = fct_infreq(.pred_class), Loan_Status = fct_infreq(Loan_Status))#Calculate Accuracy of Predictionaccuracy(dt_res, truth = Loan_Status, estimate = .pred_class)
Our finalised model has managed to generate a very strong result, 84.68% accurate on the test dataset. Model is generally performing well on predicting approvals for loans that were granted. However model is approving loans that were decided against by the bank. This is a curious case, obviously more loans a bank offers means higher potential for revenue, at a higher risk exposure. This indicates the dataset contains some inconsistencies that the model is not able to fully distinguish and has been ‘confused’ based on observations in the training set.
This presents an argument for model interpretability, in this example we cannot generate more data, so how do we know the basis by which the predictions have been made?
#Fit and Extract Fit from Workflow Objectdt_wf_fit <- dt_wf %>% fit(training(loan_split))dt_fit <- dt_wf_fit %>% pull_workflow_fit()#Generate Decision Tree Plot Using rpart.plot packagerpart.plot::rpart.plot(dt_fit$fit)
As our model is simple enough to visualise and understand, a tree plot suffices.
Immediately we observe that the decision has been based solely on the presence of a Credit History. The model is also erring on the side of providing applicants with an unknown Credit_History (= 0), and denying applicants without one (Credit_History = -1). The inconsistencies noted above are evident, not everyone with a credit history is granted a loan, but it certainly helps.
Conclusion
You return to your CDO and explain your findings. They’re impressed with the accuracy result, but now the business has to weigh up the risk of default permitting applications with unknown credit histories, and the potential revenue that it might otherwise generate.
This article has sought to explain the power of workflow_sets within the Tidymodels ecosystem. Furthermore, we’ve explored the “No Free Lunch” theorem, that no one model can be said to be better or best, and hence why it is best practice to screen many models. The types of models that respond well are also dependant on the feature engineering that is carried out.
Thank you for reading my second publication. If you’re interested in Tidymodels, I published an introductory project explaining each of the core packages when building a regression model.
Would like to acknowledge the wonderful work of Julie Slige and Max Kuhn for their ongoing efforts in developing the Tidymodels ecosystem. Their in-progress book can be viewed https://www.tmwr.org/, which has been instrumental in building my understanding. | [
{
"code": null,
"e": 552,
"s": 172,
"text": "Consider you are a data scientist at a large bank, and your CDO has instructed you to develop a means of automating bank loan decisions. You decide that this should be a binary classifier and proceed to collect several hundred data points. But what kind of model should you start off and what sort of feature engineering should you complete? Why not screen multiple combinations?"
},
{
"code": null,
"e": 985,
"s": 552,
"text": "This project will use the loan prediction data set to exemplify the use of workflow_sets() within the Tidymodels machine learning ecosystem. Screening a series of models and feature engineering pipelines are important to avoid any internal bias towards a particular model type, or the “No Free Lunch” theorem. If you’re interested in learning more about the Tidymodels ecosystem before reading, please check out my previous article."
},
{
"code": null,
"e": 1110,
"s": 985,
"text": "Loan Prediction Data has been taken from https://datahack.analyticsvidhya.com/contest/practice-problem-loan-prediction-iii/."
},
{
"code": null,
"e": 1133,
"s": 1110,
"text": "Load Packages and Data"
},
{
"code": null,
"e": 1781,
"s": 1133,
"text": "library(tidymodels) #ML meta packageslibrary(themis) #Recipe functions to deal with class imbalanceslibrary(discrim) #Naive Bayes Modelslibrary(tidyposterior) #Bayesian Performance Comparisonlibrary(corrr) #Correlation Vizlibrary(readr) #Read Tabular Datalibrary(magrittr) #Pipe Operatorslibrary(stringr) #Work with Stringslibrary(forcats) #Work with Factorslibrary(skimr) #Data Summarylibrary(patchwork) #ggplot gridslibrary(GGally) #Scatterplot Matricestrain <- read_csv(\"train_ctrUa4K.csv\")train %<>% rename(Applicant_Income = ApplicantIncome, CoApplicant_Income = CoapplicantIncome, Loan_Amount = LoanAmount) "
},
{
"code": null,
"e": 1807,
"s": 1781,
"text": "Exploratory Data Analysis"
},
{
"code": null,
"e": 1911,
"s": 1807,
"text": "Before we start screening models, complete our due diligence with some basic exploratory data analysis."
},
{
"code": null,
"e": 1964,
"s": 1911,
"text": "We use the skimr package to produce the below output"
},
{
"code": null,
"e": 1976,
"s": 1964,
"text": "skim(train)"
},
{
"code": null,
"e": 2082,
"s": 1976,
"text": "Furthermore, we can visualise these results with appropriate visualisations using the following function."
},
{
"code": null,
"e": 3363,
"s": 2082,
"text": "#Automated Exploratory Data Analysisviz_by_dtype <- function (x,y) { title <- str_replace_all(y,\"_\",\" \") %>% str_to_title() if (\"factor\" %in% class(x)) { ggplot(train, aes(x, fill = x)) + geom_bar() + theme(legend.position = \"none\", axis.text.x = element_text(angle = 45, hjust = 1), axis.text = element_text(size = 8)) + theme_minimal() + scale_fill_viridis_c()+ labs(title = title, y = \"\", x = \"\") } else if (\"numeric\" %in% class(x)) { ggplot(train, aes(x)) + geom_histogram() + theme_minimal() + scale_fill_viridis_c()+ labs(title = title, y = \"\", x = \"\") } else if (\"integer\" %in% class(x)) { ggplot(train, aes(x)) + geom_histogram() + theme_minimal() + scale_fill_viridis_c()+ labs(title = title, y = \"\", x = \"\") } else if (\"character\" %in% class(x)) { ggplot(train, aes(x, fill = x)) + geom_bar() + theme_minimal() + scale_fill_viridis_d()+ theme(legend.position = \"none\", axis.text.x = element_text(angle = 45, hjust = 1), axis.text = element_text(size = 8)) + labs(title = title, y =\"\", x= \"\") }}variable_plot <- map2(train, colnames(train), viz_by_dtype) %>% wrap_plots(ncol = 3, nrow = 5)"
},
{
"code": null,
"e": 3434,
"s": 3363,
"text": "Gender imbalance, high proportion of male applicants, with NAs present"
},
{
"code": null,
"e": 3511,
"s": 3434,
"text": "Marital Status, almost 3:2 married applicants to unmarried, with NAs present"
},
{
"code": null,
"e": 3555,
"s": 3511,
"text": "Majority of applicants do not have children"
},
{
"code": null,
"e": 3603,
"s": 3555,
"text": "Majority of applicants are university graduates"
},
{
"code": null,
"e": 3634,
"s": 3603,
"text": "Majority are not self-employed"
},
{
"code": null,
"e": 3667,
"s": 3634,
"text": "Applicant Income is right skewed"
},
{
"code": null,
"e": 3703,
"s": 3667,
"text": "Co-applicant Income is right skewed"
},
{
"code": null,
"e": 3731,
"s": 3703,
"text": "Loan Amount is right skewed"
},
{
"code": null,
"e": 3770,
"s": 3731,
"text": "Loan Amount Term is generally 360 days"
},
{
"code": null,
"e": 3833,
"s": 3770,
"text": "Majority of applicants have a credit history, with NAs present"
},
{
"code": null,
"e": 3860,
"s": 3833,
"text": "Mix of Property Area Types"
},
{
"code": null,
"e": 3963,
"s": 3860,
"text": "Majority of applications had their application approved, target variable Loan Status is imbalanced 3:2"
},
{
"code": null,
"e": 3987,
"s": 3963,
"text": "Bivariate Data Analysis"
},
{
"code": null,
"e": 4010,
"s": 3987,
"text": "Quantitative Variables"
},
{
"code": null,
"e": 4125,
"s": 4010,
"text": "Using GGally::ggpairs(), we generate a variable matrix plot for all numeric variables and coloured by Loan_Status."
},
{
"code": null,
"e": 4395,
"s": 4125,
"text": "#Correlation Matrix Plotggpairs(train %>% select(7:10,13), ggplot2::aes(color = Loan_Status, alpha = 0.3)) + theme_minimal() + scale_fill_viridis_d(aesthetics = c(\"color\", \"fill\"), begin = 0.15, end = 0.85) + labs(title = \"Numeric Bivariate Analysis of Loan Data\")"
},
{
"code": null,
"e": 4417,
"s": 4395,
"text": "Qualitative Variables"
},
{
"code": null,
"e": 4554,
"s": 4417,
"text": "The below visualisation was generated iteratively using a summary dataframe generated as below, changing the desired character variable."
},
{
"code": null,
"e": 5490,
"s": 4554,
"text": "#Generate Summary Variables for Qualitative Variablessummary_train <- train %>% select(where(is.character), -Loan_ID) %>% drop_na() %>% mutate(Loan_Status = if_else(Loan_Status == \"Y\",1,0)) %>% pivot_longer(1:6, names_to = \"Variables\", values_to = \"Values\") %>% group_by(Variables, Values) %>% summarise(mean = mean(Loan_Status), conf_int = 1.96*sd(Loan_Status)/sqrt(n())) %>% pivot_wider(names_from = Variables, values_from = Values)summary_train %>% select(Married, mean, conf_int) %>% drop_na() %>% ggplot(aes(x=Married, y = mean, color = Married)) + geom_point() + geom_errorbar(aes(ymin = mean - conf_int, ymax = mean + conf_int), width = 0.1) + theme_minimal() + theme(legend.position = \"none\", axis.title.x = element_blank(), axis.title.y = element_blank()) + scale_colour_viridis_d(aesthetics = c(\"color\", \"fill\"), begin = 0.15, end = 0.85) + labs(title=\"Married\")"
},
{
"code": null,
"e": 5775,
"s": 5490,
"text": "The benefit of having completed a visualisation as above is that it gives an understanding of the magnitude of difference of loan application success as well as the uncertainty, visualised by the 95% confidence intervals for each categorical variable. From this we note the following:"
},
{
"code": null,
"e": 5861,
"s": 5775,
"text": "Married applicants tend to have a greater chance of their application being approved."
},
{
"code": null,
"e": 5960,
"s": 5861,
"text": "Graduate applicants have a greater chance of success, maybe because of more stable/higher incomes."
},
{
"code": null,
"e": 6104,
"s": 5960,
"text": "Similarly, there is far greater variation in the success of applicants who work for themselves, likely because of variation in income stability"
},
{
"code": null,
"e": 6176,
"s": 6104,
"text": "Number of children doesn’t appear to have a great impact on loan status"
},
{
"code": null,
"e": 6377,
"s": 6176,
"text": "Female customers have a much greater variability in the success of the application, male customers is more discrete. We need to be careful of this so as to not create ingrained bias’ in the algorithm."
},
{
"code": null,
"e": 6436,
"s": 6377,
"text": "Semiurban, or Suburban has the highest success proportion."
},
{
"code": null,
"e": 6548,
"s": 6436,
"text": "Lastly, there is a significant difference in success rates between customers with and without a Credit History."
},
{
"code": null,
"e": 6642,
"s": 6548,
"text": "If we wanted to, we could explore these relationships further with ANOVA/Chi Squared testing."
},
{
"code": null,
"e": 6668,
"s": 6642,
"text": "Data Splitting — rsamples"
},
{
"code": null,
"e": 6816,
"s": 6668,
"text": "We’ve split the data 80:20, stratified by Loan_Status. Each split tibble can be accessed by calling training() or testing() on the mc_split object."
},
{
"code": null,
"e": 6934,
"s": 6816,
"text": "#Split Data for Testing and Trainingset.seed(101)loan_split <- initial_split(train, prop = 0.8, strata = Loan_Status)"
},
{
"code": null,
"e": 6963,
"s": 6934,
"text": "Model Development — parsnip."
},
{
"code": null,
"e": 7139,
"s": 6963,
"text": "As noted above, we want to screen an array of models and hone in on a couple that would be good candidates. Below we’ve initialised a series of standard classification models."
},
{
"code": null,
"e": 8210,
"s": 7139,
"text": "#Initialise Seven Models for Screeningnb_loan <- naive_Bayes(smoothness = tune(), Laplace = tune()) %>% set_engine(\"klaR\") %>% set_mode(\"classification\")logistic_loan <- logistic_reg(penalty = tune(), mixture = tune()) %>% set_engine(\"glmnet\") %>% set_mode(\"classification\")dt_loan <- decision_tree(cost_complexity = tune(), tree_depth = tune(), min_n = tune()) %>% set_engine(\"rpart\") %>% set_mode(\"classification\")rf_loan <- rand_forest(mtry = tune(), trees = tune(), min_n = tune()) %>% set_engine(\"ranger\") %>% set_mode(\"classification\")knn_loan <- nearest_neighbor(neighbors = tune(), weight_func = tune(), dist_power = tune()) %>% set_engine(\"kknn\") %>% set_mode(\"classification\")svm_loan <- svm_rbf(cost = tune(), rbf_sigma = tune(), margin = tune()) %>% set_engine(\"kernlab\") %>% set_mode(\"classification\")xgboost_loan <- boost_tree(mtry = tune(), trees = tune(), min_n = tune(), tree_depth = tune(), learn_rate = tune(), loss_reduction = tune(), sample_size = tune()) %>% set_engine(\"xgboost\") %>% set_mode(\"classification\")"
},
{
"code": null,
"e": 8240,
"s": 8210,
"text": "Feature Engineering — recipes"
},
{
"code": null,
"e": 8554,
"s": 8240,
"text": "The below is a series of recipe configurations. How will the two different imputation methods compare against one and other, in the below note we’ve used impute_mean (for numeric), impute_mode (for character) or use impute_bag (imputation using bagged trees) which can impute both numeric and character variables."
},
{
"code": null,
"e": 8705,
"s": 8554,
"text": "Note with Credit_History we’ve elected not to impute this value, instead, allocated three results to an integer value, setting unknown instances to 0."
},
{
"code": null,
"e": 8931,
"s": 8705,
"text": "As Loan_Status is imbalanced, we’ve applied SMOTE (Synthetic Minority Overs-Sampling Technique) to recipe 2 and 4. We’ll complete workflow comparison to understand any difference in accuracy between the imputation strategies."
},
{
"code": null,
"e": 10709,
"s": 8931,
"text": "#Initialise Four Recipesrecipe_1 <- recipe(Loan_Status ~., data = training(loan_split)) %>% step_rm(Loan_ID) %>% step_mutate(Credit_History = if_else(Credit_History == 1, 1, -1,0)) %>% step_scale(all_numeric_predictors(), -Credit_History) %>% step_impute_bag(Gender, Married, Dependents, Self_Employed, Loan_Amount, Loan_Amount_Term) %>% step_dummy(all_nominal_predictors())recipe_2 <- recipe(Loan_Status ~., data = training(loan_split)) %>% step_rm(Loan_ID) %>% step_mutate(Credit_History = if_else(Credit_History == 1, 1, -1,0)) %>% step_scale(all_numeric_predictors(), -Credit_History) %>% step_impute_bag(Gender, Married, Dependents, Self_Employed, Loan_Amount, Loan_Amount_Term) %>% step_dummy(all_nominal_predictors()) %>% step_smote(Loan_Status) recipe_3 <- recipe(Loan_Status ~., data = training(loan_split)) %>% step_rm(Loan_ID) %>% step_mutate(Credit_History = if_else(Credit_History == 1, 1, -1,0)) %>% step_scale(all_numeric_predictors(), -Credit_History) %>% step_impute_mean(all_numeric_predictors()) %>% step_impute_mode(all_nominal_predictors()) %>% step_dummy(all_nominal_predictors()) %>% step_zv(all_predictors())recipe_4 <- recipe(Loan_Status ~., data = training(loan_split)) %>% step_rm(Loan_ID) %>% step_mutate(Credit_History = if_else(Credit_History == 1, 1, -1,0)) %>% step_scale(all_numeric_predictors(), -Credit_History) %>% step_impute_mean(all_numeric_predictors()) %>% step_impute_mode(all_nominal_predictors()) %>% step_dummy(all_nominal_predictors()) %>% step_zv(all_predictors()) %>% step_smote(Loan_Status)"
},
{
"code": null,
"e": 10802,
"s": 10709,
"text": "Taking recipe_1, we can prepare both the training and test datasets per the transformations."
},
{
"code": null,
"e": 10965,
"s": 10802,
"text": "#Prep and Bake Training and Test Datasetsloan_train <- recipe_1 %>% prep() %>% bake(new_data = NULL)loan_test <- recipe_1 %>% prep() %>% bake(testing(loan_split))"
},
{
"code": null,
"e": 11038,
"s": 10965,
"text": "Then take these transformed datasets and visualise variable correlation."
},
{
"code": null,
"e": 11525,
"s": 11038,
"text": "#Generate Correlation Visualisationloan_train %>% bind_rows(loan_test) %>% mutate(Loan_Status = if_else(Loan_Status == \"Y\",1,0)) %>% correlate() %>% rearrange() %>% shave() %>% rplot(print_cor = T,.order = \"alphabet\") + theme_minimal() + theme(axis.text.x = element_text(angle = 90)) + scale_color_viridis_c() + labs(title = \"Correlation Plot for Trained Loan Dataset\")"
},
{
"code": null,
"e": 11803,
"s": 11525,
"text": "From the above we note a strong relationship between Loan_Status and whether an applicant has a Credit_History. This makes sense, bank’s are more inclined to give loans to customers with a credit history, evidence positive or otherwise of a customers ability to repay the loan."
},
{
"code": null,
"e": 11861,
"s": 11803,
"text": "Iterating Parnsip and Recipe Combinations — Workflow Sets"
},
{
"code": null,
"e": 12031,
"s": 11861,
"text": "Workflow Sets enables us to screen all possible combinations of recipe and parnsip model specifications. As below, we’ve created two named lists, all models and recipes."
},
{
"code": null,
"e": 12375,
"s": 12031,
"text": "#Generate List of Recipesrecipe_list <- list(Recipe1 = recipe_1, Recipe2 = recipe_2, Recipe3 = recipe_3, Recipe4 = recipe_4)#Generate List of Model Typesmodel_list <- list(Random_Forest = rf_loan, SVM = svm_loan, Naive_Bayes = nb_loan, Decision_Tree = dt_loan, Boosted_Trees = xgboost_loan, KNN = knn_loan, Logistic_Regression = logistic_loan)"
},
{
"code": null,
"e": 12453,
"s": 12375,
"text": "Here comes the fun part, creating a series of workflows using workflow_sets()"
},
{
"code": null,
"e": 12534,
"s": 12453,
"text": "model_set <- workflow_set(preproc = recipe_list, models = model_list, cross = T)"
},
{
"code": null,
"e": 12654,
"s": 12534,
"text": "Setting cross = T instructs workflow_set to create all possible combinations of parsnip model and recipe specification."
},
{
"code": null,
"e": 12900,
"s": 12654,
"text": "set.seed(2)train_resamples <- bootstraps(training(loan_split), strata = Loan_Status)doParallel::registerDoParallel(cores = 12)all_workflows <- model_set %>% workflow_map(resamples = train_resamples, verbose = TRUE)"
},
{
"code": null,
"e": 13300,
"s": 12900,
"text": "We’ve initialised a boostraps resampling procedure, this is computationally more demanding, however results in less error overall. Passing the model_set object through to workflow_map, with the resampling procedure will initate a screen of all parsnip-recipe combinations showing an output like this. This is a demanding procedure, and hence why we’ve initiated parrallel compute to ease this along."
},
{
"code": null,
"e": 13602,
"s": 13300,
"text": "Using the resampling procedure, workflow_map will fit each workflow to the training data and compute accuracy on each resample and take the mean. Furthermore, as each of the recipes specifies that the hyperparameters should be tuned, workflow_map will perform some tuning to provide an optimal result."
},
{
"code": null,
"e": 13750,
"s": 13602,
"text": "Once completed, we can call the all_workflows object and collect all the metrics that were calculated in this procedure, and visualise the results."
},
{
"code": null,
"e": 13950,
"s": 13750,
"text": "N.B there is an autoplot() function available for workflow_set objects, however we want to be able to compare recipe and model performance so have had to re-engineer features for visualisation below."
},
{
"code": null,
"e": 14740,
"s": 13950,
"text": "#Visualise Performance Comparison of Workflowscollect_metrics(all_workflows) %>% separate(wflow_id, into = c(\"Recipe\", \"Model_Type\"), sep = \"_\", remove = F, extra = \"merge\") %>% filter(.metric == \"accuracy\") %>% group_by(wflow_id) %>% filter(mean == max(mean)) %>% group_by(model) %>% select(-.config) %>% distinct() %>% ungroup() %>% mutate(Workflow_Rank = row_number(-mean), .metric = str_to_upper(.metric)) %>% ggplot(aes(x=Workflow_Rank, y = mean, shape = Recipe, color = Model_Type)) + geom_point() + geom_errorbar(aes(ymin = mean-std_err, ymax = mean+std_err)) + theme_minimal()+ scale_colour_viridis_d() + labs(title = \"Performance Comparison of Workflow Sets\", x = \"Workflow Rank\", y = \"Accuracy\", color = \"Model Types\", shape = \"Recipes\")"
},
{
"code": null,
"e": 14771,
"s": 14740,
"text": "From the above we can observe:"
},
{
"code": null,
"e": 14823,
"s": 14771,
"text": "Naive Bayes and KNN models have performed the worst"
},
{
"code": null,
"e": 14867,
"s": 14823,
"text": "Tree-Based methods have performed very well"
},
{
"code": null,
"e": 14997,
"s": 14867,
"text": "SMOTE has not offered an increase in performance for more complex model types, no change between recipes for decision tree model."
},
{
"code": null,
"e": 15205,
"s": 14997,
"text": "Whilst we’ve made very general first glance observations, given the slight difference in the mean accuracy of say the top 8 workflows, how do we discern which are distinct, or otherwise practically the same?"
},
{
"code": null,
"e": 15253,
"s": 15205,
"text": "Post Hoc Analysis of Resampling — tidyposterior"
},
{
"code": null,
"e": 15648,
"s": 15253,
"text": "One way to compare models is to examine the resampling results, and ask are the models actually different?The tidyposterior::perf_mod function enables comparisons of all of our workflow combinations by generating a set of posterior distributions, for a given metric, which can then be compared against each other for practical equivalence. Essentially, we can make between-workflow comparisons."
},
{
"code": null,
"e": 15779,
"s": 15648,
"text": "doParallel::registerDoParallel(cores = 12)set.seed(246)acc_model_eval <- perf_mod(all_workflows, metric = \"accuracy\", iter = 5000)"
},
{
"code": null,
"e": 15933,
"s": 15779,
"text": "The results of perf_mod are then passed to tidy() to extract the underlying findings of the posterior analysis. Their distributions are visualised below."
},
{
"code": null,
"e": 16343,
"s": 15933,
"text": "#Extract Results from Posterior Analysis and Visualise Distributionsacc_model_eval %>% tidy() %>% mutate(model = fct_inorder(model)) %>% ggplot(aes(x=posterior)) + geom_histogram(bins = 50) + theme_minimal() + facet_wrap(~model, nrow = 7, ncol = 6) + labs(title = \"Comparison of Posterior Distributions of Model Recipe Combinations\", x = expression(paste(\"Posterior for Mean Accuracy\")), y = \"\")"
},
{
"code": null,
"e": 16676,
"s": 16343,
"text": "Looking back at our performance comparison, we observe that the two highest rank models are Boosted Trees and Decision Trees with Recipe1, models on the extreme sides of the interpretability scale for tree based models. We can seek to understand further by taking the difference in means of their respective posterior distributions."
},
{
"code": null,
"e": 16730,
"s": 16676,
"text": "Using contrast_models() we can conduct that analysis."
},
{
"code": null,
"e": 17782,
"s": 16730,
"text": "#Compare Two Models - Difference in Meansmod_compare <- contrast_models(acc_model_eval, list_1 = \"Recipe1_Decision_Tree\", list_2 = \"Recipe1_Boosted_Trees\")a1 <- mod_compare %>% as_tibble() %>% ggplot(aes(x=difference)) + geom_histogram(bins = 50, col = \"white\", fill = \"#73D055FF\")+ geom_vline(xintercept = 0, lty = 2) + theme_minimal()+ scale_fill_viridis_b()+ labs(x= \"Posterior for Mean Difference in Accuracy\", y=\"\", title = \"Posterior Mean Difference Recipe1_Decision_Tree & Recipe3_Boosted_Trees\")a2 <- acc_model_eval %>% tidy() %>% mutate(model = fct_inorder(model)) %>% filter(model %in% c(\"Recipe1_Boosted_Trees\", \"Recipe1_Decision_Tree\")) %>% ggplot(aes(x=posterior)) + geom_histogram(bins = 50, col = \"white\", fill = \"#73D055FF\") + theme_minimal()+ scale_colour_viridis_b() + facet_wrap(~model, nrow = 2, ncol = 1) + labs(title = \"Comparison of Posterior Distributions of Model Recipe Combinations\", x = expression(paste(\"Posterior for Mean Accuracy\")), y = \"\")a2/a1"
},
{
"code": null,
"e": 17854,
"s": 17782,
"text": "Piping the mod_compare object to summary generates the following output"
},
{
"code": null,
"e": 18013,
"s": 17854,
"text": "mod_compare %>% summary()mean0.001371989 #Difference in means between posterior distributionsprobability0.5842 #Proportion of Posterior of Mean Difference > 0"
},
{
"code": null,
"e": 18311,
"s": 18013,
"text": "As also evidenced by the posterior for mean difference, the mean difference is small between the respective workflow posterior distributions for mean accuracy. 58.4% of the posterior difference of means distribution is above 0, so we can infer that the positive difference is real (albeit slight)."
},
{
"code": null,
"e": 18381,
"s": 18311,
"text": "We can investigate further, with the notion of practical equivalence."
},
{
"code": null,
"e": 18432,
"s": 18381,
"text": "summary(mod_compare, size = 0.02)pract_equiv0.9975"
},
{
"code": null,
"e": 18746,
"s": 18432,
"text": "The effect size are thresholds on both sides [-0.02, 0.02] of the difference in means posterior distribution, and the pract_equiv measures how much of the diff. in means post. distribution is within these thresholds. For our comparison, Boosted_Trees is 99.75% within the posterior distribution for Decision_Tree."
},
{
"code": null,
"e": 18804,
"s": 18746,
"text": "We can complete this exercise for all workflows as below."
},
{
"code": null,
"e": 19473,
"s": 18804,
"text": "#Pluck and modify underlying tibble from autoplot()autoplot(acc_model_eval, type = \"ROPE\", size = 0.02) %>% pluck(\"data\") %>% mutate(rank = row_number(-pract_equiv)) %>% arrange(rank) %>% separate(model, into = c(\"Recipe\", \"Model_Type\"), sep = \"_\", remove = F, extra = \"merge\") %>% ggplot(aes(x=rank, y= pract_equiv, color = Model_Type, shape = Recipe)) + geom_point(size = 5) + theme_minimal() + scale_colour_viridis_d() + labs(y= \"Practical Equivalance\", x = \"Workflow Rank\", size = \"Probability of Practical Equivalence\", color = \"Model Type\", title = \"Practical Equivalence of Workflow Sets\", subtitle = \"Calculated Using an Effect Size of 0.02\")"
},
{
"code": null,
"e": 19852,
"s": 19473,
"text": "We’ve taken the data that underpins the autoplot object that conducts the ROPE (Region of Practical Equivalence) calculation, so that we can engineer and display more features. In doing so we can easily compare the each of the workflows using Recipe1_Decision_Tree as a benchmark. There are a handful of workflows that would likely perform just as well as Recipe1_Decision_Tree."
},
{
"code": null,
"e": 20194,
"s": 19852,
"text": "The top two candidates, Boosted_Trees and Decision_Tree sit on opposite ends of the interpretability spectrum. Boosted Trees is very much a black-box method, conversely Decision Trees are more easily understood, and in this instance provides the best result, and hence we’ll finalise our workflow on the basis of using Recipe1_Decision_Tree."
},
{
"code": null,
"e": 20915,
"s": 20194,
"text": "#Pull Best Performing Hyperparameter Set From workflow_map Objectbest_result <- all_workflows %>% pull_workflow_set_result(\"Recipe1_Decision_Tree\") %>% select_best(metric = \"accuracy\")#Finalise Workflow Object With Best Parametersdt_wf <- all_workflows %>% pull_workflow(\"Recipe1_Decision_Tree\") %>% finalize_workflow(best_result)#Fit Workflow Object to Training Data and Predict Using Test Datasetdt_res <- dt_wf %>% fit(training(loan_split)) %>% predict(new_data = testing(loan_split)) %>% bind_cols(loan_test) %>% mutate(.pred_class = fct_infreq(.pred_class), Loan_Status = fct_infreq(Loan_Status))#Calculate Accuracy of Predictionaccuracy(dt_res, truth = Loan_Status, estimate = .pred_class)"
},
{
"code": null,
"e": 21472,
"s": 20915,
"text": "Our finalised model has managed to generate a very strong result, 84.68% accurate on the test dataset. Model is generally performing well on predicting approvals for loans that were granted. However model is approving loans that were decided against by the bank. This is a curious case, obviously more loans a bank offers means higher potential for revenue, at a higher risk exposure. This indicates the dataset contains some inconsistencies that the model is not able to fully distinguish and has been ‘confused’ based on observations in the training set."
},
{
"code": null,
"e": 21641,
"s": 21472,
"text": "This presents an argument for model interpretability, in this example we cannot generate more data, so how do we know the basis by which the predictions have been made?"
},
{
"code": null,
"e": 21869,
"s": 21641,
"text": "#Fit and Extract Fit from Workflow Objectdt_wf_fit <- dt_wf %>% fit(training(loan_split))dt_fit <- dt_wf_fit %>% pull_workflow_fit()#Generate Decision Tree Plot Using rpart.plot packagerpart.plot::rpart.plot(dt_fit$fit)"
},
{
"code": null,
"e": 21950,
"s": 21869,
"text": "As our model is simple enough to visualise and understand, a tree plot suffices."
},
{
"code": null,
"e": 22330,
"s": 21950,
"text": "Immediately we observe that the decision has been based solely on the presence of a Credit History. The model is also erring on the side of providing applicants with an unknown Credit_History (= 0), and denying applicants without one (Credit_History = -1). The inconsistencies noted above are evident, not everyone with a credit history is granted a loan, but it certainly helps."
},
{
"code": null,
"e": 22341,
"s": 22330,
"text": "Conclusion"
},
{
"code": null,
"e": 22607,
"s": 22341,
"text": "You return to your CDO and explain your findings. They’re impressed with the accuracy result, but now the business has to weigh up the risk of default permitting applications with unknown credit histories, and the potential revenue that it might otherwise generate."
},
{
"code": null,
"e": 22973,
"s": 22607,
"text": "This article has sought to explain the power of workflow_sets within the Tidymodels ecosystem. Furthermore, we’ve explored the “No Free Lunch” theorem, that no one model can be said to be better or best, and hence why it is best practice to screen many models. The types of models that respond well are also dependant on the feature engineering that is carried out."
},
{
"code": null,
"e": 23161,
"s": 22973,
"text": "Thank you for reading my second publication. If you’re interested in Tidymodels, I published an introductory project explaining each of the core packages when building a regression model."
}
] |
Create Primary Key on an existing table in PostgreSQL? | Although quite infrequent, you may come across situations wherein you need to define the primary key on an existing table. This can be achieved using the ALTER TABLE statement.
The syntax is −
ALTER TABLE table_name ADD PRIMARY KEY (column_name1,
column_name2,...., columns_nameN)
As can be seen from the above syntax, you can define PRIMARY KEY on multiple columns. When you have defined the PRIMARY KEY on multiple columns, the condition is that the column pairs should have unique and non-null values. Thus, if the PRIMARY KEY is defined on (column1, column2), the values (value1, value2), (value3, value2), and (value1,value4) are allowed. Even though column1 has value1 repeated and column2 has value2 repeated, the pair of columns have unique values when considered together.
Let us consider an example to understand this. Let us create a table marks and populate it as follows −
CREATE TABLE marks(
name VARCHAR,
roll_no INTEGER,
marks_obtained INTEGER,
perc_marks DOUBLE PRECISION,
max_marks INTEGER,
date_of_entry DATE
);
INSERT INTO marks(name, roll_no, marks_obtained, perc_marks,
max_marks, date_of_entry)
VALUES ('Yash', 26, 42, 42.0, 100, current_date),
('Isha', 56, 175, 87.5, 200, current_date),
('Yash', 35, 12, 24, 50, current_date);
If you query the table (SELECT * from marks2), you will see output similar to the following −
This table has no primary key set so far. Now, let us try to define the name column as the primary key.
ALTER TABLE marks ADD PRIMARY KEY (name)
PostgreSQL will return an error −
ERROR: could not create unique index "marks_pkey" DETAIL: Key (name)=(Yash) is
duplicated. SQL state: 23505
This is as expected. PRIMARY KEY can’t have duplicate values. Now, let us try to set the PRIMARY KEY on the (name, roll_no) pair.
ALTER TABLE marks ADD PRIMARY KEY (name, roll_no)
This will work because no combination of (name, roll_no) is duplicate. | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "Although quite infrequent, you may come across situations wherein you need to define the primary key on an existing table. This can be achieved using the ALTER TABLE statement."
},
{
"code": null,
"e": 1255,
"s": 1239,
"text": "The syntax is −"
},
{
"code": null,
"e": 1343,
"s": 1255,
"text": "ALTER TABLE table_name ADD PRIMARY KEY (column_name1,\ncolumn_name2,...., columns_nameN)"
},
{
"code": null,
"e": 1844,
"s": 1343,
"text": "As can be seen from the above syntax, you can define PRIMARY KEY on multiple columns. When you have defined the PRIMARY KEY on multiple columns, the condition is that the column pairs should have unique and non-null values. Thus, if the PRIMARY KEY is defined on (column1, column2), the values (value1, value2), (value3, value2), and (value1,value4) are allowed. Even though column1 has value1 repeated and column2 has value2 repeated, the pair of columns have unique values when considered together."
},
{
"code": null,
"e": 1948,
"s": 1844,
"text": "Let us consider an example to understand this. Let us create a table marks and populate it as follows −"
},
{
"code": null,
"e": 2332,
"s": 1948,
"text": "CREATE TABLE marks(\n name VARCHAR,\n roll_no INTEGER,\n marks_obtained INTEGER,\n perc_marks DOUBLE PRECISION,\n max_marks INTEGER,\n date_of_entry DATE\n);\nINSERT INTO marks(name, roll_no, marks_obtained, perc_marks,\nmax_marks, date_of_entry)\nVALUES ('Yash', 26, 42, 42.0, 100, current_date),\n('Isha', 56, 175, 87.5, 200, current_date),\n('Yash', 35, 12, 24, 50, current_date);"
},
{
"code": null,
"e": 2426,
"s": 2332,
"text": "If you query the table (SELECT * from marks2), you will see output similar to the following −"
},
{
"code": null,
"e": 2530,
"s": 2426,
"text": "This table has no primary key set so far. Now, let us try to define the name column as the primary key."
},
{
"code": null,
"e": 2571,
"s": 2530,
"text": "ALTER TABLE marks ADD PRIMARY KEY (name)"
},
{
"code": null,
"e": 2605,
"s": 2571,
"text": "PostgreSQL will return an error −"
},
{
"code": null,
"e": 2713,
"s": 2605,
"text": "ERROR: could not create unique index \"marks_pkey\" DETAIL: Key (name)=(Yash) is\nduplicated. SQL state: 23505"
},
{
"code": null,
"e": 2843,
"s": 2713,
"text": "This is as expected. PRIMARY KEY can’t have duplicate values. Now, let us try to set the PRIMARY KEY on the (name, roll_no) pair."
},
{
"code": null,
"e": 2893,
"s": 2843,
"text": "ALTER TABLE marks ADD PRIMARY KEY (name, roll_no)"
},
{
"code": null,
"e": 2964,
"s": 2893,
"text": "This will work because no combination of (name, roll_no) is duplicate."
}
] |
How can we create a custom exception in Java? | Sometimes it is required to develop meaningful exceptions based on the application requirements. We can create our own exceptions by extending Exception class in Java
User-defined exceptions in Java are also known as Custom Exceptions.
CustomException class is the custom exception class this class is extending Exception class.
Create one local variable message to store the exception message locally in the class object.
We are passing a string argument to the constructor of the custom exception object. The constructor set the argument string to the private string message.
toString() method is used to print out the exception message.
We are simply throwing a CustomException using one try-catch block in the main method and observe how the string is passed while creating a custom exception. Inside the catch block, we are printing out the message.
class CustomException extends Exception {
String message;
CustomException(String str) {
message = str;
}
public String toString() {
return ("Custom Exception Occurred : " + message);
}
}
public class MainException {
public static void main(String args[]) {
try {
throw new CustomException("This is a custom message");
} catch(CustomException e) {
System.out.println(e);
}
}
}
Custom Exception Occurred : This is a custom message | [
{
"code": null,
"e": 1229,
"s": 1062,
"text": "Sometimes it is required to develop meaningful exceptions based on the application requirements. We can create our own exceptions by extending Exception class in Java"
},
{
"code": null,
"e": 1298,
"s": 1229,
"text": "User-defined exceptions in Java are also known as Custom Exceptions."
},
{
"code": null,
"e": 1391,
"s": 1298,
"text": "CustomException class is the custom exception class this class is extending Exception class."
},
{
"code": null,
"e": 1485,
"s": 1391,
"text": "Create one local variable message to store the exception message locally in the class object."
},
{
"code": null,
"e": 1640,
"s": 1485,
"text": "We are passing a string argument to the constructor of the custom exception object. The constructor set the argument string to the private string message."
},
{
"code": null,
"e": 1702,
"s": 1640,
"text": "toString() method is used to print out the exception message."
},
{
"code": null,
"e": 1917,
"s": 1702,
"text": "We are simply throwing a CustomException using one try-catch block in the main method and observe how the string is passed while creating a custom exception. Inside the catch block, we are printing out the message."
},
{
"code": null,
"e": 2362,
"s": 1917,
"text": "class CustomException extends Exception {\n String message;\n CustomException(String str) {\n message = str;\n }\n public String toString() {\n return (\"Custom Exception Occurred : \" + message);\n }\n}\npublic class MainException {\n public static void main(String args[]) {\n try {\n throw new CustomException(\"This is a custom message\");\n } catch(CustomException e) {\n System.out.println(e);\n }\n }\n}"
},
{
"code": null,
"e": 2415,
"s": 2362,
"text": "Custom Exception Occurred : This is a custom message"
}
] |
Sum of the series 1, 2, 4, 3, 5, 7, 9, 6, 8, 10, 11, 13.. till N-th term - GeeksforGeeks | 10 Oct, 2021
Given a series of numbers 1, 2, 4, 3, 5, 7, 9, 6, 8, 10, 11, 13... The task is to find the sum of all the numbers in series till N-th number. Examples:
Input: N = 4 Output: 10 1 + 2 + 4 + 3 = 10 Input: N = 10 Output: 55
Approach: The series is basically 20 odd numbers, 21 even numbers, 22 even numbers.... The sum of first N odd numbers is N * N and sum of first N even numbers is (N * (N+1)). Calculate the summation for 2i odd or even numbers and keep adding them to the sum. Iterate for every power of 2, till the number of iterations exceeds N, and keep adding the respective summation of odd or even numbers according to the parity. For every segment the sum of the segment will be, (current sum of X odd/even numbers – previous sum of Y odd/even numbers), where X is the total sum of odd/even numbers till this segment and Y is the summation of odd/even numbers till the previous when odd/even numbers occurred. Below is the implementation of the above approach:
C++
Java
Python
C#
PHP
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the// sum of first N odd numbersint sumodd(int n){ return (n * n);} // Function to find the// sum of first N even numbersint sumeven(int n){ return (n * (n + 1));} // Function to overall// find the sum of seriesint findSum(int num){ // Initial odd numbers int sumo = 0; // Initial even numbers int sume = 0; // First power of 2 int x = 1; // Check for parity // for odd/even int cur = 0; // Counts the sum int ans = 0; while (num > 0) { // Get the minimum // out of remaining num // or power of 2 int inc = min(x, num); // Decrease that much numbers // from num num -= inc; // If the segment has odd numbers if (cur == 0) { // Summate the odd numbers // By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo); // Increase number of odd numbers sumo += inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume); // Increase number of even numbers sume += inc; } // Next set of numbers x *= 2; // Change parity for odd/even cur ^= 1; } return ans;} // Driver codeint main(){ int n = 4; cout << findSum(n); return 0;}
// Java program to implement// the above approach class GFG{ // Function to find the // sum of first N odd numbers static int sumodd(int n) { return (n * n); } // Function to find the // sum of first N even numbers static int sumeven(int n) { return (n * (n + 1)); } // Function to overall // find the sum of series static int findSum(int num) { // Initial odd numbers int sumo = 0; // Initial even numbers int sume = 0; // First power of 2 int x = 1; // Check for parity // for odd/even int cur = 0; // Counts the sum int ans = 0; while (num > 0) { // Get the minimum // out of remaining num // or power of 2 int inc = Math.min(x, num); // Decrease that much numbers // from num num -= inc; // If the segment has odd numbers if (cur == 0) { // Summate the odd numbers // By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo); // Increase number of odd numbers sumo += inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume); // Increase number of even numbers sume += inc; } // Next set of numbers x *= 2; // Change parity for odd/even cur ^= 1; } return ans; } // Driver code public static void main(String[] args) { int n = 4; System.out.println(findSum(n)); }} // This code contributed by Rajput-Ji
# Python3 program to implement# the above approach # Function to find the# sum of first N odd numbersdef sumodd(n): return (n * n) # Function to find the# sum of first N even numbersdef sumeven(n): return (n * (n + 1)) # Function to overall# find the sum of seriesdef findSum(num): # Initial odd numbers sumo = 0 # Initial even numbers sume = 0 # First power of 2 x = 1 # Check for parity # for odd/even cur = 0 # Counts the sum ans = 0 while (num > 0): # Get the minimum # out of remaining num # or power of 2 inc = min(x, num) # Decrease that much numbers # from num num -= inc # If the segment has odd numbers if (cur == 0): # Summate the odd numbers # By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo) # Increase number of odd numbers sumo += inc # If the segment has even numbers else: # Summate the even numbers # By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume) # Increase number of even numbers sume += inc # Next set of numbers x *= 2 # Change parity for odd/even cur ^= 1 return ans # Driver coden = 4print(findSum(n)) # This code is contributed by mohit kumar
// C# program to implement// the above approachusing System; class GFG{ // Function to find the // sum of first N odd numbers static int sumodd(int n) { return (n * n); } // Function to find the // sum of first N even numbers static int sumeven(int n) { return (n * (n + 1)); } // Function to overall // find the sum of series static int findSum(int num) { // Initial odd numbers int sumo = 0; // Initial even numbers int sume = 0; // First power of 2 int x = 1; // Check for parity // for odd/even int cur = 0; // Counts the sum int ans = 0; while (num > 0) { // Get the minimum // out of remaining num // or power of 2 int inc = Math.Min(x, num); // Decrease that much numbers // from num num -= inc; // If the segment has odd numbers if (cur == 0) { // Summate the odd numbers // By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo); // Increase number of odd numbers sumo += inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume); // Increase number of even numbers sume += inc; } // Next set of numbers x *= 2; // Change parity for odd/even cur ^= 1; } return ans; } // Driver code public static void Main(String[] args) { int n = 4; Console.WriteLine(findSum(n)); }} // This code has been contributed by 29AjayKumar
<?php// PHP program to implement// the above approach // Function to find the// sum of first N odd numbersfunction sumodd($n){ return ($n * $n);} // Function to find the// sum of first N even numbersfunction sumeven($n){ return ($n * ($n + 1));} // Function to overall// find the sum of seriesfunction findSum( $num){ // Initial odd numbers $sumo = 0; // Initial even numbers $sume = 0; // First power of 2 $x = 1; // Check for parity // for odd/even $cur = 0; // Counts the sum $ans = 0; while ($num > 0) { // Get the minimum // out of remaining num // or power of 2 $inc = min($x, $num); // Decrease that much numbers // from num $num -= $inc; // If the segment has odd numbers if ($cur == 0) { // Summate the odd numbers // By exclusion $ans = $ans + sumodd($sumo + $inc) - sumodd($sumo); // Increase number of odd numbers $sumo += $inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion $ans = $ans + sumeven($sume + $inc) - sumeven($sume); // Increase number of even numbers $sume += $inc; } // Next set of numbers $x *= 2; // Change parity for odd/even $cur ^= 1; } return $ans;} // Driver code$n = 4;echo findSum($n); // This code contributed by princiraj1992?>
<script> // javascript program to implement// the above approach // Function to find the// sum of first N odd numbersfunction sumodd( n){ return (n * n);} // Function to find the// sum of first N even numbersfunction sumeven( n){ return (n * (n + 1));} // Function to overall// find the sum of seriesfunction findSum( num){ // Initial odd numbers let sumo = 0; // Initial even numbers let sume = 0; // First power of 2 let x = 1; // Check for parity // for odd/even let cur = 0; // Counts the sum let ans = 0; while (num > 0) { // Get the minimum // out of remaining num // or power of 2 let inc = Math.min(x, num); // Decrease that much numbers // from num num -= inc; // If the segment has odd numbers if (cur == 0) { // Summate the odd numbers // By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo); // Increase number of odd numbers sumo += inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume); // Increase number of even numbers sume += inc; } // Next set of numbers x *= 2; // Change parity for odd/even cur ^= 1; } return ans;} // Driver code let n = 4; document.write( findSum(n)); // This code is contributed by todaysgaurav </script>
10
mohit kumar 29
Rajput-Ji
29AjayKumar
princiraj1992
todaysgaurav
hritikbhatnagar2182
simmytarika5
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Generate all permutation of a set in Python
Check if a number is Palindrome
How to check if a given point lies inside or outside a polygon?
Program to multiply two matrices
Segment Tree | Set 1 (Sum of given range)
Merge two sorted arrays with O(1) extra space
Singular Value Decomposition (SVD) | [
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 26091,
"s": 25937,
"text": "Given a series of numbers 1, 2, 4, 3, 5, 7, 9, 6, 8, 10, 11, 13... The task is to find the sum of all the numbers in series till N-th number. Examples: "
},
{
"code": null,
"e": 26159,
"s": 26091,
"text": "Input: N = 4 Output: 10 1 + 2 + 4 + 3 = 10 Input: N = 10 Output: 55"
},
{
"code": null,
"e": 26911,
"s": 26159,
"text": "Approach: The series is basically 20 odd numbers, 21 even numbers, 22 even numbers.... The sum of first N odd numbers is N * N and sum of first N even numbers is (N * (N+1)). Calculate the summation for 2i odd or even numbers and keep adding them to the sum. Iterate for every power of 2, till the number of iterations exceeds N, and keep adding the respective summation of odd or even numbers according to the parity. For every segment the sum of the segment will be, (current sum of X odd/even numbers – previous sum of Y odd/even numbers), where X is the total sum of odd/even numbers till this segment and Y is the summation of odd/even numbers till the previous when odd/even numbers occurred. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26915,
"s": 26911,
"text": "C++"
},
{
"code": null,
"e": 26920,
"s": 26915,
"text": "Java"
},
{
"code": null,
"e": 26927,
"s": 26920,
"text": "Python"
},
{
"code": null,
"e": 26930,
"s": 26927,
"text": "C#"
},
{
"code": null,
"e": 26934,
"s": 26930,
"text": "PHP"
},
{
"code": null,
"e": 26945,
"s": 26934,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the// sum of first N odd numbersint sumodd(int n){ return (n * n);} // Function to find the// sum of first N even numbersint sumeven(int n){ return (n * (n + 1));} // Function to overall// find the sum of seriesint findSum(int num){ // Initial odd numbers int sumo = 0; // Initial even numbers int sume = 0; // First power of 2 int x = 1; // Check for parity // for odd/even int cur = 0; // Counts the sum int ans = 0; while (num > 0) { // Get the minimum // out of remaining num // or power of 2 int inc = min(x, num); // Decrease that much numbers // from num num -= inc; // If the segment has odd numbers if (cur == 0) { // Summate the odd numbers // By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo); // Increase number of odd numbers sumo += inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume); // Increase number of even numbers sume += inc; } // Next set of numbers x *= 2; // Change parity for odd/even cur ^= 1; } return ans;} // Driver codeint main(){ int n = 4; cout << findSum(n); return 0;}",
"e": 28463,
"s": 26945,
"text": null
},
{
"code": "// Java program to implement// the above approach class GFG{ // Function to find the // sum of first N odd numbers static int sumodd(int n) { return (n * n); } // Function to find the // sum of first N even numbers static int sumeven(int n) { return (n * (n + 1)); } // Function to overall // find the sum of series static int findSum(int num) { // Initial odd numbers int sumo = 0; // Initial even numbers int sume = 0; // First power of 2 int x = 1; // Check for parity // for odd/even int cur = 0; // Counts the sum int ans = 0; while (num > 0) { // Get the minimum // out of remaining num // or power of 2 int inc = Math.min(x, num); // Decrease that much numbers // from num num -= inc; // If the segment has odd numbers if (cur == 0) { // Summate the odd numbers // By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo); // Increase number of odd numbers sumo += inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume); // Increase number of even numbers sume += inc; } // Next set of numbers x *= 2; // Change parity for odd/even cur ^= 1; } return ans; } // Driver code public static void main(String[] args) { int n = 4; System.out.println(findSum(n)); }} // This code contributed by Rajput-Ji",
"e": 30338,
"s": 28463,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to find the# sum of first N odd numbersdef sumodd(n): return (n * n) # Function to find the# sum of first N even numbersdef sumeven(n): return (n * (n + 1)) # Function to overall# find the sum of seriesdef findSum(num): # Initial odd numbers sumo = 0 # Initial even numbers sume = 0 # First power of 2 x = 1 # Check for parity # for odd/even cur = 0 # Counts the sum ans = 0 while (num > 0): # Get the minimum # out of remaining num # or power of 2 inc = min(x, num) # Decrease that much numbers # from num num -= inc # If the segment has odd numbers if (cur == 0): # Summate the odd numbers # By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo) # Increase number of odd numbers sumo += inc # If the segment has even numbers else: # Summate the even numbers # By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume) # Increase number of even numbers sume += inc # Next set of numbers x *= 2 # Change parity for odd/even cur ^= 1 return ans # Driver coden = 4print(findSum(n)) # This code is contributed by mohit kumar",
"e": 31731,
"s": 30338,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to find the // sum of first N odd numbers static int sumodd(int n) { return (n * n); } // Function to find the // sum of first N even numbers static int sumeven(int n) { return (n * (n + 1)); } // Function to overall // find the sum of series static int findSum(int num) { // Initial odd numbers int sumo = 0; // Initial even numbers int sume = 0; // First power of 2 int x = 1; // Check for parity // for odd/even int cur = 0; // Counts the sum int ans = 0; while (num > 0) { // Get the minimum // out of remaining num // or power of 2 int inc = Math.Min(x, num); // Decrease that much numbers // from num num -= inc; // If the segment has odd numbers if (cur == 0) { // Summate the odd numbers // By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo); // Increase number of odd numbers sumo += inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume); // Increase number of even numbers sume += inc; } // Next set of numbers x *= 2; // Change parity for odd/even cur ^= 1; } return ans; } // Driver code public static void Main(String[] args) { int n = 4; Console.WriteLine(findSum(n)); }} // This code has been contributed by 29AjayKumar",
"e": 33627,
"s": 31731,
"text": null
},
{
"code": "<?php// PHP program to implement// the above approach // Function to find the// sum of first N odd numbersfunction sumodd($n){ return ($n * $n);} // Function to find the// sum of first N even numbersfunction sumeven($n){ return ($n * ($n + 1));} // Function to overall// find the sum of seriesfunction findSum( $num){ // Initial odd numbers $sumo = 0; // Initial even numbers $sume = 0; // First power of 2 $x = 1; // Check for parity // for odd/even $cur = 0; // Counts the sum $ans = 0; while ($num > 0) { // Get the minimum // out of remaining num // or power of 2 $inc = min($x, $num); // Decrease that much numbers // from num $num -= $inc; // If the segment has odd numbers if ($cur == 0) { // Summate the odd numbers // By exclusion $ans = $ans + sumodd($sumo + $inc) - sumodd($sumo); // Increase number of odd numbers $sumo += $inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion $ans = $ans + sumeven($sume + $inc) - sumeven($sume); // Increase number of even numbers $sume += $inc; } // Next set of numbers $x *= 2; // Change parity for odd/even $cur ^= 1; } return $ans;} // Driver code$n = 4;echo findSum($n); // This code contributed by princiraj1992?>",
"e": 35202,
"s": 33627,
"text": null
},
{
"code": "<script> // javascript program to implement// the above approach // Function to find the// sum of first N odd numbersfunction sumodd( n){ return (n * n);} // Function to find the// sum of first N even numbersfunction sumeven( n){ return (n * (n + 1));} // Function to overall// find the sum of seriesfunction findSum( num){ // Initial odd numbers let sumo = 0; // Initial even numbers let sume = 0; // First power of 2 let x = 1; // Check for parity // for odd/even let cur = 0; // Counts the sum let ans = 0; while (num > 0) { // Get the minimum // out of remaining num // or power of 2 let inc = Math.min(x, num); // Decrease that much numbers // from num num -= inc; // If the segment has odd numbers if (cur == 0) { // Summate the odd numbers // By exclusion ans = ans + sumodd(sumo + inc) - sumodd(sumo); // Increase number of odd numbers sumo += inc; } // If the segment has even numbers else { // Summate the even numbers // By exclusion ans = ans + sumeven(sume + inc) - sumeven(sume); // Increase number of even numbers sume += inc; } // Next set of numbers x *= 2; // Change parity for odd/even cur ^= 1; } return ans;} // Driver code let n = 4; document.write( findSum(n)); // This code is contributed by todaysgaurav </script>",
"e": 36745,
"s": 35202,
"text": null
},
{
"code": null,
"e": 36748,
"s": 36745,
"text": "10"
},
{
"code": null,
"e": 36765,
"s": 36750,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 36775,
"s": 36765,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36787,
"s": 36775,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36801,
"s": 36787,
"text": "princiraj1992"
},
{
"code": null,
"e": 36814,
"s": 36801,
"text": "todaysgaurav"
},
{
"code": null,
"e": 36834,
"s": 36814,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 36847,
"s": 36834,
"text": "simmytarika5"
},
{
"code": null,
"e": 36854,
"s": 36847,
"text": "series"
},
{
"code": null,
"e": 36865,
"s": 36854,
"text": "series-sum"
},
{
"code": null,
"e": 36878,
"s": 36865,
"text": "Mathematical"
},
{
"code": null,
"e": 36891,
"s": 36878,
"text": "Mathematical"
},
{
"code": null,
"e": 36898,
"s": 36891,
"text": "series"
},
{
"code": null,
"e": 36996,
"s": 36898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37040,
"s": 36996,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 37071,
"s": 37040,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 37096,
"s": 37071,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 37140,
"s": 37096,
"text": "Generate all permutation of a set in Python"
},
{
"code": null,
"e": 37172,
"s": 37140,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 37236,
"s": 37172,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 37269,
"s": 37236,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 37311,
"s": 37269,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 37357,
"s": 37311,
"text": "Merge two sorted arrays with O(1) extra space"
}
] |
C# | UInt16 Struct - GeeksforGeeks | 01 May, 2019
In C#, UInt16 struct is used to represent 16-bit unsigned integers(also termed as ushort data type) starting from range 0 to 65535. It provides different types of method to perform various actions like to compare instances of this type, convert the value of an instance to its string representation, convert the string representation of a number to an instance of this type, etc. This struct is defined under System namespace. UInt16 struct inherits the ValueType class which inherits the Object class.
Example:
// C# program to illustrate the // fields of UInt16 structusing System; class GFG { // Main Method static public void Main() { // Unsigned 16-bit integer ushort val = 295; // Checking the unsigned integer if (val.Equals(UInt16.MinValue)) { Console.WriteLine("Equal to MinValue..!"); } else if (val.Equals(UInt16.MaxValue)) { Console.WriteLine("Equal to MaxValue"); } else { Console.WriteLine("Not equal"); } }}
Not equal
Example:
// C# program to illustrate how to get the hash // code of the 16-bit Unsigned integerusing System; class GFG { // Main Method static public void Main() { // UInt16 variable ulong myval = 545; // Get the hash code // Using GetHashCode Method int res = myval.GetHashCode(); Console.WriteLine("The hash code of myval is: {0}", res); }}
The hash code of myval is: 545
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.uint16?view=netframework-4.8
CSharp-UInt16-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | Replace() Method
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Data Types | [
{
"code": null,
"e": 25619,
"s": 25591,
"text": "\n01 May, 2019"
},
{
"code": null,
"e": 26122,
"s": 25619,
"text": "In C#, UInt16 struct is used to represent 16-bit unsigned integers(also termed as ushort data type) starting from range 0 to 65535. It provides different types of method to perform various actions like to compare instances of this type, convert the value of an instance to its string representation, convert the string representation of a number to an instance of this type, etc. This struct is defined under System namespace. UInt16 struct inherits the ValueType class which inherits the Object class."
},
{
"code": null,
"e": 26131,
"s": 26122,
"text": "Example:"
},
{
"code": "// C# program to illustrate the // fields of UInt16 structusing System; class GFG { // Main Method static public void Main() { // Unsigned 16-bit integer ushort val = 295; // Checking the unsigned integer if (val.Equals(UInt16.MinValue)) { Console.WriteLine(\"Equal to MinValue..!\"); } else if (val.Equals(UInt16.MaxValue)) { Console.WriteLine(\"Equal to MaxValue\"); } else { Console.WriteLine(\"Not equal\"); } }}",
"e": 26685,
"s": 26131,
"text": null
},
{
"code": null,
"e": 26696,
"s": 26685,
"text": "Not equal\n"
},
{
"code": null,
"e": 26705,
"s": 26696,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to get the hash // code of the 16-bit Unsigned integerusing System; class GFG { // Main Method static public void Main() { // UInt16 variable ulong myval = 545; // Get the hash code // Using GetHashCode Method int res = myval.GetHashCode(); Console.WriteLine(\"The hash code of myval is: {0}\", res); }}",
"e": 27102,
"s": 26705,
"text": null
},
{
"code": null,
"e": 27134,
"s": 27102,
"text": "The hash code of myval is: 545\n"
},
{
"code": null,
"e": 27145,
"s": 27134,
"text": "Reference:"
},
{
"code": null,
"e": 27225,
"s": 27145,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.uint16?view=netframework-4.8"
},
{
"code": null,
"e": 27246,
"s": 27225,
"text": "CSharp-UInt16-Struct"
},
{
"code": null,
"e": 27249,
"s": 27246,
"text": "C#"
},
{
"code": null,
"e": 27347,
"s": 27249,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27362,
"s": 27347,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27384,
"s": 27362,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27407,
"s": 27384,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27453,
"s": 27407,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27475,
"s": 27453,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 27497,
"s": 27475,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27515,
"s": 27497,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27555,
"s": 27515,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27586,
"s": 27555,
"text": "Introduction to .NET Framework"
}
] |
Ext.js - Fonts | Ext.js provides the facility to use different font packages. Font packages are used to add different classes for icons available in the package.
Font-Awesome
Font-Pictos
ExtJS new theme, Triton, has an inbuilt font family font-awesome included in the framework itself, hence we do not need any explicit requirement for the font-awesome stylesheet.
Following is an example of using Font-Awesome classes in the Triton theme.
Font-Awesome with Triton theme
When we are using any other theme apart from Triton, we need or require to add a stylesheet for font-awesome explicitly.
Following is an example of using Font-Awesome classes without the Triton theme.
Font-Awesome with normal theme(Any theme other then Triton theme)
Font-pictos is not included in the framework for ExtJS, hence we have to require the same. Only licenced users of Sencha will have the benefit to use font-pictos.
Step 1 − Require font-pictos class using the following command.
"requires": ["font-pictos"]
Step 2 − Now add pictos classes as −
iconCls: 'pictos pictos-home'
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2168,
"s": 2023,
"text": "Ext.js provides the facility to use different font packages. Font packages are used to add different classes for icons available in the package."
},
{
"code": null,
"e": 2181,
"s": 2168,
"text": "Font-Awesome"
},
{
"code": null,
"e": 2193,
"s": 2181,
"text": "Font-Pictos"
},
{
"code": null,
"e": 2371,
"s": 2193,
"text": "ExtJS new theme, Triton, has an inbuilt font family font-awesome included in the framework itself, hence we do not need any explicit requirement for the font-awesome stylesheet."
},
{
"code": null,
"e": 2446,
"s": 2371,
"text": "Following is an example of using Font-Awesome classes in the Triton theme."
},
{
"code": null,
"e": 2477,
"s": 2446,
"text": "Font-Awesome with Triton theme"
},
{
"code": null,
"e": 2598,
"s": 2477,
"text": "When we are using any other theme apart from Triton, we need or require to add a stylesheet for font-awesome explicitly."
},
{
"code": null,
"e": 2678,
"s": 2598,
"text": "Following is an example of using Font-Awesome classes without the Triton theme."
},
{
"code": null,
"e": 2744,
"s": 2678,
"text": "Font-Awesome with normal theme(Any theme other then Triton theme)"
},
{
"code": null,
"e": 2907,
"s": 2744,
"text": "Font-pictos is not included in the framework for ExtJS, hence we have to require the same. Only licenced users of Sencha will have the benefit to use font-pictos."
},
{
"code": null,
"e": 2971,
"s": 2907,
"text": "Step 1 − Require font-pictos class using the following command."
},
{
"code": null,
"e": 3000,
"s": 2971,
"text": "\"requires\": [\"font-pictos\"]\n"
},
{
"code": null,
"e": 3037,
"s": 3000,
"text": "Step 2 − Now add pictos classes as −"
},
{
"code": null,
"e": 3068,
"s": 3037,
"text": "iconCls: 'pictos pictos-home'\n"
},
{
"code": null,
"e": 3075,
"s": 3068,
"text": " Print"
},
{
"code": null,
"e": 3086,
"s": 3075,
"text": " Add Notes"
}
] |
Tryit Editor v3.7 | Tryit: HTML image | [] |
Reverse a string using the pointer in C++ | This article reverse a string using the pointer in C++ coding, First, it calculates the length of a pointer to string then run a for loop in decrement order to display the reverse string as follows;
Live Demo
#include <string.h>
#include <iostream>
using namespace std;
int main(){
char *str="ajaykumar";
cout<<"original string::"<<str;
cout<<endl<<"String after reverse::";
for(int i=(strlen(str)-1);i>=0;i--){
cout<<str[i];
}
return 0;
}
This above program prints the to be supplied string “ajaykumar” in reverse order as follows.
Original string::ajaykumar
String after reverse::ramukyaja | [
{
"code": null,
"e": 1261,
"s": 1062,
"text": "This article reverse a string using the pointer in C++ coding, First, it calculates the length of a pointer to string then run a for loop in decrement order to display the reverse string as follows;"
},
{
"code": null,
"e": 1272,
"s": 1261,
"text": " Live Demo"
},
{
"code": null,
"e": 1527,
"s": 1272,
"text": "#include <string.h>\n#include <iostream>\nusing namespace std;\nint main(){\n char *str=\"ajaykumar\";\n cout<<\"original string::\"<<str;\n cout<<endl<<\"String after reverse::\";\n for(int i=(strlen(str)-1);i>=0;i--){\n cout<<str[i];\n }\n return 0;\n}"
},
{
"code": null,
"e": 1620,
"s": 1527,
"text": "This above program prints the to be supplied string “ajaykumar” in reverse order as follows."
},
{
"code": null,
"e": 1679,
"s": 1620,
"text": "Original string::ajaykumar\nString after reverse::ramukyaja"
}
] |
Google Charts - Basic Line Chart | Following is an example of a basic line chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
googlecharts_line_basic.htm
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart','line']});
</script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script language = "JavaScript">
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number', 'Tokyo');
data.addColumn('number', 'New York');
data.addColumn('number', 'Berlin');
data.addColumn('number', 'London');
data.addRows([
['Jan', 7.0, -0.2, -0.9, 3.9],
['Feb', 6.9, 0.8, 0.6, 4.2],
['Mar', 9.5, 5.7, 3.5, 5.7],
['Apr', 14.5, 11.3, 8.4, 8.5],
['May', 18.2, 17.0, 13.5, 11.9],
['Jun', 21.5, 22.0, 17.0, 15.2],
['Jul', 25.2, 24.8, 18.6, 17.0],
['Aug', 26.5, 24.1, 17.9, 16.6],
['Sep', 23.3, 20.1, 14.3, 14.2],
['Oct', 18.3, 14.1, 9.0, 10.3],
['Nov', 13.9, 8.6, 3.9, 6.6],
['Dec', 9.6, 2.5, 1.0, 4.8]
]);
// Set chart options
var options = {'title' : 'Average Temperatures of Cities',
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Temperature'
},
'width':550,
'height':400
};
// Instantiate and draw the chart.
var chart = new google.visualization.LineChart(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2452,
"s": 2261,
"text": "Following is an example of a basic line chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example."
},
{
"code": null,
"e": 2480,
"s": 2452,
"text": "googlecharts_line_basic.htm"
},
{
"code": null,
"e": 4583,
"s": 2480,
"text": "<html>\n <head>\n <title>Google Charts Tutorial</title>\n <script type = \"text/javascript\" src = \"https://www.gstatic.com/charts/loader.js\">\n </script>\n <script type = \"text/javascript\">\n google.charts.load('current', {packages: ['corechart','line']}); \n </script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\">\n </div>\n <script language = \"JavaScript\">\n function drawChart() {\n // Define the chart to be drawn.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Month');\n data.addColumn('number', 'Tokyo');\n data.addColumn('number', 'New York');\n data.addColumn('number', 'Berlin');\n data.addColumn('number', 'London');\n data.addRows([\n ['Jan', 7.0, -0.2, -0.9, 3.9],\n ['Feb', 6.9, 0.8, 0.6, 4.2],\n ['Mar', 9.5, 5.7, 3.5, 5.7],\n ['Apr', 14.5, 11.3, 8.4, 8.5],\n ['May', 18.2, 17.0, 13.5, 11.9],\n ['Jun', 21.5, 22.0, 17.0, 15.2],\n \n ['Jul', 25.2, 24.8, 18.6, 17.0],\n ['Aug', 26.5, 24.1, 17.9, 16.6],\n ['Sep', 23.3, 20.1, 14.3, 14.2],\n ['Oct', 18.3, 14.1, 9.0, 10.3],\n ['Nov', 13.9, 8.6, 3.9, 6.6],\n ['Dec', 9.6, 2.5, 1.0, 4.8]\n ]);\n \n // Set chart options\n var options = {'title' : 'Average Temperatures of Cities',\n hAxis: {\n title: 'Month'\n },\n vAxis: {\n title: 'Temperature'\n }, \n 'width':550,\n 'height':400\t \n };\n\n // Instantiate and draw the chart.\n var chart = new google.visualization.LineChart(document.getElementById('container'));\n chart.draw(data, options);\n }\n google.charts.setOnLoadCallback(drawChart);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4602,
"s": 4583,
"text": "Verify the result."
},
{
"code": null,
"e": 4609,
"s": 4602,
"text": " Print"
},
{
"code": null,
"e": 4620,
"s": 4609,
"text": " Add Notes"
}
] |
Calculate Arithmetic mean in R Programming - mean() Function - GeeksforGeeks | 05 Jun, 2020
mean() function in R Language is used to calculate the arithmetic mean of the elements of the numeric vector passed to it as argument.
Syntax: mean(x, na.rm)
Parameters:x: Numeric Vectorna.rm: Boolean value to ignore NA value
Example 1:
# R program to calculate# Arithmetic mean of a vector # Creating a numeric vectorx1 <- c(1, 2, 3, 4, 5, 6)x2 <-c(1.2, 2.3, 3.4, 4.5)x3 <- c(-1, -2, -3, -4, -5, -6) # Calling mean() functionmean(x1)mean(x2)mean(x3)
Output:
[1] 3.5
[1] 2.85
[1] -3.5
Example 2:
# R program to calculate# Arithmetic mean of a vector # Creating a numeric vectorx1 <- c(1, 2, 3, NA, 5, NA, NA) # Calling mean() function# including NA valuesmean(x1, na.rm = FALSE) # Calling mean() function# excluding NA valuesmean(x1, na.rm = TRUE)
Output:
[1] NA
[1] 2.75
R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming | [
{
"code": null,
"e": 24681,
"s": 24653,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 24816,
"s": 24681,
"text": "mean() function in R Language is used to calculate the arithmetic mean of the elements of the numeric vector passed to it as argument."
},
{
"code": null,
"e": 24839,
"s": 24816,
"text": "Syntax: mean(x, na.rm)"
},
{
"code": null,
"e": 24907,
"s": 24839,
"text": "Parameters:x: Numeric Vectorna.rm: Boolean value to ignore NA value"
},
{
"code": null,
"e": 24918,
"s": 24907,
"text": "Example 1:"
},
{
"code": "# R program to calculate# Arithmetic mean of a vector # Creating a numeric vectorx1 <- c(1, 2, 3, 4, 5, 6)x2 <-c(1.2, 2.3, 3.4, 4.5)x3 <- c(-1, -2, -3, -4, -5, -6) # Calling mean() functionmean(x1)mean(x2)mean(x3)",
"e": 25134,
"s": 24918,
"text": null
},
{
"code": null,
"e": 25142,
"s": 25134,
"text": "Output:"
},
{
"code": null,
"e": 25169,
"s": 25142,
"text": "[1] 3.5\n[1] 2.85\n[1] -3.5\n"
},
{
"code": null,
"e": 25180,
"s": 25169,
"text": "Example 2:"
},
{
"code": "# R program to calculate# Arithmetic mean of a vector # Creating a numeric vectorx1 <- c(1, 2, 3, NA, 5, NA, NA) # Calling mean() function# including NA valuesmean(x1, na.rm = FALSE) # Calling mean() function# excluding NA valuesmean(x1, na.rm = TRUE)",
"e": 25435,
"s": 25180,
"text": null
},
{
"code": null,
"e": 25443,
"s": 25435,
"text": "Output:"
},
{
"code": null,
"e": 25460,
"s": 25443,
"text": "[1] NA\n[1] 2.75\n"
},
{
"code": null,
"e": 25476,
"s": 25460,
"text": "R Math-Function"
},
{
"code": null,
"e": 25487,
"s": 25476,
"text": "R Language"
},
{
"code": null,
"e": 25585,
"s": 25487,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25594,
"s": 25585,
"text": "Comments"
},
{
"code": null,
"e": 25607,
"s": 25594,
"text": "Old Comments"
},
{
"code": null,
"e": 25665,
"s": 25607,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 25709,
"s": 25665,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 25761,
"s": 25709,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 25813,
"s": 25761,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 25845,
"s": 25813,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 25877,
"s": 25845,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 25915,
"s": 25877,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 25950,
"s": 25915,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26008,
"s": 25950,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
Powershell - Get-ChildItem Cmdlet | Get-ChildItem cmdlet can be used to get the items or child items in one or more specific locations.
In these examples, we're see the Get-ChildItem cmdlet in action.
In this example, first we've a file test.txt in D:\temp\test with content "Welcome to TutorialsPoint.Com" and test1.txt with content "Hello World!" and "Welcome to TutorialsPoint.Com" in two lines.
Get the file details in a variable.
$A = Get-ChildItem D:\temp\test\*.txt
Get the file details using Format-Wide cmdlet.
Format-Wide -InputObject $A
You can see following output in PowerShell console.
Directory: D:\temp\test
test.txt test1.txt
Get the names of the items in current directory.
Type the following command in PowerShell ISE Console
Get-ChildItem -Name
You can see following output in PowerShell console consider being in D:\temp\Test directory.
test.csv
test.txt
test.xml
test1.txt
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2134,
"s": 2034,
"text": "Get-ChildItem cmdlet can be used to get the items or child items in one or more specific locations."
},
{
"code": null,
"e": 2199,
"s": 2134,
"text": "In these examples, we're see the Get-ChildItem cmdlet in action."
},
{
"code": null,
"e": 2397,
"s": 2199,
"text": "In this example, first we've a file test.txt in D:\\temp\\test with content \"Welcome to TutorialsPoint.Com\" and test1.txt with content \"Hello World!\" and \"Welcome to TutorialsPoint.Com\" in two lines."
},
{
"code": null,
"e": 2433,
"s": 2397,
"text": "Get the file details in a variable."
},
{
"code": null,
"e": 2471,
"s": 2433,
"text": "$A = Get-ChildItem D:\\temp\\test\\*.txt"
},
{
"code": null,
"e": 2518,
"s": 2471,
"text": "Get the file details using Format-Wide cmdlet."
},
{
"code": null,
"e": 2546,
"s": 2518,
"text": "Format-Wide -InputObject $A"
},
{
"code": null,
"e": 2598,
"s": 2546,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 2697,
"s": 2598,
"text": " Directory: D:\\temp\\test\ntest.txt test1.txt \n"
},
{
"code": null,
"e": 2746,
"s": 2697,
"text": "Get the names of the items in current directory."
},
{
"code": null,
"e": 2799,
"s": 2746,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 2819,
"s": 2799,
"text": "Get-ChildItem -Name"
},
{
"code": null,
"e": 2912,
"s": 2819,
"text": "You can see following output in PowerShell console consider being in D:\\temp\\Test directory."
},
{
"code": null,
"e": 2950,
"s": 2912,
"text": "test.csv\ntest.txt\ntest.xml\ntest1.txt\n"
},
{
"code": null,
"e": 2985,
"s": 2950,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3006,
"s": 2985,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 3041,
"s": 3006,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3054,
"s": 3041,
"text": " Vijay Saini"
},
{
"code": null,
"e": 3091,
"s": 3054,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3103,
"s": 3091,
"text": " Fettah Ben"
},
{
"code": null,
"e": 3110,
"s": 3103,
"text": " Print"
},
{
"code": null,
"e": 3121,
"s": 3110,
"text": " Add Notes"
}
] |
How to Set opacity for View in Android? | This example demonstrates how to Set opacity for View 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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="86dp"
android:background="#011ffd"
android:gravity="center"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="Click here to set view Alpha/Opacity of in android programmatically" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView txt;
Button btn;
ObjectAnimator objectanimator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.button1);
objectanimator = ObjectAnimator.ofFloat(txt,"Opacity",0.6f);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
objectanimator.setDuration(4000);
objectanimator.start();
}
});
}
}
Step 4 − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code. | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "This example demonstrates how to Set opacity for View in Android ."
},
{
"code": null,
"e": 1259,
"s": 1129,
"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": 1325,
"s": 1259,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2436,
"s": 1325,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout 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:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"100dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"86dp\"\n android:background=\"#011ffd\"\n android:gravity=\"center\"\n android:text=\"TextView\"\n android:textAppearance=\"?android:attr/textAppearanceLarge\" />\n <Button\n android:id=\"@+id/button1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/textView1\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"48dp\"\n android:text=\"Click here to set view Alpha/Opacity of in android programmatically\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2494,
"s": 2436,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3425,
"s": 2494,
"text": "package com.example.sample;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.animation.ObjectAnimator;\nimport android.app.Activity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView txt;\n Button btn;\n ObjectAnimator objectanimator;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n txt = (TextView)findViewById(R.id.textView1);\n btn = (Button)findViewById(R.id.button1);\n objectanimator = ObjectAnimator.ofFloat(txt,\"Opacity\",0.6f);\n btn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n objectanimator.setDuration(4000);\n objectanimator.start();\n }\n });\n }\n}"
},
{
"code": null,
"e": 3491,
"s": 3425,
"text": "Step 4 − Add the following code to Manifests/AndroidManifest.xml"
},
{
"code": null,
"e": 4168,
"s": 3491,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4515,
"s": 4168,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4556,
"s": 4515,
"text": "Click here to download the project code."
}
] |
Installing MATLAB on MacOS | 04 Jul, 2021
MATLAB stands for “Matrix Laboratory” and it is a numerical computing environment and fourth-generation programming language. designed by Math Works, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, and FORTRAN.
Now, we will see how to download and install MATLAB on MacOS.
For Installation of MATLAB your system must satisfy the following minimum requirements :
Operating system: macOS Catalina (10.15), macOS Mojave (10.14), or macOS High Sierra (10.13.6).
Processor: Any Intel x86-64 processor
RAM required: At least 4 GB of RAM is required
Disk Space: MATLAB installation may take up to 27 GB of disk space
If your system completes the above minimum requirement then you can install MATLAB on your system else you have to upgrade your system before the installation of MATLAB.
Step 1: Go to your Mathworks account homepage.
Step 2: Locate the License you would like to download products for in the list.
Step 3: Click the downwards-pointing blue arrow on the same row as the license in question.
Step 4: Click the blue button on the left to download the latest release of MATLAB you have access to, or select an older license in the menu on the right.
Step 5: Choose the platform you need the installer for.
Step 6: If prompted by your browser to Run or Save the installer choose to save.
Step 7: Locate the installer in a file browser. It should be located in the default download location unless you specified another location. The installer will be named:
Mac: matlab_R20XXx_maci64.zip
To begin with the installation process you must have downloaded the MATLAB setup.
Step 1: After the extraction of the setup, an application named ‘setup’ with MATLAB icon will appear. Click on that application the following window will appear asking for your account (If you don’t already have an account create at the time of installation):
Step 2: After filling in your account details you need to read the terms and conditions and if you agree with them then fill in “Yes” and click on the next button to proceed further.
Step 3: Later you will be asked for the license to install and run the application. You have two options for the verification of the license either you attach the License file from your system or you fill in the Activation key for the verification of the license.
Note: You will need an active internet connection for verification of license using the activation key
Step 4: Then after the verification of the License you will be asked for the destination where the setup is to be installed , you can either change it or keep the same as per your preference.
Step 5: Now you are asked to fill the products you want to use in your MATLAB. You should probably select all services in case you want to use some service in the future. Then click on next.
Step 6: For the final step you will be asked whether you want to share the experience information to Mathworks .
Step 7: After that wait for the installation process to be finished and then open the MATLAB application installed to confirm the proper functioning for the first time.
Now the MATLAB is successfully installed in your system.
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 418,
"s": 52,
"text": "MATLAB stands for “Matrix Laboratory” and it is a numerical computing environment and fourth-generation programming language. designed by Math Works, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, and FORTRAN."
},
{
"code": null,
"e": 480,
"s": 418,
"text": "Now, we will see how to download and install MATLAB on MacOS."
},
{
"code": null,
"e": 569,
"s": 480,
"text": "For Installation of MATLAB your system must satisfy the following minimum requirements :"
},
{
"code": null,
"e": 665,
"s": 569,
"text": "Operating system: macOS Catalina (10.15), macOS Mojave (10.14), or macOS High Sierra (10.13.6)."
},
{
"code": null,
"e": 703,
"s": 665,
"text": "Processor: Any Intel x86-64 processor"
},
{
"code": null,
"e": 750,
"s": 703,
"text": "RAM required: At least 4 GB of RAM is required"
},
{
"code": null,
"e": 817,
"s": 750,
"text": "Disk Space: MATLAB installation may take up to 27 GB of disk space"
},
{
"code": null,
"e": 987,
"s": 817,
"text": "If your system completes the above minimum requirement then you can install MATLAB on your system else you have to upgrade your system before the installation of MATLAB."
},
{
"code": null,
"e": 1034,
"s": 987,
"text": "Step 1: Go to your Mathworks account homepage."
},
{
"code": null,
"e": 1114,
"s": 1034,
"text": "Step 2: Locate the License you would like to download products for in the list."
},
{
"code": null,
"e": 1206,
"s": 1114,
"text": "Step 3: Click the downwards-pointing blue arrow on the same row as the license in question."
},
{
"code": null,
"e": 1362,
"s": 1206,
"text": "Step 4: Click the blue button on the left to download the latest release of MATLAB you have access to, or select an older license in the menu on the right."
},
{
"code": null,
"e": 1418,
"s": 1362,
"text": "Step 5: Choose the platform you need the installer for."
},
{
"code": null,
"e": 1499,
"s": 1418,
"text": "Step 6: If prompted by your browser to Run or Save the installer choose to save."
},
{
"code": null,
"e": 1669,
"s": 1499,
"text": "Step 7: Locate the installer in a file browser. It should be located in the default download location unless you specified another location. The installer will be named:"
},
{
"code": null,
"e": 1699,
"s": 1669,
"text": "Mac: matlab_R20XXx_maci64.zip"
},
{
"code": null,
"e": 1781,
"s": 1699,
"text": "To begin with the installation process you must have downloaded the MATLAB setup."
},
{
"code": null,
"e": 2041,
"s": 1781,
"text": "Step 1: After the extraction of the setup, an application named ‘setup’ with MATLAB icon will appear. Click on that application the following window will appear asking for your account (If you don’t already have an account create at the time of installation):"
},
{
"code": null,
"e": 2224,
"s": 2041,
"text": "Step 2: After filling in your account details you need to read the terms and conditions and if you agree with them then fill in “Yes” and click on the next button to proceed further."
},
{
"code": null,
"e": 2488,
"s": 2224,
"text": "Step 3: Later you will be asked for the license to install and run the application. You have two options for the verification of the license either you attach the License file from your system or you fill in the Activation key for the verification of the license."
},
{
"code": null,
"e": 2591,
"s": 2488,
"text": "Note: You will need an active internet connection for verification of license using the activation key"
},
{
"code": null,
"e": 2783,
"s": 2591,
"text": "Step 4: Then after the verification of the License you will be asked for the destination where the setup is to be installed , you can either change it or keep the same as per your preference."
},
{
"code": null,
"e": 2974,
"s": 2783,
"text": "Step 5: Now you are asked to fill the products you want to use in your MATLAB. You should probably select all services in case you want to use some service in the future. Then click on next."
},
{
"code": null,
"e": 3087,
"s": 2974,
"text": "Step 6: For the final step you will be asked whether you want to share the experience information to Mathworks ."
},
{
"code": null,
"e": 3257,
"s": 3087,
"text": "Step 7: After that wait for the installation process to be finished and then open the MATLAB application installed to confirm the proper functioning for the first time. "
},
{
"code": null,
"e": 3315,
"s": 3257,
"text": "Now the MATLAB is successfully installed in your system. "
},
{
"code": null,
"e": 3322,
"s": 3315,
"text": "Picked"
},
{
"code": null,
"e": 3329,
"s": 3322,
"text": "MATLAB"
}
] |
NavigableString class – Python Beautifulsoup | 25 Oct, 2020
NavigableString class is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. A string corresponds to a bit of text within a tag. Beautiful Soup uses the NavigableString class to contain these bits of text.
Syntax:
<tag> String here </tag>
Below given examples explain the concept of NavigableString class in Beautiful Soup. Example 1: In this example, we are going to see the type of a string.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with a HTML pagesoup = BeautifulSoup(''' <html> <h2> Heading 1 </h2> <h1> Heading 2 </h1> </html> ''', "lxml") # Get the whole h2 tagtag = soup.h2 # Get the string inside the tagstring = tag.string # Print the typeprint(type(string))
Output:
<class 'bs4.element.NavigableString'>
Example 2: In this example we are going to convert the NavigableString to a Unicode string.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with a HTML pagesoup = BeautifulSoup(''' <html> <h2> Heading 1 </h2> <h1> Heading 2 </h1> </html> ''', "lxml") # Get the whole h2 tagtag = soup.h2 # Get the string inside the tag and convert # it into stringstring = str(tag.string) # Print the typeprint(type(string))
Output:
<type 'str'>
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Oct, 2020"
},
{
"code": null,
"e": 369,
"s": 28,
"text": "NavigableString class is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. A string corresponds to a bit of text within a tag. Beautiful Soup uses the NavigableString class to contain these bits of text."
},
{
"code": null,
"e": 378,
"s": 369,
"text": "Syntax: "
},
{
"code": null,
"e": 404,
"s": 378,
"text": "<tag> String here </tag>\n"
},
{
"code": null,
"e": 559,
"s": 404,
"text": "Below given examples explain the concept of NavigableString class in Beautiful Soup. Example 1: In this example, we are going to see the type of a string."
},
{
"code": null,
"e": 567,
"s": 559,
"text": "Python3"
},
{
"code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with a HTML pagesoup = BeautifulSoup(''' <html> <h2> Heading 1 </h2> <h1> Heading 2 </h1> </html> ''', \"lxml\") # Get the whole h2 tagtag = soup.h2 # Get the string inside the tagstring = tag.string # Print the typeprint(type(string))",
"e": 905,
"s": 567,
"text": null
},
{
"code": null,
"e": 914,
"s": 905,
"text": "Output: "
},
{
"code": null,
"e": 953,
"s": 914,
"text": "<class 'bs4.element.NavigableString'>\n"
},
{
"code": null,
"e": 1045,
"s": 953,
"text": "Example 2: In this example we are going to convert the NavigableString to a Unicode string."
},
{
"code": null,
"e": 1053,
"s": 1045,
"text": "Python3"
},
{
"code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with a HTML pagesoup = BeautifulSoup(''' <html> <h2> Heading 1 </h2> <h1> Heading 2 </h1> </html> ''', \"lxml\") # Get the whole h2 tagtag = soup.h2 # Get the string inside the tag and convert # it into stringstring = str(tag.string) # Print the typeprint(type(string))",
"e": 1425,
"s": 1053,
"text": null
},
{
"code": null,
"e": 1434,
"s": 1425,
"text": "Output: "
},
{
"code": null,
"e": 1448,
"s": 1434,
"text": "<type 'str'>\n"
},
{
"code": null,
"e": 1461,
"s": 1448,
"text": "Web-scraping"
},
{
"code": null,
"e": 1468,
"s": 1461,
"text": "Python"
}
] |
Program for length of a string using recursion | 13 Jul, 2022
Given a string calculate length of the string using recursion. Examples:
Input : str = "abcd"
Output :4
Input : str = "GEEKSFORGEEKS"
Output :13
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
We have discussed 5 Different methods to find length of a string in C++ How to find length of a string without string.h and loop in C?Algorithm
recLen(str)
{
If str is NULL
return 0
Else
return 1 + recLen(str + 1)
}
C++
Java
Python3
C#
PHP
Javascript
// CPP program to calculate length of // a string using recursion#include <bits/stdc++.h>using namespace std; /* Function to calculate length */int recLen(char* str) { // if we reach at the end of the string if (*str == '\0') return 0; else return 1 + recLen(str + 1); } /* Driver program to test above function */int main(){ char str[] = "GeeksforGeeks"; cout << recLen(str); return 0;}
// java program to calculate length of // a string using recursionimport java.util.*; public class GFG{ /* Function to calculate length */ private static int recLen(String str) { // if we reach at the end of the string if (str.equals("")) return 0; else return recLen(str.substring(1)) + 1; } /* Driver program to test above function */ public static void main(String[] args) { String str ="GeeksforGeeks"; System.out.println(recLen(str)); }} // This code is contributed by Sam007.
# Python program to calculate # length of a string using # recursionstr = "GeeksforGeeks" # Function to # calculate lengthdef string_length(str) : # if we reach at the # end of the string if str == '': return 0 else : return 1 + string_length(str[1:]) # Driver Codeprint (string_length(str)) # This code is contributed by# Prabhjeet
// C# program to calculate length of // a string using recursionusing System; public class GFG{ /* Function to calculate length */ private static int recLen(string str) { // if we reach at the end of the string if (str.Equals("")) return 0; else return recLen(str.Substring(1)) + 1; } /* Driver program to test above function */ public static void Main() { string str ="GeeksforGeeks"; Console.WriteLine(recLen(str)); }} // This code is contributed by vt_m.
<?php// PHP program to calculate // length of a string using // recursion // Function to // calculate lengthfunction recLen(&$str, $i) { // if we reach at the // end of the string if ($i == strlen($str)) return 0; else return 1 + recLen($str, $i + 1); } // Driver Code$str = "GeeksforGeeks";echo (recLen($str, 0)); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // JavaScript program to calculate length of // a string using recursion /* Function to calculate length */ function recLen(str) { // if we reach at the end of the string if (str == "") return 0; else return recLen(str.substring(1)) + 1; } // Driver code let str ="GeeksforGeeks"; document.write(recLen(str)); </script>
Output:
13
Time Complexity : O(n) Auxiliary Space : O(n) for recursion call stack.
Since this solution requires extra space and function call overhead, it is not recommended to use it in practice.
manishshaw1
prabhjeetbhabra
susmitakundugoaldanga
Recursion
Strings
Strings
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Jul, 2022"
},
{
"code": null,
"e": 128,
"s": 53,
"text": "Given a string calculate length of the string using recursion. Examples: "
},
{
"code": null,
"e": 201,
"s": 128,
"text": "Input : str = \"abcd\"\nOutput :4\n\nInput : str = \"GEEKSFORGEEKS\"\nOutput :13"
},
{
"code": null,
"e": 212,
"s": 203,
"text": "Chapters"
},
{
"code": null,
"e": 239,
"s": 212,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 289,
"s": 239,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 312,
"s": 289,
"text": "captions off, selected"
},
{
"code": null,
"e": 320,
"s": 312,
"text": "English"
},
{
"code": null,
"e": 344,
"s": 320,
"text": "This is a modal window."
},
{
"code": null,
"e": 413,
"s": 344,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 435,
"s": 413,
"text": "End of dialog window."
},
{
"code": null,
"e": 581,
"s": 435,
"text": "We have discussed 5 Different methods to find length of a string in C++ How to find length of a string without string.h and loop in C?Algorithm "
},
{
"code": null,
"e": 674,
"s": 581,
"text": "recLen(str)\n{\n If str is NULL \n return 0\n Else \n return 1 + recLen(str + 1)\n}"
},
{
"code": null,
"e": 680,
"s": 676,
"text": "C++"
},
{
"code": null,
"e": 685,
"s": 680,
"text": "Java"
},
{
"code": null,
"e": 693,
"s": 685,
"text": "Python3"
},
{
"code": null,
"e": 696,
"s": 693,
"text": "C#"
},
{
"code": null,
"e": 700,
"s": 696,
"text": "PHP"
},
{
"code": null,
"e": 711,
"s": 700,
"text": "Javascript"
},
{
"code": "// CPP program to calculate length of // a string using recursion#include <bits/stdc++.h>using namespace std; /* Function to calculate length */int recLen(char* str) { // if we reach at the end of the string if (*str == '\\0') return 0; else return 1 + recLen(str + 1); } /* Driver program to test above function */int main(){ char str[] = \"GeeksforGeeks\"; cout << recLen(str); return 0;}",
"e": 1137,
"s": 711,
"text": null
},
{
"code": "// java program to calculate length of // a string using recursionimport java.util.*; public class GFG{ /* Function to calculate length */ private static int recLen(String str) { // if we reach at the end of the string if (str.equals(\"\")) return 0; else return recLen(str.substring(1)) + 1; } /* Driver program to test above function */ public static void main(String[] args) { String str =\"GeeksforGeeks\"; System.out.println(recLen(str)); }} // This code is contributed by Sam007.",
"e": 1722,
"s": 1137,
"text": null
},
{
"code": "# Python program to calculate # length of a string using # recursionstr = \"GeeksforGeeks\" # Function to # calculate lengthdef string_length(str) : # if we reach at the # end of the string if str == '': return 0 else : return 1 + string_length(str[1:]) # Driver Codeprint (string_length(str)) # This code is contributed by# Prabhjeet",
"e": 2095,
"s": 1722,
"text": null
},
{
"code": "// C# program to calculate length of // a string using recursionusing System; public class GFG{ /* Function to calculate length */ private static int recLen(string str) { // if we reach at the end of the string if (str.Equals(\"\")) return 0; else return recLen(str.Substring(1)) + 1; } /* Driver program to test above function */ public static void Main() { string str =\"GeeksforGeeks\"; Console.WriteLine(recLen(str)); }} // This code is contributed by vt_m.",
"e": 2656,
"s": 2095,
"text": null
},
{
"code": "<?php// PHP program to calculate // length of a string using // recursion // Function to // calculate lengthfunction recLen(&$str, $i) { // if we reach at the // end of the string if ($i == strlen($str)) return 0; else return 1 + recLen($str, $i + 1); } // Driver Code$str = \"GeeksforGeeks\";echo (recLen($str, 0)); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 3104,
"s": 2656,
"text": null
},
{
"code": "<script> // JavaScript program to calculate length of // a string using recursion /* Function to calculate length */ function recLen(str) { // if we reach at the end of the string if (str == \"\") return 0; else return recLen(str.substring(1)) + 1; } // Driver code let str =\"GeeksforGeeks\"; document.write(recLen(str)); </script>",
"e": 3521,
"s": 3104,
"text": null
},
{
"code": null,
"e": 3530,
"s": 3521,
"text": "Output: "
},
{
"code": null,
"e": 3533,
"s": 3530,
"text": "13"
},
{
"code": null,
"e": 3607,
"s": 3533,
"text": "Time Complexity : O(n) Auxiliary Space : O(n) for recursion call stack. "
},
{
"code": null,
"e": 3722,
"s": 3607,
"text": "Since this solution requires extra space and function call overhead, it is not recommended to use it in practice. "
},
{
"code": null,
"e": 3734,
"s": 3722,
"text": "manishshaw1"
},
{
"code": null,
"e": 3750,
"s": 3734,
"text": "prabhjeetbhabra"
},
{
"code": null,
"e": 3772,
"s": 3750,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 3782,
"s": 3772,
"text": "Recursion"
},
{
"code": null,
"e": 3790,
"s": 3782,
"text": "Strings"
},
{
"code": null,
"e": 3798,
"s": 3790,
"text": "Strings"
},
{
"code": null,
"e": 3808,
"s": 3798,
"text": "Recursion"
}
] |
How to Sort Numeric Array using JavaScript ? | 27 Jan, 2022
The JavaScript Array.sort() method is used to sort the array elements in-place and returns the sorted array. This function sorts the elements in string format. It will work good for string array but not for numbers. For example: if numbers are sorted as string, than “75” is bigger than “200”.Example:
Input : [12, 25, 31, 23, 75, 81, 100]
Wrong Output : [100, 12, 23, 25, 31, 75, 81]
Correct Output : [12, 23, 25, 31, 75, 81, 100]
Example: This example sorts the array elements in string format.
javascript
<script> // Declare and initialize original arrayvar marks = [12, 25, 31, 23, 75, 81, 100]; // Print Before Sorting Arraydocument.write("Original Array</br>");document.write(marks); document.write("</br>"); // Call sort functionmarks.sort(); document.write("</br>After Sorting in Ascending Order</br>"); // Print Sorted Numeric Arraydocument.write(marks); </script>
Output:
Original Array
12,25,31,23,75,81,100
After Sorting in Ascending Order
100,12,23,25,31,75,81
Then, how to sort number array elements ? There are two approaches to sort the number array in ascending order.
Using Compare Function
By Creating Loops
Using Compare Function: We can create a Compare function that return negative, zero, or positive values. Syntax:
function(a, b){return a - b}
Negative Value ( a > b) => a will be Place before b
zero value (a == b) => No Change
Positive Value (a < b ) => a will be place after b
Example: This example uses compare function to sort the array elements in ascending order.
javascript
<script> // Declare and initialize an Arrayvar marks = [12, 25, 31, 23, 75, 81, 100]; // Print Before sorting arraydocument.write("Original Array</br>");document.write(marks); document.write("</br>"); // Sort elements using compare methodmarks.sort(function(a, b){return a - b}); document.write("</br>After sorting in Ascending order</br>"); // Print sorted Numeric arraydocument.write(marks); </script>
Output:
Original Array
12,25,31,23,75,81,100
After sorting in Ascending order
12,23,25,31,75,81,100
Now, we would like to sort the array in Descending order than we have to change the compare function.Syntax:
function(a, b){return b - a}
Negative Value ( b < a) => a will be Place after b
zero value (a == b) => No Change
Positive Value (b > a ) => a will be place before b
Example: This example uses compare function to sort the array elements in descending order.
javascript
<script> // Declare and initialize an Arrayvar marks = [12, 25, 31, 23, 75, 81, 100]; // Print Before sorting arraydocument.write("Original Array</br>");document.write(marks); document.write("</br>"); // Sort elements using compare methodmarks.sort(function(a, b){return b - a}); document.write("</br>After sorting in Ascending order</br>"); // Print sorted Numeric arraydocument.write(marks); </script>
Output:
Original Array
12,25,31,23,75,81,100
After sorting in Ascending order
100,81,75,31,25,23,12
Creating Loops: We can also use loops to sort the array elements. Here, we will use bubble sort (simple sorting technique) to sort the array elements in ascending order.Example:
javascript
<script> // Sorting functionfunction Numeric_sort(ar) { var i = 0, j; while (i < ar.length) { j = i + 1; while (j < ar.length) { if (ar[j] < ar[i]) { var temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } j++; } i++; }} // Original Arrayvar arr = [1, 15, 10, 45, 27, 100]; // Print Before sorting arraydocument.write("Original Array</br>");document.write(arr); document.write("</br>"); // Function callNumeric_sort(arr); document.write("</br>Sorted Array</br>"); // Print sorted Numeric arraydocument.write(arr); </script>
Output:
Original Array
1,15,10,45,27,100
Sorted Array
1,10,15,27,45,100
Akanksha_Rai
surindertarika1234
sumitgumber28
javascript-array
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "The JavaScript Array.sort() method is used to sort the array elements in-place and returns the sorted array. This function sorts the elements in string format. It will work good for string array but not for numbers. For example: if numbers are sorted as string, than “75” is bigger than “200”.Example: "
},
{
"code": null,
"e": 473,
"s": 332,
"text": "Input : [12, 25, 31, 23, 75, 81, 100]\nWrong Output : [100, 12, 23, 25, 31, 75, 81]\nCorrect Output : [12, 23, 25, 31, 75, 81, 100]"
},
{
"code": null,
"e": 540,
"s": 473,
"text": "Example: This example sorts the array elements in string format. "
},
{
"code": null,
"e": 551,
"s": 540,
"text": "javascript"
},
{
"code": "<script> // Declare and initialize original arrayvar marks = [12, 25, 31, 23, 75, 81, 100]; // Print Before Sorting Arraydocument.write(\"Original Array</br>\");document.write(marks); document.write(\"</br>\"); // Call sort functionmarks.sort(); document.write(\"</br>After Sorting in Ascending Order</br>\"); // Print Sorted Numeric Arraydocument.write(marks); </script>",
"e": 933,
"s": 551,
"text": null
},
{
"code": null,
"e": 943,
"s": 933,
"text": "Output: "
},
{
"code": null,
"e": 1036,
"s": 943,
"text": "Original Array\n12,25,31,23,75,81,100\n\nAfter Sorting in Ascending Order\n100,12,23,25,31,75,81"
},
{
"code": null,
"e": 1150,
"s": 1036,
"text": "Then, how to sort number array elements ? There are two approaches to sort the number array in ascending order. "
},
{
"code": null,
"e": 1173,
"s": 1150,
"text": "Using Compare Function"
},
{
"code": null,
"e": 1191,
"s": 1173,
"text": "By Creating Loops"
},
{
"code": null,
"e": 1306,
"s": 1191,
"text": "Using Compare Function: We can create a Compare function that return negative, zero, or positive values. Syntax: "
},
{
"code": null,
"e": 1335,
"s": 1306,
"text": "function(a, b){return a - b}"
},
{
"code": null,
"e": 1389,
"s": 1337,
"text": "Negative Value ( a > b) => a will be Place before b"
},
{
"code": null,
"e": 1422,
"s": 1389,
"text": "zero value (a == b) => No Change"
},
{
"code": null,
"e": 1473,
"s": 1422,
"text": "Positive Value (a < b ) => a will be place after b"
},
{
"code": null,
"e": 1566,
"s": 1473,
"text": "Example: This example uses compare function to sort the array elements in ascending order. "
},
{
"code": null,
"e": 1577,
"s": 1566,
"text": "javascript"
},
{
"code": "<script> // Declare and initialize an Arrayvar marks = [12, 25, 31, 23, 75, 81, 100]; // Print Before sorting arraydocument.write(\"Original Array</br>\");document.write(marks); document.write(\"</br>\"); // Sort elements using compare methodmarks.sort(function(a, b){return a - b}); document.write(\"</br>After sorting in Ascending order</br>\"); // Print sorted Numeric arraydocument.write(marks); </script>",
"e": 2001,
"s": 1577,
"text": null
},
{
"code": null,
"e": 2011,
"s": 2001,
"text": "Output: "
},
{
"code": null,
"e": 2104,
"s": 2011,
"text": "Original Array\n12,25,31,23,75,81,100\n\nAfter sorting in Ascending order\n12,23,25,31,75,81,100"
},
{
"code": null,
"e": 2215,
"s": 2104,
"text": "Now, we would like to sort the array in Descending order than we have to change the compare function.Syntax: "
},
{
"code": null,
"e": 2244,
"s": 2215,
"text": "function(a, b){return b - a}"
},
{
"code": null,
"e": 2297,
"s": 2246,
"text": "Negative Value ( b < a) => a will be Place after b"
},
{
"code": null,
"e": 2330,
"s": 2297,
"text": "zero value (a == b) => No Change"
},
{
"code": null,
"e": 2382,
"s": 2330,
"text": "Positive Value (b > a ) => a will be place before b"
},
{
"code": null,
"e": 2476,
"s": 2382,
"text": "Example: This example uses compare function to sort the array elements in descending order. "
},
{
"code": null,
"e": 2487,
"s": 2476,
"text": "javascript"
},
{
"code": "<script> // Declare and initialize an Arrayvar marks = [12, 25, 31, 23, 75, 81, 100]; // Print Before sorting arraydocument.write(\"Original Array</br>\");document.write(marks); document.write(\"</br>\"); // Sort elements using compare methodmarks.sort(function(a, b){return b - a}); document.write(\"</br>After sorting in Ascending order</br>\"); // Print sorted Numeric arraydocument.write(marks); </script>",
"e": 2911,
"s": 2487,
"text": null
},
{
"code": null,
"e": 2921,
"s": 2911,
"text": "Output: "
},
{
"code": null,
"e": 3014,
"s": 2921,
"text": "Original Array\n12,25,31,23,75,81,100\n\nAfter sorting in Ascending order\n100,81,75,31,25,23,12"
},
{
"code": null,
"e": 3194,
"s": 3014,
"text": "Creating Loops: We can also use loops to sort the array elements. Here, we will use bubble sort (simple sorting technique) to sort the array elements in ascending order.Example: "
},
{
"code": null,
"e": 3205,
"s": 3194,
"text": "javascript"
},
{
"code": "<script> // Sorting functionfunction Numeric_sort(ar) { var i = 0, j; while (i < ar.length) { j = i + 1; while (j < ar.length) { if (ar[j] < ar[i]) { var temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } j++; } i++; }} // Original Arrayvar arr = [1, 15, 10, 45, 27, 100]; // Print Before sorting arraydocument.write(\"Original Array</br>\");document.write(arr); document.write(\"</br>\"); // Function callNumeric_sort(arr); document.write(\"</br>Sorted Array</br>\"); // Print sorted Numeric arraydocument.write(arr); </script>",
"e": 3884,
"s": 3205,
"text": null
},
{
"code": null,
"e": 3894,
"s": 3884,
"text": "Output: "
},
{
"code": null,
"e": 3959,
"s": 3894,
"text": "Original Array\n1,15,10,45,27,100\n\nSorted Array\n1,10,15,27,45,100"
},
{
"code": null,
"e": 3974,
"s": 3961,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3993,
"s": 3974,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4007,
"s": 3993,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4024,
"s": 4007,
"text": "javascript-array"
},
{
"code": null,
"e": 4040,
"s": 4024,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4051,
"s": 4040,
"text": "JavaScript"
},
{
"code": null,
"e": 4068,
"s": 4051,
"text": "Web Technologies"
},
{
"code": null,
"e": 4095,
"s": 4068,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4111,
"s": 4095,
"text": "Write From Home"
}
] |
Python – tensorflow.eye() | 10 Jul, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
tensorflow.eye() is used to generate identity matrix.
Syntax: tensorflow.eye( num_rows, num_columns, batch_shape, dtype, name)
Parameters:
num_rows: It is int32 scalar Tensor which defines the number of rows to be present in resulting matrix.
num_columns(optional): It is int32 scalar Tensor which defines the number of columns to be present in resulting matrix. It’s default value is num_rows.
batch_shape(optional): It is list or tuple of Python integers or a 1-D int32 Tensor. If it’s not none the returned Tensor will have leading batch dimensions of this shape.
dtype(optional): It defines the dtype of returned tensor. Default value is float32.
name(optional): It defines the name for the operation.
Return : It returns a Tensor of shape batch_shape + [num_rows, num_columns].
Example 1:
Python3
# Importing the libraryimport tensorflow as tf # Initializing the inputnum_rows = 5 # Printing the inputprint('num_rows:', num_rows) # Calculating resultres = tf.eye(num_rows) # Printing the resultprint('res: ', res)
Output:
num_rows: 5
res: tf.Tensor(
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]], shape=(5, 5), dtype=float32)
Example 2:
Python3
# Importing the libraryimport tensorflow as tf # Initializing the inputnum_rows = 5num_columns = 6batch_shape = [3] # Printing the inputprint('num_rows:', num_rows)print('num_columns:', num_columns)print('batch_shape:', batch_shape) # Calculating resultres = tf.eye(num_rows, num_columns, batch_shape) # Printing the resultprint('res: ', res)
Output:
num_rows: 5
num_columns: 6
batch_shape: [3]
res: tf.Tensor(
[[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]]
[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]]
[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]]], shape=(3, 5, 6), dtype=float32)
Python-Tensorflow
Tensorflow
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
Python | os.path.join() method
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 | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. "
},
{
"code": null,
"e": 214,
"s": 160,
"text": "tensorflow.eye() is used to generate identity matrix."
},
{
"code": null,
"e": 287,
"s": 214,
"text": "Syntax: tensorflow.eye( num_rows, num_columns, batch_shape, dtype, name)"
},
{
"code": null,
"e": 299,
"s": 287,
"text": "Parameters:"
},
{
"code": null,
"e": 403,
"s": 299,
"text": "num_rows: It is int32 scalar Tensor which defines the number of rows to be present in resulting matrix."
},
{
"code": null,
"e": 555,
"s": 403,
"text": "num_columns(optional): It is int32 scalar Tensor which defines the number of columns to be present in resulting matrix. It’s default value is num_rows."
},
{
"code": null,
"e": 729,
"s": 555,
"text": "batch_shape(optional): It is list or tuple of Python integers or a 1-D int32 Tensor. If it’s not none the returned Tensor will have leading batch dimensions of this shape. "
},
{
"code": null,
"e": 813,
"s": 729,
"text": "dtype(optional): It defines the dtype of returned tensor. Default value is float32."
},
{
"code": null,
"e": 868,
"s": 813,
"text": "name(optional): It defines the name for the operation."
},
{
"code": null,
"e": 945,
"s": 868,
"text": "Return : It returns a Tensor of shape batch_shape + [num_rows, num_columns]."
},
{
"code": null,
"e": 956,
"s": 945,
"text": "Example 1:"
},
{
"code": null,
"e": 964,
"s": 956,
"text": "Python3"
},
{
"code": "# Importing the libraryimport tensorflow as tf # Initializing the inputnum_rows = 5 # Printing the inputprint('num_rows:', num_rows) # Calculating resultres = tf.eye(num_rows) # Printing the resultprint('res: ', res)",
"e": 1185,
"s": 964,
"text": null
},
{
"code": null,
"e": 1193,
"s": 1185,
"text": "Output:"
},
{
"code": null,
"e": 1345,
"s": 1193,
"text": "\nnum_rows: 5\nres: tf.Tensor(\n[[1. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0.]\n [0. 0. 1. 0. 0.]\n [0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 1.]], shape=(5, 5), dtype=float32)\n"
},
{
"code": null,
"e": 1356,
"s": 1345,
"text": "Example 2:"
},
{
"code": null,
"e": 1364,
"s": 1356,
"text": "Python3"
},
{
"code": "# Importing the libraryimport tensorflow as tf # Initializing the inputnum_rows = 5num_columns = 6batch_shape = [3] # Printing the inputprint('num_rows:', num_rows)print('num_columns:', num_columns)print('batch_shape:', batch_shape) # Calculating resultres = tf.eye(num_rows, num_columns, batch_shape) # Printing the resultprint('res: ', res)",
"e": 1711,
"s": 1364,
"text": null
},
{
"code": null,
"e": 1719,
"s": 1711,
"text": "Output:"
},
{
"code": null,
"e": 2152,
"s": 1719,
"text": "\nnum_rows: 5\nnum_columns: 6\nbatch_shape: [3]\nres: tf.Tensor(\n[[[1. 0. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0. 0.]\n [0. 0. 1. 0. 0. 0.]\n [0. 0. 0. 1. 0. 0.]\n [0. 0. 0. 0. 1. 0.]]\n\n [[1. 0. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0. 0.]\n [0. 0. 1. 0. 0. 0.]\n [0. 0. 0. 1. 0. 0.]\n [0. 0. 0. 0. 1. 0.]]\n\n [[1. 0. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0. 0.]\n [0. 0. 1. 0. 0. 0.]\n [0. 0. 0. 1. 0. 0.]\n [0. 0. 0. 0. 1. 0.]]], shape=(3, 5, 6), dtype=float32)\n\n"
},
{
"code": null,
"e": 2170,
"s": 2152,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 2181,
"s": 2170,
"text": "Tensorflow"
},
{
"code": null,
"e": 2188,
"s": 2181,
"text": "Python"
},
{
"code": null,
"e": 2286,
"s": 2188,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2318,
"s": 2286,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2345,
"s": 2318,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2366,
"s": 2345,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2389,
"s": 2366,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2420,
"s": 2389,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2476,
"s": 2420,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2518,
"s": 2476,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2560,
"s": 2518,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2599,
"s": 2560,
"text": "Python | Get unique values from a list"
}
] |
numpy.ones_like() in Python | 22 Oct, 2020
The numpy.one_like() function returns an array of given shape and type as a given array, with ones.
Syntax: numpy.ones_like(array, dtype = None, order = 'K', subok = True)
Parameters :
array : array_like input
subok : [optional, boolean]If true, then newly created array will be sub-class of array;
otherwise, a base-class array
order : C_contiguous or F_contiguous
C-contiguous order in memory(last index varies the fastest)
C order means that operating row-wise on the array will be slightly quicker
FORTRAN-contiguous order in memory (first index varies the fastest).
F order means that column-wise operations will be faster.
dtype : [optional, float(byDefault)] Data type of returned array.
Returns :
ndarray of ones having given shape, order and datatype.
# Python Programming illustrating# numpy.ones_like method import numpy as geek array = geek.arange(10).reshape(5, 2)print("Original array : \n", array) b = geek.ones_like(array, float)print("\nMatrix b : \n", b) array = geek.arange(8)c = geek.ones_like(array)print("\nMatrix c : \n", c)
Output:
Original array :
[[0 1]
[2 3]
[4 5]
[6 7]
[8 9]]
Matrix b :
[[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]]
Matrix c :
[1 1 1 1 1 1 1 1]
References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.ones_like.htmlNote :Also, these codes won’t run on online-ID. Please run them on your systems to explore the working
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nidhi_biet
10frazier
Python numpy-arrayCreation
Python-numpy
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
Python OOPs Concepts | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Oct, 2020"
},
{
"code": null,
"e": 153,
"s": 53,
"text": "The numpy.one_like() function returns an array of given shape and type as a given array, with ones."
},
{
"code": null,
"e": 225,
"s": 153,
"text": "Syntax: numpy.ones_like(array, dtype = None, order = 'K', subok = True)"
},
{
"code": null,
"e": 238,
"s": 225,
"text": "Parameters :"
},
{
"code": null,
"e": 809,
"s": 238,
"text": "array : array_like input\nsubok : [optional, boolean]If true, then newly created array will be sub-class of array; \n otherwise, a base-class array\norder : C_contiguous or F_contiguous\n C-contiguous order in memory(last index varies the fastest)\n C order means that operating row-wise on the array will be slightly quicker\n FORTRAN-contiguous order in memory (first index varies the fastest).\n F order means that column-wise operations will be faster. \ndtype : [optional, float(byDefault)] Data type of returned array. \n"
},
{
"code": null,
"e": 819,
"s": 809,
"text": "Returns :"
},
{
"code": null,
"e": 875,
"s": 819,
"text": "ndarray of ones having given shape, order and datatype."
},
{
"code": "# Python Programming illustrating# numpy.ones_like method import numpy as geek array = geek.arange(10).reshape(5, 2)print(\"Original array : \\n\", array) b = geek.ones_like(array, float)print(\"\\nMatrix b : \\n\", b) array = geek.arange(8)c = geek.ones_like(array)print(\"\\nMatrix c : \\n\", c)",
"e": 1168,
"s": 875,
"text": null
},
{
"code": null,
"e": 1176,
"s": 1168,
"text": "Output:"
},
{
"code": null,
"e": 1334,
"s": 1176,
"text": "Original array : \n [[0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]]\n\nMatrix b : \n [[ 1. 1.]\n [ 1. 1.]\n [ 1. 1.]\n [ 1. 1.]\n [ 1. 1.]]\n\nMatrix c : \n [1 1 1 1 1 1 1 1]\n"
},
{
"code": null,
"e": 1526,
"s": 1334,
"text": "References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.ones_like.htmlNote :Also, these codes won’t run on online-ID. Please run them on your systems to explore the working"
},
{
"code": null,
"e": 1830,
"s": 1526,
"text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1955,
"s": 1830,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1966,
"s": 1955,
"text": "nidhi_biet"
},
{
"code": null,
"e": 1976,
"s": 1966,
"text": "10frazier"
},
{
"code": null,
"e": 2003,
"s": 1976,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 2016,
"s": 2003,
"text": "Python-numpy"
},
{
"code": null,
"e": 2023,
"s": 2016,
"text": "Python"
},
{
"code": null,
"e": 2121,
"s": 2023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2139,
"s": 2121,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2181,
"s": 2139,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2203,
"s": 2181,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2238,
"s": 2203,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2264,
"s": 2238,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2296,
"s": 2264,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2325,
"s": 2296,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2352,
"s": 2325,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2382,
"s": 2352,
"text": "Iterate over a list in Python"
}
] |
How to get character array from string in JavaScript? | 20 Jul, 2021
The string in JavaScript can be converted into a character array by using the split() and Array.from() functions.
Using String split() Function: The str.split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.Syntax:
str.split(separator, limit)
Example:
<!DOCTYPE html><html> <head> <title> String to a character array </title></head> <body style="text-align:center;"> <h1>GeeksforGeeks</h1> <p id = "one" >GeeksforGeeks: A computer science portal</p> <input type="button" value="Click Here!" onclick="myGeeks()"> <script> function myGeeks() { var str = document.getElementById("one").innerHTML; document.getElementById("one").innerHTML = str.split(""); } </script></body> </html>
Output:Before Clicking the button:After Clicking the button:
Using Array.from() Function: The Array.from() function is an inbuilt function in JavaScript which creates a new array instance from a given array. In case of a string, every alphabet of the string is converted to an element of the new array instance and in case of integer values, new array instance simple take the elements of the given array.Syntax:
Array.from(str)
Example:
<!DOCTYPE html><html> <head> <title> String to a character array </title></head> <body style="text-align:center;"> <h1>GeeksforGeeks</h1> <p id = "one" >GeeksforGeeks: A computer science portal</p> <input type="button" value="Click Here!" onclick="myGeeks()"> <script> function myGeeks() { var str = document.getElementById("one").innerHTML; document.getElementById("one").innerHTML = Array.from(str); } </script></body> </html>
Output:Before Clicking the button:After Clicking the button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
javascript-array
javascript-string
Picked
JavaScript
Web Technologies
Web technologies Questions
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
How to append HTML code to a div using JavaScript ?
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": 28,
"s": 0,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "The string in JavaScript can be converted into a character array by using the split() and Array.from() functions."
},
{
"code": null,
"e": 348,
"s": 142,
"text": "Using String split() Function: The str.split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.Syntax:"
},
{
"code": null,
"e": 376,
"s": 348,
"text": "str.split(separator, limit)"
},
{
"code": null,
"e": 385,
"s": 376,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> String to a character array </title></head> <body style=\"text-align:center;\"> <h1>GeeksforGeeks</h1> <p id = \"one\" >GeeksforGeeks: A computer science portal</p> <input type=\"button\" value=\"Click Here!\" onclick=\"myGeeks()\"> <script> function myGeeks() { var str = document.getElementById(\"one\").innerHTML; document.getElementById(\"one\").innerHTML = str.split(\"\"); } </script></body> </html> ",
"e": 923,
"s": 385,
"text": null
},
{
"code": null,
"e": 984,
"s": 923,
"text": "Output:Before Clicking the button:After Clicking the button:"
},
{
"code": null,
"e": 1336,
"s": 984,
"text": "Using Array.from() Function: The Array.from() function is an inbuilt function in JavaScript which creates a new array instance from a given array. In case of a string, every alphabet of the string is converted to an element of the new array instance and in case of integer values, new array instance simple take the elements of the given array.Syntax:"
},
{
"code": null,
"e": 1352,
"s": 1336,
"text": "Array.from(str)"
},
{
"code": null,
"e": 1361,
"s": 1352,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> String to a character array </title></head> <body style=\"text-align:center;\"> <h1>GeeksforGeeks</h1> <p id = \"one\" >GeeksforGeeks: A computer science portal</p> <input type=\"button\" value=\"Click Here!\" onclick=\"myGeeks()\"> <script> function myGeeks() { var str = document.getElementById(\"one\").innerHTML; document.getElementById(\"one\").innerHTML = Array.from(str); } </script></body> </html> ",
"e": 1901,
"s": 1361,
"text": null
},
{
"code": null,
"e": 1962,
"s": 1901,
"text": "Output:Before Clicking the button:After Clicking the button:"
},
{
"code": null,
"e": 2181,
"s": 1962,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 2198,
"s": 2181,
"text": "javascript-array"
},
{
"code": null,
"e": 2216,
"s": 2198,
"text": "javascript-string"
},
{
"code": null,
"e": 2223,
"s": 2216,
"text": "Picked"
},
{
"code": null,
"e": 2234,
"s": 2223,
"text": "JavaScript"
},
{
"code": null,
"e": 2251,
"s": 2234,
"text": "Web Technologies"
},
{
"code": null,
"e": 2278,
"s": 2251,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2376,
"s": 2278,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2437,
"s": 2376,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2509,
"s": 2437,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2549,
"s": 2509,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2590,
"s": 2549,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2642,
"s": 2590,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2675,
"s": 2642,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2737,
"s": 2675,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2798,
"s": 2737,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2848,
"s": 2798,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Panic in Golang | 17 Sep, 2019
In Go language, panic is just like an exception, it also arises at runtime. Or in other words, panic means an unexpected condition arises in your Go program due to which the execution of your program is terminated. Sometimes panic occurs at runtime when some specific situation arises like out-of-bounds array accesses, etc. as shown in Example 1 or sometimes it is deliberately thrown by the programmer to handle the worst-case scenario in the Go program with the help of panic() function as shown in Example 2.The panic function is an inbuilt function which is defined under the builtin package of the Go language. This function terminates the flow of control and starts panicking.
Syntax:
func panic(v interface{})
It can receive any type of argument. When the panic occurs in the Go program the program terminates at runtime and in the output screen an error message as well as the stack trace till the point where the panic occurred is shown. Generally, in Go language when the panic occurs in the program, the program does not terminate immediately, it terminates when the go completes all the pending work of that program.For Example, suppose a function A calls panic, then the execution of the function A is stopped and if any deferred functions are available in A, then they are executed normally after that the function A return to its caller and to the caller A behaves like a call to panic. This process continues until all the functions in the current goroutine are returned, after that the program crashes as shown in example 3.
Example 1:
// Simple Go program which illustrates// the concept of panicpackage main import "fmt" // Main functionfunc main() { // Creating an array of string type // Using var keyword var myarr [3]string // Elements are assigned // using an index myarr[0] = "GFG" myarr[1] = "GeeksforGeeks" myarr[2] = "Geek" // Accessing the elements // of the array // Using index value fmt.Println("Elements of Array:") fmt.Println("Element 1: ", myarr[0]) // Program panics because // the size of the array is // 3 and we try to access // index 5 which is not // available in the current array, // So, it gives an runtime error fmt.Println("Element 2: ", myarr[5]) }
Output:
./prog.go:32:34: invalid array index 5 (out of bounds for 3-element array)
Example 2:
// Go program which illustrates // how to create your own panic// Using panic functionpackage main import "fmt" // Functionfunc entry(lang *string, aname *string) { // When the value of lang // is nil it will panic if lang == nil { panic("Error: Language cannot be nil") } // When the value of aname // is nil it will panic if aname == nil { panic("Error: Author name cannot be nil") } // When the values of the lang and aname // are non-nil values it will print // normal output fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname)} // Main functionfunc main() { A_lang := "GO Language" // Here in entry function, we pass // a non-nil and nil values // Due to nil value this method panics entry(&A_lang, nil)}
Output:
panic: Error: Author name cannot be nil
goroutine 1 [running]:
main.entry(0x41a788, 0x0)
/tmp/sandbox108627012/prog.go:20 +0x140
main.main()
/tmp/sandbox108627012/prog.go:37 +0x40
Example 3:
// Go program which illustrates the// concept of Defer while panickingpackage main import ( "fmt") // Functionfunc entry(lang *string, aname *string) { // Defer statement defer fmt.Println("Defer statement in the entry function") // When the value of lang // is nil it will panic if lang == nil { panic("Error: Language cannot be nil") } // When the value of aname // is nil it will panic if aname == nil { panic("Error: Author name cannot be nil") } // When the values of the lang and aname // are non-nil values it will // print normal output fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname)} // Main functionfunc main() { A_lang := "GO Language" // Defer statement defer fmt.Println("Defer statement in the Main function") // Here in entry function, we pass // one non-nil and one-nil value // Due to nil value this method panics entry(&A_lang, nil)}
Output:
Defer statement in the entry function
Defer statement in the Main function
panic: Error: Author name cannot be nil
goroutine 1 [running]:
main.entry(0x41a780, 0x0)
/tmp/sandbox121565297/prog.go:24 +0x220
main.main()
/tmp/sandbox121565297/prog.go:44 +0xa0
Note: Defer statement or function always run even if the program panics.
Usage of Panic:
You can use panic for an unrecoverable error where the program is not able to continue its execution.
You can also use panic if you want an error for a specific condition in your program.
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 737,
"s": 53,
"text": "In Go language, panic is just like an exception, it also arises at runtime. Or in other words, panic means an unexpected condition arises in your Go program due to which the execution of your program is terminated. Sometimes panic occurs at runtime when some specific situation arises like out-of-bounds array accesses, etc. as shown in Example 1 or sometimes it is deliberately thrown by the programmer to handle the worst-case scenario in the Go program with the help of panic() function as shown in Example 2.The panic function is an inbuilt function which is defined under the builtin package of the Go language. This function terminates the flow of control and starts panicking."
},
{
"code": null,
"e": 745,
"s": 737,
"text": "Syntax:"
},
{
"code": null,
"e": 771,
"s": 745,
"text": "func panic(v interface{})"
},
{
"code": null,
"e": 1596,
"s": 771,
"text": "It can receive any type of argument. When the panic occurs in the Go program the program terminates at runtime and in the output screen an error message as well as the stack trace till the point where the panic occurred is shown. Generally, in Go language when the panic occurs in the program, the program does not terminate immediately, it terminates when the go completes all the pending work of that program.For Example, suppose a function A calls panic, then the execution of the function A is stopped and if any deferred functions are available in A, then they are executed normally after that the function A return to its caller and to the caller A behaves like a call to panic. This process continues until all the functions in the current goroutine are returned, after that the program crashes as shown in example 3."
},
{
"code": null,
"e": 1607,
"s": 1596,
"text": "Example 1:"
},
{
"code": "// Simple Go program which illustrates// the concept of panicpackage main import \"fmt\" // Main functionfunc main() { // Creating an array of string type // Using var keyword var myarr [3]string // Elements are assigned // using an index myarr[0] = \"GFG\" myarr[1] = \"GeeksforGeeks\" myarr[2] = \"Geek\" // Accessing the elements // of the array // Using index value fmt.Println(\"Elements of Array:\") fmt.Println(\"Element 1: \", myarr[0]) // Program panics because // the size of the array is // 3 and we try to access // index 5 which is not // available in the current array, // So, it gives an runtime error fmt.Println(\"Element 2: \", myarr[5]) }",
"e": 2323,
"s": 1607,
"text": null
},
{
"code": null,
"e": 2331,
"s": 2323,
"text": "Output:"
},
{
"code": null,
"e": 2406,
"s": 2331,
"text": "./prog.go:32:34: invalid array index 5 (out of bounds for 3-element array)"
},
{
"code": null,
"e": 2417,
"s": 2406,
"text": "Example 2:"
},
{
"code": "// Go program which illustrates // how to create your own panic// Using panic functionpackage main import \"fmt\" // Functionfunc entry(lang *string, aname *string) { // When the value of lang // is nil it will panic if lang == nil { panic(\"Error: Language cannot be nil\") } // When the value of aname // is nil it will panic if aname == nil { panic(\"Error: Author name cannot be nil\") } // When the values of the lang and aname // are non-nil values it will print // normal output fmt.Printf(\"Author Language: %s \\n Author Name: %s\\n\", *lang, *aname)} // Main functionfunc main() { A_lang := \"GO Language\" // Here in entry function, we pass // a non-nil and nil values // Due to nil value this method panics entry(&A_lang, nil)}",
"e": 3231,
"s": 2417,
"text": null
},
{
"code": null,
"e": 3239,
"s": 3231,
"text": "Output:"
},
{
"code": null,
"e": 3429,
"s": 3239,
"text": "panic: Error: Author name cannot be nil\n\ngoroutine 1 [running]:\nmain.entry(0x41a788, 0x0)\n /tmp/sandbox108627012/prog.go:20 +0x140\nmain.main()\n /tmp/sandbox108627012/prog.go:37 +0x40\n"
},
{
"code": null,
"e": 3440,
"s": 3429,
"text": "Example 3:"
},
{
"code": "// Go program which illustrates the// concept of Defer while panickingpackage main import ( \"fmt\") // Functionfunc entry(lang *string, aname *string) { // Defer statement defer fmt.Println(\"Defer statement in the entry function\") // When the value of lang // is nil it will panic if lang == nil { panic(\"Error: Language cannot be nil\") } // When the value of aname // is nil it will panic if aname == nil { panic(\"Error: Author name cannot be nil\") } // When the values of the lang and aname // are non-nil values it will // print normal output fmt.Printf(\"Author Language: %s \\n Author Name: %s\\n\", *lang, *aname)} // Main functionfunc main() { A_lang := \"GO Language\" // Defer statement defer fmt.Println(\"Defer statement in the Main function\") // Here in entry function, we pass // one non-nil and one-nil value // Due to nil value this method panics entry(&A_lang, nil)}",
"e": 4417,
"s": 3440,
"text": null
},
{
"code": null,
"e": 4425,
"s": 4417,
"text": "Output:"
},
{
"code": null,
"e": 4690,
"s": 4425,
"text": "Defer statement in the entry function\nDefer statement in the Main function\npanic: Error: Author name cannot be nil\n\ngoroutine 1 [running]:\nmain.entry(0x41a780, 0x0)\n /tmp/sandbox121565297/prog.go:24 +0x220\nmain.main()\n /tmp/sandbox121565297/prog.go:44 +0xa0\n"
},
{
"code": null,
"e": 4763,
"s": 4690,
"text": "Note: Defer statement or function always run even if the program panics."
},
{
"code": null,
"e": 4779,
"s": 4763,
"text": "Usage of Panic:"
},
{
"code": null,
"e": 4881,
"s": 4779,
"text": "You can use panic for an unrecoverable error where the program is not able to continue its execution."
},
{
"code": null,
"e": 4967,
"s": 4881,
"text": "You can also use panic if you want an error for a specific condition in your program."
},
{
"code": null,
"e": 4974,
"s": 4967,
"text": "Golang"
},
{
"code": null,
"e": 4986,
"s": 4974,
"text": "Go Language"
}
] |
Integer valueOf() Method in Java | 14 Dec, 2021
1. The java.lang.Integer.valueOf(int a) is an inbuilt method which is used to return an Integer instance representing the specified int value a.
Syntax :
public static Integer valueOf(int a)
Parameters : The method accepts a single parameter a of integer type representing the parameter whose Integer instance is to be returned.
Return Value : The method returns an Integer instance representing a.
Examples :
Input: a = 65
Output: 65
Input: a = -985
Output: -985
Below programs illustrate the java.lang.Integer.valueOf(int a) method.
Program 1: For a positive number.
Java
// Java program to illustrate the// java.lang.Integer.valueOf(int a)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(10); // Returns an Integer instance // representing the specified int value System.out.println("Output Value = " + obj.valueOf(85)); }}
Output Value = 85
Program 2: For a negative number.
Java
// Java program to illustrate the// java.lang.Integer.valueOf(int a)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(10); // It will return a Integer instance // representing the specified int value System.out.println("Output Value = " + obj.valueOf(-9185)); }}
Output Value = -9185
2. The java.lang.Integer.valueOf(String str) is an inbuilt method which is used to return an Integer object, holding the value of the specified String str.
Syntax:
public static Integer valueOf(String str)
Parameters: This method accepts a single parameter str of String type that is to be parsed.
Return Value: The method returns an Integer object holding the value represented by the string argument.
Examples:
Input: str = "65"
Output: 65
Input: str = "-452"
Output: 452
Below programs illustrate the java.lang.Integer.valueOf(String str) method:
Program 1: For a positive number.
java
// Java program to illustrate the// java.lang.Integer.valueOf(String str)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(8); String str = "424"; // It will return a Integer instance // representing the specified string System.out.println("Integer Value = " + obj.valueOf(str)); }}
Integer Value = 424
Program 2: For a negative number.
Java
// Java program to illustrate the// java.lang.Integer.valueOf(String str)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(8); String str = "-6156"; // It will return a Integer instance // representing the specified string System.out.println("Output Value = " + obj.valueOf(str)); }}
Output Value = -6156
3. The java.lang.Integer.valueOf(String s, int radix) is an inbuilt method which returns an Integer object, holding the value extracted from the specified String when parsed with the base given by the second argument.
Syntax :
public static Integer valueOf(String str, int base)
Parameter: The method accepts two parameters:
str: This is of String type which is to be parsed.
base This is of Integer type and refers to the base to be used to interpret str.
Return Value : The method returns an Integer object holding the value represented by the string argument in the specified base or radix.
Examples:
Input: str = "1101"
base = 2
Output: 13
Input: str = "101"
base = 4
Output: 17
Below program illustrates the java.lang.Integer.valueOf(String str, int base) method:
Java
// Java program to illustrate the// java.lang.Integer.valueOf(String str, int base)import java.lang.*; public class Geeks { public static void main(String[] args) { // Base = 2 Integer val1 = Integer.valueOf("1010", 8); System.out.println(val1); // Base = 16 Integer val2 = Integer.valueOf("1011", 16); System.out.println(val2); // Base = 2 Integer val3 = Integer.valueOf("1010", 2); System.out.println(val3); // Base = 10 Integer val4 = Integer.valueOf("1021", 10); System.out.println(val4); }}
520
4113
10
1021
anikaseth98
Java-Functions
Java-Integer
Java-lang package
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
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 198,
"s": 53,
"text": "1. The java.lang.Integer.valueOf(int a) is an inbuilt method which is used to return an Integer instance representing the specified int value a."
},
{
"code": null,
"e": 208,
"s": 198,
"text": "Syntax : "
},
{
"code": null,
"e": 245,
"s": 208,
"text": "public static Integer valueOf(int a)"
},
{
"code": null,
"e": 383,
"s": 245,
"text": "Parameters : The method accepts a single parameter a of integer type representing the parameter whose Integer instance is to be returned."
},
{
"code": null,
"e": 453,
"s": 383,
"text": "Return Value : The method returns an Integer instance representing a."
},
{
"code": null,
"e": 464,
"s": 453,
"text": "Examples :"
},
{
"code": null,
"e": 519,
"s": 464,
"text": "Input: a = 65\nOutput: 65\n\nInput: a = -985\nOutput: -985"
},
{
"code": null,
"e": 590,
"s": 519,
"text": "Below programs illustrate the java.lang.Integer.valueOf(int a) method."
},
{
"code": null,
"e": 624,
"s": 590,
"text": "Program 1: For a positive number."
},
{
"code": null,
"e": 629,
"s": 624,
"text": "Java"
},
{
"code": "// Java program to illustrate the// java.lang.Integer.valueOf(int a)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(10); // Returns an Integer instance // representing the specified int value System.out.println(\"Output Value = \" + obj.valueOf(85)); }}",
"e": 1019,
"s": 629,
"text": null
},
{
"code": null,
"e": 1037,
"s": 1019,
"text": "Output Value = 85"
},
{
"code": null,
"e": 1073,
"s": 1039,
"text": "Program 2: For a negative number."
},
{
"code": null,
"e": 1078,
"s": 1073,
"text": "Java"
},
{
"code": "// Java program to illustrate the// java.lang.Integer.valueOf(int a)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(10); // It will return a Integer instance // representing the specified int value System.out.println(\"Output Value = \" + obj.valueOf(-9185)); }}",
"e": 1476,
"s": 1078,
"text": null
},
{
"code": null,
"e": 1497,
"s": 1476,
"text": "Output Value = -9185"
},
{
"code": null,
"e": 1655,
"s": 1499,
"text": "2. The java.lang.Integer.valueOf(String str) is an inbuilt method which is used to return an Integer object, holding the value of the specified String str."
},
{
"code": null,
"e": 1663,
"s": 1655,
"text": "Syntax:"
},
{
"code": null,
"e": 1705,
"s": 1663,
"text": "public static Integer valueOf(String str)"
},
{
"code": null,
"e": 1797,
"s": 1705,
"text": "Parameters: This method accepts a single parameter str of String type that is to be parsed."
},
{
"code": null,
"e": 1902,
"s": 1797,
"text": "Return Value: The method returns an Integer object holding the value represented by the string argument."
},
{
"code": null,
"e": 1912,
"s": 1902,
"text": "Examples:"
},
{
"code": null,
"e": 1974,
"s": 1912,
"text": "Input: str = \"65\"\nOutput: 65\n\nInput: str = \"-452\"\nOutput: 452"
},
{
"code": null,
"e": 2050,
"s": 1974,
"text": "Below programs illustrate the java.lang.Integer.valueOf(String str) method:"
},
{
"code": null,
"e": 2084,
"s": 2050,
"text": "Program 1: For a positive number."
},
{
"code": null,
"e": 2089,
"s": 2084,
"text": "java"
},
{
"code": "// Java program to illustrate the// java.lang.Integer.valueOf(String str)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(8); String str = \"424\"; // It will return a Integer instance // representing the specified string System.out.println(\"Integer Value = \" + obj.valueOf(str)); }}",
"e": 2515,
"s": 2089,
"text": null
},
{
"code": null,
"e": 2535,
"s": 2515,
"text": "Integer Value = 424"
},
{
"code": null,
"e": 2571,
"s": 2537,
"text": "Program 2: For a negative number."
},
{
"code": null,
"e": 2576,
"s": 2571,
"text": "Java"
},
{
"code": "// Java program to illustrate the// java.lang.Integer.valueOf(String str)import java.lang.*; public class Geeks { public static void main(String[] args) { Integer obj = new Integer(8); String str = \"-6156\"; // It will return a Integer instance // representing the specified string System.out.println(\"Output Value = \" + obj.valueOf(str)); }}",
"e": 3002,
"s": 2576,
"text": null
},
{
"code": null,
"e": 3023,
"s": 3002,
"text": "Output Value = -6156"
},
{
"code": null,
"e": 3243,
"s": 3025,
"text": "3. The java.lang.Integer.valueOf(String s, int radix) is an inbuilt method which returns an Integer object, holding the value extracted from the specified String when parsed with the base given by the second argument."
},
{
"code": null,
"e": 3253,
"s": 3243,
"text": "Syntax : "
},
{
"code": null,
"e": 3305,
"s": 3253,
"text": "public static Integer valueOf(String str, int base)"
},
{
"code": null,
"e": 3351,
"s": 3305,
"text": "Parameter: The method accepts two parameters:"
},
{
"code": null,
"e": 3402,
"s": 3351,
"text": "str: This is of String type which is to be parsed."
},
{
"code": null,
"e": 3483,
"s": 3402,
"text": "base This is of Integer type and refers to the base to be used to interpret str."
},
{
"code": null,
"e": 3620,
"s": 3483,
"text": "Return Value : The method returns an Integer object holding the value represented by the string argument in the specified base or radix."
},
{
"code": null,
"e": 3631,
"s": 3620,
"text": "Examples: "
},
{
"code": null,
"e": 3725,
"s": 3631,
"text": "Input: str = \"1101\"\n base = 2\nOutput: 13\n\nInput: str = \"101\"\n base = 4\nOutput: 17"
},
{
"code": null,
"e": 3811,
"s": 3725,
"text": "Below program illustrates the java.lang.Integer.valueOf(String str, int base) method:"
},
{
"code": null,
"e": 3816,
"s": 3811,
"text": "Java"
},
{
"code": "// Java program to illustrate the// java.lang.Integer.valueOf(String str, int base)import java.lang.*; public class Geeks { public static void main(String[] args) { // Base = 2 Integer val1 = Integer.valueOf(\"1010\", 8); System.out.println(val1); // Base = 16 Integer val2 = Integer.valueOf(\"1011\", 16); System.out.println(val2); // Base = 2 Integer val3 = Integer.valueOf(\"1010\", 2); System.out.println(val3); // Base = 10 Integer val4 = Integer.valueOf(\"1021\", 10); System.out.println(val4); }}",
"e": 4419,
"s": 3816,
"text": null
},
{
"code": null,
"e": 4436,
"s": 4419,
"text": "520\n4113\n10\n1021"
},
{
"code": null,
"e": 4450,
"s": 4438,
"text": "anikaseth98"
},
{
"code": null,
"e": 4465,
"s": 4450,
"text": "Java-Functions"
},
{
"code": null,
"e": 4478,
"s": 4465,
"text": "Java-Integer"
},
{
"code": null,
"e": 4496,
"s": 4478,
"text": "Java-lang package"
},
{
"code": null,
"e": 4501,
"s": 4496,
"text": "Java"
},
{
"code": null,
"e": 4506,
"s": 4501,
"text": "Java"
},
{
"code": null,
"e": 4604,
"s": 4506,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4655,
"s": 4604,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 4686,
"s": 4655,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4705,
"s": 4686,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4735,
"s": 4705,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4753,
"s": 4735,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4773,
"s": 4753,
"text": "Collections in Java"
},
{
"code": null,
"e": 4788,
"s": 4773,
"text": "Stream In Java"
},
{
"code": null,
"e": 4820,
"s": 4788,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 4844,
"s": 4820,
"text": "Singleton Class in Java"
}
] |
QBasic | 11 Jul, 2022
The name QBasic is an acronym for Quick Beginners All Purpose Symbolic Instruction Code. It was developed and launched by Microsoft in the year 1991 and is considered to be one of the most ideal languages for absolute beginners. It was intended as a replacement for GW-BASIC. QBasic was based on earlier QuickBASIC 4.5 compiler. It does not produce .exe files but instead generates files with extension .bas which can only be executed immediately by the built in QBasic interpreter. It is based on DOS operating systems but is also executable on windows.
Beginning with QBasic:QBasic is available as an open source software.
QBasic consists of two windows:
Program Window: The window titled as ‘Untitled’ is the program window. It is the place where program/code is written
Immediate Window: The window below Program Window titled as ‘Immediate’ is the immediate window. This window is used as a debugging tool and is used when the user wants to check the output of a single statement.
Some Basic useful commands on QBasic:1. PRINT: This command prints the statement or data written after it. If the data to be printed is a string then it is written inside double quotes (” “) and if it is a number or a variable it can be written directly.
Example:
PRINT "HELLO GEEKS"
PRINT age
2. INPUT: INPUT command is used to take inputs/data from the user. It can be used to input both strings and numbers.If the data to be taken is a numerical value then the variable name in which it is to be stored is written directly after the INPUT command.
Syntax:
INPUT "[message to user]"; [variable_name]
Example:
INPUT age
If the data to be taken is string then the variable name in which it is to be stored is written followed by $ after the INPUT command.
INPUT name$
3. CLS: CLS stands for Clear Screen and is used to clear the screen if some previous results/outputs are present on the screen.
Below is a simple program to illustrate above commands:
Output:
Explanation:When using INPUT commands, users are presented with the message associated with it and are asked to input values to variables.PRINT statement prints the statements associated with it.
Applications of Qbasic:
QBasic is the most suitable language for the beginners to start with. It introduces people to programming without any need to worry about the internal working of the computer.
QBasic is very easy and simple to apply and create business applications, for creating games and even simple databases. It offers commands like SET, CIRCLE, LINE, etc which allow the programmer to draw using Qbasic. Hence, graphics can also be created using QBasic.
QBasic also supports creating sounds of some desired frequency through the speakers of your PC. Though only one sound can be played at once.
Advantages of QBasic:
The key feature of the language is its close resemblance to English.
Syntax of your code is checked automatically.
Qbasic has a dynamic program debugging feature.
Lengthy programs can be broken into smaller modules
Disadvantages of QBasic:
The language is not structured.
Qbasic is DOS based and has now become obsolete and is limited only in the field of education and programming.
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 609,
"s": 54,
"text": "The name QBasic is an acronym for Quick Beginners All Purpose Symbolic Instruction Code. It was developed and launched by Microsoft in the year 1991 and is considered to be one of the most ideal languages for absolute beginners. It was intended as a replacement for GW-BASIC. QBasic was based on earlier QuickBASIC 4.5 compiler. It does not produce .exe files but instead generates files with extension .bas which can only be executed immediately by the built in QBasic interpreter. It is based on DOS operating systems but is also executable on windows."
},
{
"code": null,
"e": 679,
"s": 609,
"text": "Beginning with QBasic:QBasic is available as an open source software."
},
{
"code": null,
"e": 711,
"s": 679,
"text": "QBasic consists of two windows:"
},
{
"code": null,
"e": 828,
"s": 711,
"text": "Program Window: The window titled as ‘Untitled’ is the program window. It is the place where program/code is written"
},
{
"code": null,
"e": 1040,
"s": 828,
"text": "Immediate Window: The window below Program Window titled as ‘Immediate’ is the immediate window. This window is used as a debugging tool and is used when the user wants to check the output of a single statement."
},
{
"code": null,
"e": 1295,
"s": 1040,
"text": "Some Basic useful commands on QBasic:1. PRINT: This command prints the statement or data written after it. If the data to be printed is a string then it is written inside double quotes (” “) and if it is a number or a variable it can be written directly."
},
{
"code": null,
"e": 1304,
"s": 1295,
"text": "Example:"
},
{
"code": null,
"e": 1324,
"s": 1304,
"text": "PRINT \"HELLO GEEKS\""
},
{
"code": null,
"e": 1334,
"s": 1324,
"text": "PRINT age"
},
{
"code": null,
"e": 1591,
"s": 1334,
"text": "2. INPUT: INPUT command is used to take inputs/data from the user. It can be used to input both strings and numbers.If the data to be taken is a numerical value then the variable name in which it is to be stored is written directly after the INPUT command."
},
{
"code": null,
"e": 1599,
"s": 1591,
"text": "Syntax:"
},
{
"code": null,
"e": 1643,
"s": 1599,
"text": "INPUT \"[message to user]\"; [variable_name] "
},
{
"code": null,
"e": 1652,
"s": 1643,
"text": "Example:"
},
{
"code": null,
"e": 1662,
"s": 1652,
"text": "INPUT age"
},
{
"code": null,
"e": 1797,
"s": 1662,
"text": "If the data to be taken is string then the variable name in which it is to be stored is written followed by $ after the INPUT command."
},
{
"code": null,
"e": 1809,
"s": 1797,
"text": "INPUT name$"
},
{
"code": null,
"e": 1937,
"s": 1809,
"text": "3. CLS: CLS stands for Clear Screen and is used to clear the screen if some previous results/outputs are present on the screen."
},
{
"code": null,
"e": 1993,
"s": 1937,
"text": "Below is a simple program to illustrate above commands:"
},
{
"code": null,
"e": 2001,
"s": 1993,
"text": "Output:"
},
{
"code": null,
"e": 2197,
"s": 2001,
"text": "Explanation:When using INPUT commands, users are presented with the message associated with it and are asked to input values to variables.PRINT statement prints the statements associated with it."
},
{
"code": null,
"e": 2221,
"s": 2197,
"text": "Applications of Qbasic:"
},
{
"code": null,
"e": 2397,
"s": 2221,
"text": "QBasic is the most suitable language for the beginners to start with. It introduces people to programming without any need to worry about the internal working of the computer."
},
{
"code": null,
"e": 2663,
"s": 2397,
"text": "QBasic is very easy and simple to apply and create business applications, for creating games and even simple databases. It offers commands like SET, CIRCLE, LINE, etc which allow the programmer to draw using Qbasic. Hence, graphics can also be created using QBasic."
},
{
"code": null,
"e": 2804,
"s": 2663,
"text": "QBasic also supports creating sounds of some desired frequency through the speakers of your PC. Though only one sound can be played at once."
},
{
"code": null,
"e": 2826,
"s": 2804,
"text": "Advantages of QBasic:"
},
{
"code": null,
"e": 2895,
"s": 2826,
"text": "The key feature of the language is its close resemblance to English."
},
{
"code": null,
"e": 2941,
"s": 2895,
"text": "Syntax of your code is checked automatically."
},
{
"code": null,
"e": 2989,
"s": 2941,
"text": "Qbasic has a dynamic program debugging feature."
},
{
"code": null,
"e": 3041,
"s": 2989,
"text": "Lengthy programs can be broken into smaller modules"
},
{
"code": null,
"e": 3066,
"s": 3041,
"text": "Disadvantages of QBasic:"
},
{
"code": null,
"e": 3098,
"s": 3066,
"text": "The language is not structured."
},
{
"code": null,
"e": 3209,
"s": 3098,
"text": "Qbasic is DOS based and has now become obsolete and is limited only in the field of education and programming."
},
{
"code": null,
"e": 3214,
"s": 3209,
"text": "Misc"
},
{
"code": null,
"e": 3219,
"s": 3214,
"text": "Misc"
},
{
"code": null,
"e": 3224,
"s": 3219,
"text": "Misc"
}
] |
How to Reset an Input Value when Limit Exceeds using AngularJS ? | 02 Mar, 2020
The task is to handle an input field if the number entered by the user in the input exceeds some limit using angularJS. We define a limitTo directive and use it on an HTML input element. This directive is used for all the handling of overflowing limits. The directive calls a function on the keypress event where we can check for the limits.
Example 1: This example sets the value of user input to 0 if its limit exceeds to 100.
<!DOCTYPE html><html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"> </script></head> <body ng-controller="MyController"> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <b> Edit an input value when it exceeds the limit </b> <br><br> <!-- Custom directive limit-to --> <input limit-to="100" type="number" ng-model="val"> {{val}} </center> <script type="text/javascript"> angular.module('myApp', []) .controller('MyController', ['$scope', function($scope) { // Value to ng model the input $scope.val; }]) .directive("limitTo", ['$timeout', function($timeout) { // Declaration of custom directive return { restrict: "A", link: function(scope, elem, attrs) { var limit = parseInt(attrs.limitTo); elem.on("keypress", function(e) { $timeout(function() { if (parseInt(e.target.value) > limit) { // Handle change here scope.val = 0; scope.$apply(); e.preventDefault(); } }); }); } } }]); </script></body> </html>
Output: As soon as the user exceeds 100, the value is set back to 0.
Example 2: Here we change the text based on input limit. If the value of input is less than 0 then it goes to 0. If it’s value is greater than 100 then it goes to 100 otherwise it stays as it is.
<!DOCTYPE html><html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"> </script></head> <body ng-controller="MyController"> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <b> Edit an input value when it exceeds the limit </b> <br><br> <!-- Custom directive limit-to --> <input limit-to="100" type="number" ng-model="val"> <br> {{text}} </center> <script type="text/javascript"> angular.module('myApp', []) .controller('MyController', ['$scope', function($scope) { // Value to ng model the input $scope.val; $scope.text = 'Inside Limit'; }]) .directive("limitTo", ['$timeout', function($timeout) { // Declaration of custom directive return { restrict: "A", link: function(scope, elem, attrs) { var limit = parseInt(attrs.limitTo); elem.on("keypress", function(e) { $timeout(function() { if (parseInt(e.target.value) > limit) { // Handle change here if greater scope.text = "Outside limit (greater)"; scope.val = 100; scope.$apply(); e.preventDefault(); } else if (parseInt(e.target.value) < 0) { scope.text = "Outside limit (smaller)"; scope.val = 0 scope.$apply(); e.preventDefault(); } else { scope.text = "Inside Limit"; scope.$apply(); e.preventDefault(); } }); }); } } }]); </script></body> </html>
AngularJS-Misc
Picked
AngularJS
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Mar, 2020"
},
{
"code": null,
"e": 370,
"s": 28,
"text": "The task is to handle an input field if the number entered by the user in the input exceeds some limit using angularJS. We define a limitTo directive and use it on an HTML input element. This directive is used for all the handling of overflowing limits. The directive calls a function on the keypress event where we can check for the limits."
},
{
"code": null,
"e": 457,
"s": 370,
"text": "Example 1: This example sets the value of user input to 0 if its limit exceeds to 100."
},
{
"code": "<!DOCTYPE html><html ng-app=\"myApp\"> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js\"> </script></head> <body ng-controller=\"MyController\"> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> Edit an input value when it exceeds the limit </b> <br><br> <!-- Custom directive limit-to --> <input limit-to=\"100\" type=\"number\" ng-model=\"val\"> {{val}} </center> <script type=\"text/javascript\"> angular.module('myApp', []) .controller('MyController', ['$scope', function($scope) { // Value to ng model the input $scope.val; }]) .directive(\"limitTo\", ['$timeout', function($timeout) { // Declaration of custom directive return { restrict: \"A\", link: function(scope, elem, attrs) { var limit = parseInt(attrs.limitTo); elem.on(\"keypress\", function(e) { $timeout(function() { if (parseInt(e.target.value) > limit) { // Handle change here scope.val = 0; scope.$apply(); e.preventDefault(); } }); }); } } }]); </script></body> </html>",
"e": 2168,
"s": 457,
"text": null
},
{
"code": null,
"e": 2237,
"s": 2168,
"text": "Output: As soon as the user exceeds 100, the value is set back to 0."
},
{
"code": null,
"e": 2433,
"s": 2237,
"text": "Example 2: Here we change the text based on input limit. If the value of input is less than 0 then it goes to 0. If it’s value is greater than 100 then it goes to 100 otherwise it stays as it is."
},
{
"code": "<!DOCTYPE html><html ng-app=\"myApp\"> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js\"> </script></head> <body ng-controller=\"MyController\"> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> Edit an input value when it exceeds the limit </b> <br><br> <!-- Custom directive limit-to --> <input limit-to=\"100\" type=\"number\" ng-model=\"val\"> <br> {{text}} </center> <script type=\"text/javascript\"> angular.module('myApp', []) .controller('MyController', ['$scope', function($scope) { // Value to ng model the input $scope.val; $scope.text = 'Inside Limit'; }]) .directive(\"limitTo\", ['$timeout', function($timeout) { // Declaration of custom directive return { restrict: \"A\", link: function(scope, elem, attrs) { var limit = parseInt(attrs.limitTo); elem.on(\"keypress\", function(e) { $timeout(function() { if (parseInt(e.target.value) > limit) { // Handle change here if greater scope.text = \"Outside limit (greater)\"; scope.val = 100; scope.$apply(); e.preventDefault(); } else if (parseInt(e.target.value) < 0) { scope.text = \"Outside limit (smaller)\"; scope.val = 0 scope.$apply(); e.preventDefault(); } else { scope.text = \"Inside Limit\"; scope.$apply(); e.preventDefault(); } }); }); } } }]); </script></body> </html>",
"e": 4742,
"s": 2433,
"text": null
},
{
"code": null,
"e": 4757,
"s": 4742,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 4764,
"s": 4757,
"text": "Picked"
},
{
"code": null,
"e": 4774,
"s": 4764,
"text": "AngularJS"
},
{
"code": null,
"e": 4778,
"s": 4774,
"text": "CSS"
},
{
"code": null,
"e": 4783,
"s": 4778,
"text": "HTML"
},
{
"code": null,
"e": 4800,
"s": 4783,
"text": "Web Technologies"
},
{
"code": null,
"e": 4827,
"s": 4800,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4832,
"s": 4827,
"text": "HTML"
},
{
"code": null,
"e": 4930,
"s": 4832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4954,
"s": 4930,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 4989,
"s": 4954,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 5013,
"s": 4989,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 5066,
"s": 5013,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 5115,
"s": 5066,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 5163,
"s": 5115,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 5225,
"s": 5163,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5275,
"s": 5225,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5333,
"s": 5275,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
delattr() and del() in Python | 16 Apr, 2021
delattr
The delattr() method is used to delete the named attribute from the object, with the prior permission of the object. Syntax:
delattr(object, name)
The function takes only two parameter:
object : from which
the name attribute is to be removed.
name : of the attribute
which is to be removed.
The function doesn't returns any value,
it just removes the attribute,
only if the object allows it.
The Working : Suppose we have a class by name Geek and it has five students as the attribute. So, using the delattr() method, we can remove any one of the attributes.
Python3
# Python code to illustrate delattr()class Geek: stu1 = "Henry" stu2 = "Zack" stu3 = "Stephen" stu4 = "Amy" stu5 = "Shawn" names = Geek() print('Students before delattr()--')print('First = ',names.stu1)print('Second = ',names.stu2)print('Third = ',names.stu3)print('Fourth = ',names.stu4)print('Fifth = ',names.stu5) # implementing the methoddelattr(Geek, 'stu5') print('After deleting fifth student--')print('First = ',names.stu1)print('Second = ',names.stu2)print('Third = ',names.stu3)print('Fourth = ',names.stu4)# this statement raises an errorprint('Fifth = ',names.stu5)
Output:
Students before delattr()--
First = Henry
Second = Zack
Third = Stephen
Fourth = Amy
Fifth = Shawn
After deleting fifth student--
First = Henry
Second = Zack
Third = Stephen
Fourth = Amy
When the execution moves to the last line of the program, i.e., when the fifth attribute is called, the compiler raises an error:
Traceback (most recent call last):
File "/home/028e8526d603bccb30e9aeb7ece9e1eb.py", line 25, in
print('Fifth = ',names.stu5)
AttributeError: 'Geek' object has no attribute 'stu5'
del operator
There is another operator in Python that does the similar work as the delattr() method. It is the del operator. Let’s see how it works.
Python3
# Python code to illustrate del()class Geek: stu1 = "Henry" stu2 = "Zack" stu3 = "Stephen" stu4 = "Amy" stu5 = "Shawn" names = Geek() print('Students before del--')print('First = ',names.stu1)print('Second = ',names.stu2)print('Third = ',names.stu3)print('Fourth = ',names.stu4)print('Fifth = ',names.stu5) # implementing the operatordel Geek.stu5 print('After deleting fifth student--')print('First = ',names.stu1)print('Second = ',names.stu2)print('Third = ',names.stu3)print('Fourth = ',names.stu4)# this statement raises an errorprint('Fifth = ',names.stu5)
Output:
Students before del--
First = Henry
Second = Zack
Third = Stephen
Fourth = Amy
Fifth = Shawn
After deleting fifth student--
First = Henry
Second = Zack
Third = Stephen
Fourth = Amy
The result is the same with an error:
Traceback (most recent call last):
File "/home/7c239eef9b897e964108c701f1f94c8a.py", line 26, in
print('Fifth = ',names.stu5)
AttributeError: 'Geek' object has no attribute 'stu5'
del vs delattr()
Dynamic deletion : del is more explicit and efficient and delattr() allows dynamic attribute deleting.Speed : If the above programs are considered and run then there is a slight difference between the speed of execution. del is slightly faster in comparison to delattr(), depending on the machine.byte-code Instructions : del also takes less byte-code instructions in comparison to delattr().
Dynamic deletion : del is more explicit and efficient and delattr() allows dynamic attribute deleting.
Speed : If the above programs are considered and run then there is a slight difference between the speed of execution. del is slightly faster in comparison to delattr(), depending on the machine.
byte-code Instructions : del also takes less byte-code instructions in comparison to delattr().
So we conclude the comparison by saying that del is slightly faster than delattr, but when it comes to dynamic deletion of attribute then delattr() has advantage as it is not possible by del operator.
simranarora5sos
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 61,
"s": 53,
"text": "delattr"
},
{
"code": null,
"e": 188,
"s": 61,
"text": "The delattr() method is used to delete the named attribute from the object, with the prior permission of the object. Syntax: "
},
{
"code": null,
"e": 464,
"s": 188,
"text": "delattr(object, name)\n\nThe function takes only two parameter:\n\nobject : from which \nthe name attribute is to be removed.\nname : of the attribute \nwhich is to be removed.\n\nThe function doesn't returns any value, \nit just removes the attribute, \nonly if the object allows it."
},
{
"code": null,
"e": 633,
"s": 464,
"text": "The Working : Suppose we have a class by name Geek and it has five students as the attribute. So, using the delattr() method, we can remove any one of the attributes. "
},
{
"code": null,
"e": 641,
"s": 633,
"text": "Python3"
},
{
"code": "# Python code to illustrate delattr()class Geek: stu1 = \"Henry\" stu2 = \"Zack\" stu3 = \"Stephen\" stu4 = \"Amy\" stu5 = \"Shawn\" names = Geek() print('Students before delattr()--')print('First = ',names.stu1)print('Second = ',names.stu2)print('Third = ',names.stu3)print('Fourth = ',names.stu4)print('Fifth = ',names.stu5) # implementing the methoddelattr(Geek, 'stu5') print('After deleting fifth student--')print('First = ',names.stu1)print('Second = ',names.stu2)print('Third = ',names.stu3)print('Fourth = ',names.stu4)# this statement raises an errorprint('Fifth = ',names.stu5)",
"e": 1224,
"s": 641,
"text": null
},
{
"code": null,
"e": 1234,
"s": 1224,
"text": "Output: "
},
{
"code": null,
"e": 1430,
"s": 1234,
"text": "Students before delattr()--\nFirst = Henry\nSecond = Zack\nThird = Stephen\nFourth = Amy\nFifth = Shawn\nAfter deleting fifth student--\nFirst = Henry\nSecond = Zack\nThird = Stephen\nFourth = Amy"
},
{
"code": null,
"e": 1562,
"s": 1430,
"text": "When the execution moves to the last line of the program, i.e., when the fifth attribute is called, the compiler raises an error: "
},
{
"code": null,
"e": 1749,
"s": 1562,
"text": "Traceback (most recent call last):\n File \"/home/028e8526d603bccb30e9aeb7ece9e1eb.py\", line 25, in \n print('Fifth = ',names.stu5)\nAttributeError: 'Geek' object has no attribute 'stu5'"
},
{
"code": null,
"e": 1764,
"s": 1751,
"text": "del operator"
},
{
"code": null,
"e": 1902,
"s": 1764,
"text": "There is another operator in Python that does the similar work as the delattr() method. It is the del operator. Let’s see how it works. "
},
{
"code": null,
"e": 1910,
"s": 1902,
"text": "Python3"
},
{
"code": "# Python code to illustrate del()class Geek: stu1 = \"Henry\" stu2 = \"Zack\" stu3 = \"Stephen\" stu4 = \"Amy\" stu5 = \"Shawn\" names = Geek() print('Students before del--')print('First = ',names.stu1)print('Second = ',names.stu2)print('Third = ',names.stu3)print('Fourth = ',names.stu4)print('Fifth = ',names.stu5) # implementing the operatordel Geek.stu5 print('After deleting fifth student--')print('First = ',names.stu1)print('Second = ',names.stu2)print('Third = ',names.stu3)print('Fourth = ',names.stu4)# this statement raises an errorprint('Fifth = ',names.stu5)",
"e": 2477,
"s": 1910,
"text": null
},
{
"code": null,
"e": 2487,
"s": 2477,
"text": "Output: "
},
{
"code": null,
"e": 2677,
"s": 2487,
"text": "Students before del--\nFirst = Henry\nSecond = Zack\nThird = Stephen\nFourth = Amy\nFifth = Shawn\nAfter deleting fifth student--\nFirst = Henry\nSecond = Zack\nThird = Stephen\nFourth = Amy"
},
{
"code": null,
"e": 2717,
"s": 2677,
"text": "The result is the same with an error: "
},
{
"code": null,
"e": 2904,
"s": 2717,
"text": "Traceback (most recent call last):\n File \"/home/7c239eef9b897e964108c701f1f94c8a.py\", line 26, in \n print('Fifth = ',names.stu5)\nAttributeError: 'Geek' object has no attribute 'stu5'"
},
{
"code": null,
"e": 2923,
"s": 2906,
"text": "del vs delattr()"
},
{
"code": null,
"e": 3318,
"s": 2925,
"text": "Dynamic deletion : del is more explicit and efficient and delattr() allows dynamic attribute deleting.Speed : If the above programs are considered and run then there is a slight difference between the speed of execution. del is slightly faster in comparison to delattr(), depending on the machine.byte-code Instructions : del also takes less byte-code instructions in comparison to delattr()."
},
{
"code": null,
"e": 3421,
"s": 3318,
"text": "Dynamic deletion : del is more explicit and efficient and delattr() allows dynamic attribute deleting."
},
{
"code": null,
"e": 3617,
"s": 3421,
"text": "Speed : If the above programs are considered and run then there is a slight difference between the speed of execution. del is slightly faster in comparison to delattr(), depending on the machine."
},
{
"code": null,
"e": 3713,
"s": 3617,
"text": "byte-code Instructions : del also takes less byte-code instructions in comparison to delattr()."
},
{
"code": null,
"e": 3915,
"s": 3713,
"text": "So we conclude the comparison by saying that del is slightly faster than delattr, but when it comes to dynamic deletion of attribute then delattr() has advantage as it is not possible by del operator. "
},
{
"code": null,
"e": 3931,
"s": 3915,
"text": "simranarora5sos"
},
{
"code": null,
"e": 3957,
"s": 3931,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 3964,
"s": 3957,
"text": "Python"
},
{
"code": null,
"e": 4062,
"s": 3964,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4080,
"s": 4062,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4122,
"s": 4080,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4144,
"s": 4122,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4179,
"s": 4144,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4205,
"s": 4179,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4237,
"s": 4205,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4266,
"s": 4237,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4296,
"s": 4266,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4323,
"s": 4296,
"text": "Python Classes and Objects"
}
] |
p5.js Keyboard | keyIsPressed | 15 Apr, 2019
The keyIsPressed variable in p5.js is true if any key is pressed and false if no keys are pressed.
Syntax:
keyIsPressed
Below program illustrates the keyIsPressed variable in p5.js:Example-1:
let valueX;let valueY; function setup() { // Create Canvas of size 500*500 createCanvas(1000, 500);} function draw() { // set background color background(200); fill('green'); // set text and text size textSize(25); text('Press Key to change the figure '+ 'from Circle To Keyboard', 30, 30); // use of keyIsPressed Variable if (keyIsPressed) { // draw ellipse ellipse(mouseX, mouseY, 115, 115); fill('red'); text("Key Is Pressed", 100, 300); } else { rect(mouseX / 2, mouseY / 2, 300, 200); } }
Output:Before:After:
Example-2:
let valueX;let valueY; function setup() { // Create Canvas of size 500*500 createCanvas(500, 500);} function draw() { // set background color background(200); fill('green'); // set text and text size textSize(25); text('Click to flip the the figure', 30, 30); // use of KeyIsPressed if (keyIsPressed) { fill(valueX, 255 - valueY, 255 - valueX); // draw rectangle rect(mouseX, mouseY, 115, 115); fill(valueY, 255 - valueX, 255 - valueX); rect(mouseX, mouseY + 115, 115, 115); fill(255 - valueY, 255 - valueX, 255 - valueY); } else { rect(mouseX - 115, mouseY, 115, 115); fill(255 - valueY, 255 - valueY, 255 - valueY); rect(mouseX - 115, mouseY + 115, 115, 115); }}
Output:Before:After:Reference: https://p5js.org/reference/#/p5/keyIsPressed
JavaScript-p5.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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
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": "\n15 Apr, 2019"
},
{
"code": null,
"e": 127,
"s": 28,
"text": "The keyIsPressed variable in p5.js is true if any key is pressed and false if no keys are pressed."
},
{
"code": null,
"e": 135,
"s": 127,
"text": "Syntax:"
},
{
"code": null,
"e": 149,
"s": 135,
"text": "keyIsPressed\n"
},
{
"code": null,
"e": 221,
"s": 149,
"text": "Below program illustrates the keyIsPressed variable in p5.js:Example-1:"
},
{
"code": "let valueX;let valueY; function setup() { // Create Canvas of size 500*500 createCanvas(1000, 500);} function draw() { // set background color background(200); fill('green'); // set text and text size textSize(25); text('Press Key to change the figure '+ 'from Circle To Keyboard', 30, 30); // use of keyIsPressed Variable if (keyIsPressed) { // draw ellipse ellipse(mouseX, mouseY, 115, 115); fill('red'); text(\"Key Is Pressed\", 100, 300); } else { rect(mouseX / 2, mouseY / 2, 300, 200); } }",
"e": 815,
"s": 221,
"text": null
},
{
"code": null,
"e": 836,
"s": 815,
"text": "Output:Before:After:"
},
{
"code": null,
"e": 847,
"s": 836,
"text": "Example-2:"
},
{
"code": "let valueX;let valueY; function setup() { // Create Canvas of size 500*500 createCanvas(500, 500);} function draw() { // set background color background(200); fill('green'); // set text and text size textSize(25); text('Click to flip the the figure', 30, 30); // use of KeyIsPressed if (keyIsPressed) { fill(valueX, 255 - valueY, 255 - valueX); // draw rectangle rect(mouseX, mouseY, 115, 115); fill(valueY, 255 - valueX, 255 - valueX); rect(mouseX, mouseY + 115, 115, 115); fill(255 - valueY, 255 - valueX, 255 - valueY); } else { rect(mouseX - 115, mouseY, 115, 115); fill(255 - valueY, 255 - valueY, 255 - valueY); rect(mouseX - 115, mouseY + 115, 115, 115); }}",
"e": 1646,
"s": 847,
"text": null
},
{
"code": null,
"e": 1722,
"s": 1646,
"text": "Output:Before:After:Reference: https://p5js.org/reference/#/p5/keyIsPressed"
},
{
"code": null,
"e": 1739,
"s": 1722,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1750,
"s": 1739,
"text": "JavaScript"
},
{
"code": null,
"e": 1767,
"s": 1750,
"text": "Web Technologies"
},
{
"code": null,
"e": 1865,
"s": 1767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1926,
"s": 1865,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1998,
"s": 1926,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2038,
"s": 1998,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2091,
"s": 2038,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2143,
"s": 2091,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2205,
"s": 2143,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2238,
"s": 2205,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2299,
"s": 2238,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2349,
"s": 2299,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
SVG viewBox Attribute | 21 Jan, 2022
The viewBox is an attribute of the SVG element in HTML. It is used to scale the SVG element that means we can set the coordinates as well as width and height.
Syntax:
viewBox = "min-x min-y width height"
Attribute Values:
min-x: It is used to set the horizontal axis. It is used to make the SVG move on a horizontal axis (i.e Left and Right).
min-y: It is used to set the vertical axis. It is used to make the SVG move on a vertical axis (i.e Up and Down).
width: It is used to set the width of viewbox.
height: It is used to set the height of viewbox.
Note: The letter ‘B’ is capital in the viewBox.
So with the help of these values, we can scale the SVG vector and change the direction of it (i.e make it to left, right, top or bottom) based on the value defined in the width and height property in the SVG element.
Example:
<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type="text/css"> svg { border: 1px solid #aaa; } </style></head> <body> <!-- Without viewBox --> <svg width="200" height="200"> <circle cx="50" cy="50" r="45" stroke="#000" stroke-width="3" fill="none"/> </svg> <!-- With viewBox --> <svg width="200" height="200" viewBox="0 0 200 200"> <circle cx="50" cy="50" r="45" stroke="#000" stroke-width="3" fill="none"/> </svg></body> </html>
Output:
Here, the square box shows the border for the SVG and with viewBox attribute we can set the scale and pan for the vector. The output for both of the above SVG elements are same. We set the width and height for SVG and viewBox equal (i.e 200) so we are getting both the circles of the same size.
Values of width and height: With the width and height values you can change the size of the SVG vector. So, if we want to change the size and make it larger, then set the value for width and height, in viewBox, smaller then the width and height properties of the SVG element.
Example:
<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type="text/css"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width="200" height="200" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="45" stroke="#000" stroke-width="3" fill="none"/> </svg></body> </html>
Output:
So now, to change the size of the SVG vector and make it smaller we have to set the value of width and height in the viewBox, larger than the width and height properties of SVG element.
Example:
<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type="text/css"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width="200" height="200" viewBox="0 0 300 300"> <circle cx="50" cy="50" r="45" stroke="#000" stroke-width="3" fill="none"/> </svg></body> </html>
Output:
Left Move: Set the value of x-min with a positive number. It will move the SVG in the left side.
Example:
<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type="text/css"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width="200" height="200" viewBox="50 0 100 100"> <circle cx="50" cy="50" r="45" stroke="#000" stroke-width="3" fill="none"/> </svg></body> </html>
Output:
Right Move: Set the value of x-min with a negative number. It will move the SVG to the right side.
Example:
<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type="text/css"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width="200" height="200" viewBox="-50 0 100 100"> <circle cx="50" cy="50" r="45" stroke="#000" stroke-width="3" fill="none"/> </svg></body> </html>
Output:
Top Move: Set the value of y-min to a positive number. It will move the SVG on the top side.
Example:
<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type="text/css"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width="200" height="200" viewBox="0 50 100 100"> <circle cx="50" cy="50" r="45" stroke="#000" stroke-width="3" fill="none"/> </svg></body> </html>
Output:
Bottom Move: Set the value of y-min with a negative number. It will move the SVG on the bottom side.
Example:
<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type="text/css"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width="200" height="200" viewBox="0 -50 100 100"> <circle cx="50" cy="50" r="45" stroke="#000" stroke-width="3" fill="none"/> </svg></body> </html>
Output:
adityakuumar466
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "The viewBox is an attribute of the SVG element in HTML. It is used to scale the SVG element that means we can set the coordinates as well as width and height."
},
{
"code": null,
"e": 195,
"s": 187,
"text": "Syntax:"
},
{
"code": null,
"e": 232,
"s": 195,
"text": "viewBox = \"min-x min-y width height\""
},
{
"code": null,
"e": 250,
"s": 232,
"text": "Attribute Values:"
},
{
"code": null,
"e": 371,
"s": 250,
"text": "min-x: It is used to set the horizontal axis. It is used to make the SVG move on a horizontal axis (i.e Left and Right)."
},
{
"code": null,
"e": 485,
"s": 371,
"text": "min-y: It is used to set the vertical axis. It is used to make the SVG move on a vertical axis (i.e Up and Down)."
},
{
"code": null,
"e": 532,
"s": 485,
"text": "width: It is used to set the width of viewbox."
},
{
"code": null,
"e": 581,
"s": 532,
"text": "height: It is used to set the height of viewbox."
},
{
"code": null,
"e": 629,
"s": 581,
"text": "Note: The letter ‘B’ is capital in the viewBox."
},
{
"code": null,
"e": 846,
"s": 629,
"text": "So with the help of these values, we can scale the SVG vector and change the direction of it (i.e make it to left, right, top or bottom) based on the value defined in the width and height property in the SVG element."
},
{
"code": null,
"e": 855,
"s": 846,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type=\"text/css\"> svg { border: 1px solid #aaa; } </style></head> <body> <!-- Without viewBox --> <svg width=\"200\" height=\"200\"> <circle cx=\"50\" cy=\"50\" r=\"45\" stroke=\"#000\" stroke-width=\"3\" fill=\"none\"/> </svg> <!-- With viewBox --> <svg width=\"200\" height=\"200\" viewBox=\"0 0 200 200\"> <circle cx=\"50\" cy=\"50\" r=\"45\" stroke=\"#000\" stroke-width=\"3\" fill=\"none\"/> </svg></body> </html>",
"e": 1432,
"s": 855,
"text": null
},
{
"code": null,
"e": 1440,
"s": 1432,
"text": "Output:"
},
{
"code": null,
"e": 1735,
"s": 1440,
"text": "Here, the square box shows the border for the SVG and with viewBox attribute we can set the scale and pan for the vector. The output for both of the above SVG elements are same. We set the width and height for SVG and viewBox equal (i.e 200) so we are getting both the circles of the same size."
},
{
"code": null,
"e": 2011,
"s": 1735,
"text": "Values of width and height: With the width and height values you can change the size of the SVG vector. So, if we want to change the size and make it larger, then set the value for width and height, in viewBox, smaller then the width and height properties of the SVG element."
},
{
"code": null,
"e": 2020,
"s": 2011,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type=\"text/css\"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width=\"200\" height=\"200\" viewBox=\"0 0 100 100\"> <circle cx=\"50\" cy=\"50\" r=\"45\" stroke=\"#000\" stroke-width=\"3\" fill=\"none\"/> </svg></body> </html>",
"e": 2383,
"s": 2020,
"text": null
},
{
"code": null,
"e": 2391,
"s": 2383,
"text": "Output:"
},
{
"code": null,
"e": 2577,
"s": 2391,
"text": "So now, to change the size of the SVG vector and make it smaller we have to set the value of width and height in the viewBox, larger than the width and height properties of SVG element."
},
{
"code": null,
"e": 2586,
"s": 2577,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type=\"text/css\"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width=\"200\" height=\"200\" viewBox=\"0 0 300 300\"> <circle cx=\"50\" cy=\"50\" r=\"45\" stroke=\"#000\" stroke-width=\"3\" fill=\"none\"/> </svg></body> </html>",
"e": 2947,
"s": 2586,
"text": null
},
{
"code": null,
"e": 2955,
"s": 2947,
"text": "Output:"
},
{
"code": null,
"e": 3052,
"s": 2955,
"text": "Left Move: Set the value of x-min with a positive number. It will move the SVG in the left side."
},
{
"code": null,
"e": 3061,
"s": 3052,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type=\"text/css\"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width=\"200\" height=\"200\" viewBox=\"50 0 100 100\"> <circle cx=\"50\" cy=\"50\" r=\"45\" stroke=\"#000\" stroke-width=\"3\" fill=\"none\"/> </svg></body> </html>",
"e": 3423,
"s": 3061,
"text": null
},
{
"code": null,
"e": 3431,
"s": 3423,
"text": "Output:"
},
{
"code": null,
"e": 3530,
"s": 3431,
"text": "Right Move: Set the value of x-min with a negative number. It will move the SVG to the right side."
},
{
"code": null,
"e": 3539,
"s": 3530,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type=\"text/css\"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width=\"200\" height=\"200\" viewBox=\"-50 0 100 100\"> <circle cx=\"50\" cy=\"50\" r=\"45\" stroke=\"#000\" stroke-width=\"3\" fill=\"none\"/> </svg></body> </html>",
"e": 3902,
"s": 3539,
"text": null
},
{
"code": null,
"e": 3910,
"s": 3902,
"text": "Output:"
},
{
"code": null,
"e": 4003,
"s": 3910,
"text": "Top Move: Set the value of y-min to a positive number. It will move the SVG on the top side."
},
{
"code": null,
"e": 4012,
"s": 4003,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type=\"text/css\"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width=\"200\" height=\"200\" viewBox=\"0 50 100 100\"> <circle cx=\"50\" cy=\"50\" r=\"45\" stroke=\"#000\" stroke-width=\"3\" fill=\"none\"/> </svg></body> </html>",
"e": 4374,
"s": 4012,
"text": null
},
{
"code": null,
"e": 4382,
"s": 4374,
"text": "Output:"
},
{
"code": null,
"e": 4483,
"s": 4382,
"text": "Bottom Move: Set the value of y-min with a negative number. It will move the SVG on the bottom side."
},
{
"code": null,
"e": 4492,
"s": 4483,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>SVG viewBox Attribute</title> <style type=\"text/css\"> svg { border: 1px solid #aaa; } </style></head> <body> <svg width=\"200\" height=\"200\" viewBox=\"0 -50 100 100\"> <circle cx=\"50\" cy=\"50\" r=\"45\" stroke=\"#000\" stroke-width=\"3\" fill=\"none\"/> </svg></body> </html>",
"e": 4855,
"s": 4492,
"text": null
},
{
"code": null,
"e": 4863,
"s": 4855,
"text": "Output:"
},
{
"code": null,
"e": 4879,
"s": 4863,
"text": "adityakuumar466"
},
{
"code": null,
"e": 4886,
"s": 4879,
"text": "Picked"
},
{
"code": null,
"e": 4891,
"s": 4886,
"text": "HTML"
},
{
"code": null,
"e": 4908,
"s": 4891,
"text": "Web Technologies"
},
{
"code": null,
"e": 4935,
"s": 4908,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4940,
"s": 4935,
"text": "HTML"
}
] |
Number of subarrays having sum less than K | 04 May, 2021
Given an array of non-negative numbers and a non-negative number k, find the number of subarrays having sum less than k. We may assume that there is no overflow.Examples :
Input : arr[] = {2, 5, 6}
K = 10
Output : 4
The subarrays are {2}, {5}, {6} and
{2, 5},
Input : arr[] = {1, 11, 2, 3, 15}
K = 10
Output : 4
{1}, {2}, {3} and {2, 3}
A simple solution is to generate all subarrays of the array and then count the number of arrays having sum less than K. Below is the implementation of above approach :
C++
Java
Python3
C#
PHP
Javascript
// CPP program to count// subarrays having sum// less than k.#include <bits/stdc++.h>using namespace std; // Function to find number// of subarrays having sum// less than k.int countSubarray(int arr[], int n, int k){ int count = 0; for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // If sum is less than k // then update sum and // increment count if (sum + arr[j] < k) { sum = arr[j] + sum; count++; } else { break; } } } return count;} // Driver Codeint main(){ int array[] = { 1, 11, 2, 3, 15 }; int k = 10; int size = sizeof(array) / sizeof(array[0]); int count = countSubarray(array, size, k); cout << count << "\n";}
// Java program to count subarrays// having sum less than k.import java.io.*; class GFG { // Function to find number of // subarrays having sum less than k. static int countSubarray(int arr[], int n, int k) { int count = 0; for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // If sum is less than // k then update sum and // increment count if (sum + arr[j] < k) { sum = arr[j] + sum; count++; } else { break; } } } return count; } // Driver Code public static void main(String[] args) { int array[] = { 1, 11, 2, 3, 15 }; int k = 10; int size = array.length; int count = countSubarray(array, size, k); System.out.println(count); }} // This code is contributed by Sam007
# python program to count subarrays# having sum less than k. # Function to find number of subarrays# having sum less than k.def countSubarray(arr, n, k): count = 0 for i in range(0, n): sum = 0; for j in range(i, n): # If sum is less than k # then update sum and # increment count if (sum + arr[j] < k): sum = arr[j] + sum count+= 1 else: break return count; # Driver Codearray = [1, 11, 2, 3, 15]k = 10size = len(array)count = countSubarray(array, size, k);print(count) # This code is contributed by Sam007
// C# program to count subarrays// having sum less than k.using System; class GFG { // Function to find number // of subarrays having sum // less than k. static int countSubarray(int[] arr, int n, int k) { int count = 0; for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // If sum is less than k // then update sum and // increment count if (sum + arr[j] < k) { sum = arr[j] + sum; count++; } else { break; } } } return count; } // Driver Code public static void Main(String[] args) { int[] array = { 1, 11, 2, 3, 15 }; int k = 10; int size = array.Length; int count = countSubarray(array, size, k); Console.WriteLine(count); }} // This code is contributed by Sam007
<?php// PHP program to count// subarrays having sum// less than k. // Function to find number // of subarrays having sum// less than k.function countSubarray($arr, $n, $k){ $count = 0; for ($i = 0; $i < $n; $i++) { $sum = 0; for ($j = $i; $j < $n; $j++) { // If sum is less than // k then update sum and // increment count if ($sum + $arr[$j] < $k) { $sum = $arr[$j] + $sum; $count++; } else { break; } } } return $count;} // Driver Code$array = array(1, 11, 2, 3, 15);$k = 10;$size = sizeof($array);$count = countSubarray($array, $size, $k);echo $count, "\n"; // This code is contributed by ajit?>
<script>// javascript program to count subarrays// having sum less than k. // Function to find number of // subarrays having sum less than k. function countSubarray(arr , n , k) { var count = 0; for (i = 0; i < n; i++) { var sum = 0; for (j = i; j < n; j++) { // If sum is less than // k then update sum and // increment count if (sum + arr[j] < k) { sum = arr[j] + sum; count++; } else { break; } } } return count; } // Driver Code var array = [ 1, 11, 2, 3, 15 ]; var k = 10; var size = array.length; var count = countSubarray(array, size, k); document.write(count); // This code is contributed by Rajput-Ji</script>
4
Time complexity : O(n^2).An efficient solution is based on a sliding window technique that can be used to solve the problem. We use two pointers start and end to represent starting and ending points of the sliding window. (Not that we need to find contiguous parts).Initially both start and endpoint to the beginning of the array, i.e. index 0. Now, let’s try to add a new element el. There are two possible conditions.1st case : If sum is less than k, increment end by one position. So contiguous arrays this step produce are (end – start). We also add el to previous sum. There are as many such arrays as the length of the window.2nd case : If sum becomes greater than or equal to k, this means we need to subtract starting element from sum so that the sum again becomes less than k. So we adjust the window’s left border by incrementing start.We follow the same procedure until end < array size.Implementation:
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to count// subarrays having sum// less than k.#include <bits/stdc++.h>using namespace std; // Function to find number// of subarrays having sum// less than k.int countSubarrays(int arr[], int n, int k){ int start = 0, end = 0, count = 0, sum = arr[0]; while (start < n && end < n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if (sum < k) { end++; if (end >= start) count += end - start; // For last element, // end may become n if (end < n) sum += arr[end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { sum -= arr[start]; start++; } } return count;} // Driver Codeint main(){ int array[] = { 1, 11, 2, 3, 15 }; int k = 10; int size = sizeof(array) / sizeof(array[0]); cout << countSubarrays(array, size, k);}
// Java program to count// subarrays having sum// less than k.import java.io.*; class GFG { // Function to find number // of subarrays having sum // less than k. static int countSubarray(int arr[], int n, int k) { int start = 0, end = 0; int count = 0, sum = arr[0]; while (start < n && end < n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if (sum < k) { end++; if (end >= start) count += end - start; // For last element, // end may become n. if (end < n) sum += arr[end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { sum -= arr[start]; start++; } } return count; } // Driver Code public static void main(String[] args) { int array[] = { 1, 11, 2, 3, 15 }; int k = 10; int size = array.length; int count = countSubarray(array, size, k); System.out.println(count); }} // This code is contributed by Sam007
# Python 3 program to count subarrays# having sum less than k. # Function to find number of subarrays# having sum less than k.def countSubarrays(arr, n, k): start = 0 end = 0 count = 0 sum = arr[0] while (start < n and end < n) : # If sum is less than k, move end # by one position. Update count and # sum accordingly. if (sum < k) : end += 1 if (end >= start): count += end - start # For last element, end may become n if (end < n): sum += arr[end] # If sum is greater than or equal to k, # subtract arr[start] from sum and # decrease sliding window by moving # start by one position else : sum -= arr[start] start += 1 return count # Driver Codeif __name__ == "__main__": array = [ 1, 11, 2, 3, 15 ] k = 10 size = len(array) print(countSubarrays(array, size, k)) # This code is contributed by ita_c
// C# program to count// subarrays having sum// less than k.using System; class GFG { // Function to find number // of subarrays having sum // less than k. static int countSubarray(int[] arr, int n, int k) { int start = 0, end = 0; int count = 0, sum = arr[0]; while (start < n && end < n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if (sum < k) { end++; if (end >= start) count += end - start; // For last element, // end may become n. if (end < n) sum += arr[end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { sum -= arr[start]; start++; } } return count; } // Driver Code public static void Main(String[] args) { int[] array = { 1, 11, 2, 3, 15 }; int k = 10; int size = array.Length; int count = countSubarray(array, size, k); Console.WriteLine(count); }} // This code is contributed by Sam007
<?php// PHP program to count// subarrays having sum// less than k. // Function to find number// of subarrays having sum// less than k.function countSubarrays($arr, $n, $k){ $start = 0; $end = 0; $count = 0; $sum = $arr[0]; while ($start < $n && $end < $n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if ($sum < $k) { $end++; if ($end >= $start) $count += $end - $start; // For last element, // end may become n if ($end < $n) $sum += $arr[$end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { $sum -= $arr[$start]; $start++; } } return $count;} // Driver Code $array =array (1, 11, 2, 3, 15); $k = 10; $size = sizeof($array) ; echo countSubarrays($array, $size, $k); // This code is contributed by ajit?>
<script> // Javascript program to count // subarrays having sum // less than k. // Function to find number // of subarrays having sum // less than k. function countSubarray(arr, n, k) { let start = 0, end = 0; let count = 0, sum = arr[0]; while (start < n && end < n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if (sum < k) { end++; if (end >= start) count += end - start; // For last element, // end may become n. if (end < n) sum += arr[end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { sum -= arr[start]; start++; } } return count; } let array = [ 1, 11, 2, 3, 15 ]; let k = 10; let size = array.length; let count = countSubarray(array, size, k); document.write(count); </script>
4
Time complexity : O(n).
Sam007
jit_t
ukasp
mmayankk98
Rajput-Ji
suresh07
sliding-window
subarray
subarray-sum
Arrays
sliding-window
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 May, 2021"
},
{
"code": null,
"e": 226,
"s": 52,
"text": "Given an array of non-negative numbers and a non-negative number k, find the number of subarrays having sum less than k. We may assume that there is no overflow.Examples : "
},
{
"code": null,
"e": 408,
"s": 226,
"text": "Input : arr[] = {2, 5, 6}\n K = 10\nOutput : 4\nThe subarrays are {2}, {5}, {6} and\n{2, 5},\n\nInput : arr[] = {1, 11, 2, 3, 15}\n K = 10\nOutput : 4\n{1}, {2}, {3} and {2, 3}"
},
{
"code": null,
"e": 580,
"s": 410,
"text": "A simple solution is to generate all subarrays of the array and then count the number of arrays having sum less than K. Below is the implementation of above approach : "
},
{
"code": null,
"e": 584,
"s": 580,
"text": "C++"
},
{
"code": null,
"e": 589,
"s": 584,
"text": "Java"
},
{
"code": null,
"e": 597,
"s": 589,
"text": "Python3"
},
{
"code": null,
"e": 600,
"s": 597,
"text": "C#"
},
{
"code": null,
"e": 604,
"s": 600,
"text": "PHP"
},
{
"code": null,
"e": 615,
"s": 604,
"text": "Javascript"
},
{
"code": "// CPP program to count// subarrays having sum// less than k.#include <bits/stdc++.h>using namespace std; // Function to find number// of subarrays having sum// less than k.int countSubarray(int arr[], int n, int k){ int count = 0; for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // If sum is less than k // then update sum and // increment count if (sum + arr[j] < k) { sum = arr[j] + sum; count++; } else { break; } } } return count;} // Driver Codeint main(){ int array[] = { 1, 11, 2, 3, 15 }; int k = 10; int size = sizeof(array) / sizeof(array[0]); int count = countSubarray(array, size, k); cout << count << \"\\n\";}",
"e": 1452,
"s": 615,
"text": null
},
{
"code": "// Java program to count subarrays// having sum less than k.import java.io.*; class GFG { // Function to find number of // subarrays having sum less than k. static int countSubarray(int arr[], int n, int k) { int count = 0; for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // If sum is less than // k then update sum and // increment count if (sum + arr[j] < k) { sum = arr[j] + sum; count++; } else { break; } } } return count; } // Driver Code public static void main(String[] args) { int array[] = { 1, 11, 2, 3, 15 }; int k = 10; int size = array.length; int count = countSubarray(array, size, k); System.out.println(count); }} // This code is contributed by Sam007",
"e": 2463,
"s": 1452,
"text": null
},
{
"code": "# python program to count subarrays# having sum less than k. # Function to find number of subarrays# having sum less than k.def countSubarray(arr, n, k): count = 0 for i in range(0, n): sum = 0; for j in range(i, n): # If sum is less than k # then update sum and # increment count if (sum + arr[j] < k): sum = arr[j] + sum count+= 1 else: break return count; # Driver Codearray = [1, 11, 2, 3, 15]k = 10size = len(array)count = countSubarray(array, size, k);print(count) # This code is contributed by Sam007",
"e": 3109,
"s": 2463,
"text": null
},
{
"code": "// C# program to count subarrays// having sum less than k.using System; class GFG { // Function to find number // of subarrays having sum // less than k. static int countSubarray(int[] arr, int n, int k) { int count = 0; for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // If sum is less than k // then update sum and // increment count if (sum + arr[j] < k) { sum = arr[j] + sum; count++; } else { break; } } } return count; } // Driver Code public static void Main(String[] args) { int[] array = { 1, 11, 2, 3, 15 }; int k = 10; int size = array.Length; int count = countSubarray(array, size, k); Console.WriteLine(count); }} // This code is contributed by Sam007",
"e": 4119,
"s": 3109,
"text": null
},
{
"code": "<?php// PHP program to count// subarrays having sum// less than k. // Function to find number // of subarrays having sum// less than k.function countSubarray($arr, $n, $k){ $count = 0; for ($i = 0; $i < $n; $i++) { $sum = 0; for ($j = $i; $j < $n; $j++) { // If sum is less than // k then update sum and // increment count if ($sum + $arr[$j] < $k) { $sum = $arr[$j] + $sum; $count++; } else { break; } } } return $count;} // Driver Code$array = array(1, 11, 2, 3, 15);$k = 10;$size = sizeof($array);$count = countSubarray($array, $size, $k);echo $count, \"\\n\"; // This code is contributed by ajit?>",
"e": 4904,
"s": 4119,
"text": null
},
{
"code": "<script>// javascript program to count subarrays// having sum less than k. // Function to find number of // subarrays having sum less than k. function countSubarray(arr , n , k) { var count = 0; for (i = 0; i < n; i++) { var sum = 0; for (j = i; j < n; j++) { // If sum is less than // k then update sum and // increment count if (sum + arr[j] < k) { sum = arr[j] + sum; count++; } else { break; } } } return count; } // Driver Code var array = [ 1, 11, 2, 3, 15 ]; var k = 10; var size = array.length; var count = countSubarray(array, size, k); document.write(count); // This code is contributed by Rajput-Ji</script>",
"e": 5851,
"s": 4904,
"text": null
},
{
"code": null,
"e": 5853,
"s": 5851,
"text": "4"
},
{
"code": null,
"e": 6771,
"s": 5855,
"text": "Time complexity : O(n^2).An efficient solution is based on a sliding window technique that can be used to solve the problem. We use two pointers start and end to represent starting and ending points of the sliding window. (Not that we need to find contiguous parts).Initially both start and endpoint to the beginning of the array, i.e. index 0. Now, let’s try to add a new element el. There are two possible conditions.1st case : If sum is less than k, increment end by one position. So contiguous arrays this step produce are (end – start). We also add el to previous sum. There are as many such arrays as the length of the window.2nd case : If sum becomes greater than or equal to k, this means we need to subtract starting element from sum so that the sum again becomes less than k. So we adjust the window’s left border by incrementing start.We follow the same procedure until end < array size.Implementation: "
},
{
"code": null,
"e": 6775,
"s": 6771,
"text": "C++"
},
{
"code": null,
"e": 6780,
"s": 6775,
"text": "Java"
},
{
"code": null,
"e": 6789,
"s": 6780,
"text": "Python 3"
},
{
"code": null,
"e": 6792,
"s": 6789,
"text": "C#"
},
{
"code": null,
"e": 6796,
"s": 6792,
"text": "PHP"
},
{
"code": null,
"e": 6807,
"s": 6796,
"text": "Javascript"
},
{
"code": "// CPP program to count// subarrays having sum// less than k.#include <bits/stdc++.h>using namespace std; // Function to find number// of subarrays having sum// less than k.int countSubarrays(int arr[], int n, int k){ int start = 0, end = 0, count = 0, sum = arr[0]; while (start < n && end < n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if (sum < k) { end++; if (end >= start) count += end - start; // For last element, // end may become n if (end < n) sum += arr[end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { sum -= arr[start]; start++; } } return count;} // Driver Codeint main(){ int array[] = { 1, 11, 2, 3, 15 }; int k = 10; int size = sizeof(array) / sizeof(array[0]); cout << countSubarrays(array, size, k);}",
"e": 7943,
"s": 6807,
"text": null
},
{
"code": "// Java program to count// subarrays having sum// less than k.import java.io.*; class GFG { // Function to find number // of subarrays having sum // less than k. static int countSubarray(int arr[], int n, int k) { int start = 0, end = 0; int count = 0, sum = arr[0]; while (start < n && end < n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if (sum < k) { end++; if (end >= start) count += end - start; // For last element, // end may become n. if (end < n) sum += arr[end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { sum -= arr[start]; start++; } } return count; } // Driver Code public static void main(String[] args) { int array[] = { 1, 11, 2, 3, 15 }; int k = 10; int size = array.length; int count = countSubarray(array, size, k); System.out.println(count); }} // This code is contributed by Sam007",
"e": 9330,
"s": 7943,
"text": null
},
{
"code": "# Python 3 program to count subarrays# having sum less than k. # Function to find number of subarrays# having sum less than k.def countSubarrays(arr, n, k): start = 0 end = 0 count = 0 sum = arr[0] while (start < n and end < n) : # If sum is less than k, move end # by one position. Update count and # sum accordingly. if (sum < k) : end += 1 if (end >= start): count += end - start # For last element, end may become n if (end < n): sum += arr[end] # If sum is greater than or equal to k, # subtract arr[start] from sum and # decrease sliding window by moving # start by one position else : sum -= arr[start] start += 1 return count # Driver Codeif __name__ == \"__main__\": array = [ 1, 11, 2, 3, 15 ] k = 10 size = len(array) print(countSubarrays(array, size, k)) # This code is contributed by ita_c",
"e": 10332,
"s": 9330,
"text": null
},
{
"code": "// C# program to count// subarrays having sum// less than k.using System; class GFG { // Function to find number // of subarrays having sum // less than k. static int countSubarray(int[] arr, int n, int k) { int start = 0, end = 0; int count = 0, sum = arr[0]; while (start < n && end < n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if (sum < k) { end++; if (end >= start) count += end - start; // For last element, // end may become n. if (end < n) sum += arr[end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { sum -= arr[start]; start++; } } return count; } // Driver Code public static void Main(String[] args) { int[] array = { 1, 11, 2, 3, 15 }; int k = 10; int size = array.Length; int count = countSubarray(array, size, k); Console.WriteLine(count); }} // This code is contributed by Sam007",
"e": 11712,
"s": 10332,
"text": null
},
{
"code": "<?php// PHP program to count// subarrays having sum// less than k. // Function to find number// of subarrays having sum// less than k.function countSubarrays($arr, $n, $k){ $start = 0; $end = 0; $count = 0; $sum = $arr[0]; while ($start < $n && $end < $n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if ($sum < $k) { $end++; if ($end >= $start) $count += $end - $start; // For last element, // end may become n if ($end < $n) $sum += $arr[$end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { $sum -= $arr[$start]; $start++; } } return $count;} // Driver Code $array =array (1, 11, 2, 3, 15); $k = 10; $size = sizeof($array) ; echo countSubarrays($array, $size, $k); // This code is contributed by ajit?>",
"e": 12845,
"s": 11712,
"text": null
},
{
"code": "<script> // Javascript program to count // subarrays having sum // less than k. // Function to find number // of subarrays having sum // less than k. function countSubarray(arr, n, k) { let start = 0, end = 0; let count = 0, sum = arr[0]; while (start < n && end < n) { // If sum is less than k, // move end by one position. // Update count and sum // accordingly. if (sum < k) { end++; if (end >= start) count += end - start; // For last element, // end may become n. if (end < n) sum += arr[end]; } // If sum is greater than or // equal to k, subtract // arr[start] from sum and // decrease sliding window by // moving start by one position else { sum -= arr[start]; start++; } } return count; } let array = [ 1, 11, 2, 3, 15 ]; let k = 10; let size = array.length; let count = countSubarray(array, size, k); document.write(count); </script>",
"e": 14083,
"s": 12845,
"text": null
},
{
"code": null,
"e": 14085,
"s": 14083,
"text": "4"
},
{
"code": null,
"e": 14112,
"s": 14087,
"text": "Time complexity : O(n). "
},
{
"code": null,
"e": 14119,
"s": 14112,
"text": "Sam007"
},
{
"code": null,
"e": 14125,
"s": 14119,
"text": "jit_t"
},
{
"code": null,
"e": 14131,
"s": 14125,
"text": "ukasp"
},
{
"code": null,
"e": 14142,
"s": 14131,
"text": "mmayankk98"
},
{
"code": null,
"e": 14152,
"s": 14142,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 14161,
"s": 14152,
"text": "suresh07"
},
{
"code": null,
"e": 14176,
"s": 14161,
"text": "sliding-window"
},
{
"code": null,
"e": 14185,
"s": 14176,
"text": "subarray"
},
{
"code": null,
"e": 14198,
"s": 14185,
"text": "subarray-sum"
},
{
"code": null,
"e": 14205,
"s": 14198,
"text": "Arrays"
},
{
"code": null,
"e": 14220,
"s": 14205,
"text": "sliding-window"
},
{
"code": null,
"e": 14227,
"s": 14220,
"text": "Arrays"
}
] |
How to install a Python Module? | The best and recommended way to install Python modules is to use pip, the Python package manager.
If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setuptools, but will need to upgrade to the latest version:
On Linux or macOS:
pip install -U pip setuptools
On Windows:
python -m pip install -U pip setuptools
If you’re using a Python install on Linux that’s managed by the system package manager (e.g "yum", "apt-get" etc...), and you want to use the system package manager to install or upgrade pip, then see: https://packaging.python.org/guides/installing-using-linux-tools/
Otherwise:
Download get-pip.py from https://bootstrap.pypa.io/get-pip.py. Run python get-pip.py. This will install or upgrade pip.
Now you can use pip to install python packages. For example, To install the latest version of "SomeProject":
$ pip install 'SomeProject'
To install a specific version:
$ pip install 'SomeProject==1.4'
To install greater than or equal to one version and less than another:
$ pip install 'SomeProject>=1,<2' | [
{
"code": null,
"e": 1285,
"s": 1187,
"text": "The best and recommended way to install Python modules is to use pip, the Python package manager."
},
{
"code": null,
"e": 1449,
"s": 1285,
"text": "If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setuptools, but will need to upgrade to the latest version:"
},
{
"code": null,
"e": 1468,
"s": 1449,
"text": "On Linux or macOS:"
},
{
"code": null,
"e": 1498,
"s": 1468,
"text": "pip install -U pip setuptools"
},
{
"code": null,
"e": 1510,
"s": 1498,
"text": "On Windows:"
},
{
"code": null,
"e": 1550,
"s": 1510,
"text": "python -m pip install -U pip setuptools"
},
{
"code": null,
"e": 1818,
"s": 1550,
"text": "If you’re using a Python install on Linux that’s managed by the system package manager (e.g \"yum\", \"apt-get\" etc...), and you want to use the system package manager to install or upgrade pip, then see: https://packaging.python.org/guides/installing-using-linux-tools/"
},
{
"code": null,
"e": 1829,
"s": 1818,
"text": "Otherwise:"
},
{
"code": null,
"e": 1949,
"s": 1829,
"text": "Download get-pip.py from https://bootstrap.pypa.io/get-pip.py. Run python get-pip.py. This will install or upgrade pip."
},
{
"code": null,
"e": 2058,
"s": 1949,
"text": "Now you can use pip to install python packages. For example, To install the latest version of \"SomeProject\":"
},
{
"code": null,
"e": 2086,
"s": 2058,
"text": "$ pip install 'SomeProject'"
},
{
"code": null,
"e": 2117,
"s": 2086,
"text": "To install a specific version:"
},
{
"code": null,
"e": 2150,
"s": 2117,
"text": "$ pip install 'SomeProject==1.4'"
},
{
"code": null,
"e": 2221,
"s": 2150,
"text": "To install greater than or equal to one version and less than another:"
},
{
"code": null,
"e": 2255,
"s": 2221,
"text": "$ pip install 'SomeProject>=1,<2'"
}
] |
How to use Bootstrap in ReactJS ? | 28 Apr, 2021
There are the following ways we can use bootstrap in our ReactJS Project.
1. Using Bootstrap CDN: The simplest way to use Bootstrap in your React application is to use BootstrapCDN. There are no downloads or installations needed. Simply provide a link in the head section of your app, as seen in the example below.
<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css”integrity=”sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4′′crossorigin=”anonymous”>
2. Using the react-bootstrap library: This is the recommended method for applying Bootstrap to your React program if you’re using a build tool or a package bundler like webpack. Bootstrap must be installed as a dependency for your app.
npm install bootstrap
3. Install a React Bootstrap package: The third choice for integrating Bootstrap into a React app is to use a package that includes rebuilt Bootstrap components that can be used as React components. The following are the two most common packages:
react-bootstrap
reactstrap
In the following example, we have implemented the first way to use Bootstrap in the ReactJS project.
Creating React Application:
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
Project Structure: It will look like the following.
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, { useState } from 'react'; class App extends React.Component { constructor(props) { super(props) this.state = { counter: 0 } this.handleClick = this.handleClick.bind(this); } handleClick = () => { console.log("hi") alert("The value of counter is :" + this.state.counter) this.setState({ counter: this.state.counter + 1 }) } render() { return ( <div > <div className="jumbotron"> <h1 className="display-4">Hello From GFG!</h1> <p className="lead">This is a simple Example of using bootstrap in React.</p> <hr className="my-4" /> <p>the Component is called jumbotron in bootstrap.</p> <p className="lead"> <a onClick={this.handleClick} className="btn btn-primary btn-lg" href="#" role="button">Click me</a> </p> </div> </div> ); }} export default App;
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:
Picked
React-Bootstrap
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
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?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 102,
"s": 28,
"text": "There are the following ways we can use bootstrap in our ReactJS Project."
},
{
"code": null,
"e": 343,
"s": 102,
"text": "1. Using Bootstrap CDN: The simplest way to use Bootstrap in your React application is to use BootstrapCDN. There are no downloads or installations needed. Simply provide a link in the head section of your app, as seen in the example below."
},
{
"code": null,
"e": 554,
"s": 343,
"text": "<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css”integrity=”sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4′′crossorigin=”anonymous”>"
},
{
"code": null,
"e": 791,
"s": 554,
"text": "2. Using the react-bootstrap library: This is the recommended method for applying Bootstrap to your React program if you’re using a build tool or a package bundler like webpack. Bootstrap must be installed as a dependency for your app."
},
{
"code": null,
"e": 813,
"s": 791,
"text": "npm install bootstrap"
},
{
"code": null,
"e": 1061,
"s": 813,
"text": "3. Install a React Bootstrap package: The third choice for integrating Bootstrap into a React app is to use a package that includes rebuilt Bootstrap components that can be used as React components. The following are the two most common packages:"
},
{
"code": null,
"e": 1077,
"s": 1061,
"text": "react-bootstrap"
},
{
"code": null,
"e": 1088,
"s": 1077,
"text": "reactstrap"
},
{
"code": null,
"e": 1189,
"s": 1088,
"text": "In the following example, we have implemented the first way to use Bootstrap in the ReactJS project."
},
{
"code": null,
"e": 1217,
"s": 1189,
"text": "Creating React Application:"
},
{
"code": null,
"e": 1312,
"s": 1217,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 1376,
"s": 1312,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1408,
"s": 1376,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1521,
"s": 1408,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 1621,
"s": 1521,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 1635,
"s": 1621,
"text": "cd foldername"
},
{
"code": null,
"e": 1687,
"s": 1635,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1817,
"s": 1687,
"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": 1824,
"s": 1817,
"text": "App.js"
},
{
"code": "import React, { useState } from 'react'; class App extends React.Component { constructor(props) { super(props) this.state = { counter: 0 } this.handleClick = this.handleClick.bind(this); } handleClick = () => { console.log(\"hi\") alert(\"The value of counter is :\" + this.state.counter) this.setState({ counter: this.state.counter + 1 }) } render() { return ( <div > <div className=\"jumbotron\"> <h1 className=\"display-4\">Hello From GFG!</h1> <p className=\"lead\">This is a simple Example of using bootstrap in React.</p> <hr className=\"my-4\" /> <p>the Component is called jumbotron in bootstrap.</p> <p className=\"lead\"> <a onClick={this.handleClick} className=\"btn btn-primary btn-lg\" href=\"#\" role=\"button\">Click me</a> </p> </div> </div> ); }} export default App;",
"e": 2764,
"s": 1824,
"text": null
},
{
"code": null,
"e": 2877,
"s": 2764,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2887,
"s": 2877,
"text": "npm start"
},
{
"code": null,
"e": 2986,
"s": 2887,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2993,
"s": 2986,
"text": "Picked"
},
{
"code": null,
"e": 3009,
"s": 2993,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 3025,
"s": 3009,
"text": "React-Questions"
},
{
"code": null,
"e": 3033,
"s": 3025,
"text": "ReactJS"
},
{
"code": null,
"e": 3050,
"s": 3033,
"text": "Web Technologies"
},
{
"code": null,
"e": 3148,
"s": 3050,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3186,
"s": 3148,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 3213,
"s": 3186,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 3252,
"s": 3213,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 3304,
"s": 3252,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 3343,
"s": 3304,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 3405,
"s": 3343,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3438,
"s": 3405,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3499,
"s": 3438,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3549,
"s": 3499,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Program to print right and left arrow patterns | 30 Apr, 2021
Write to program to print the right arrow pattern and the left arrow pattern formed of stars. Input is an odd number n which represents height and width of pattern to be printed.Examples:
Input : n = 9
Output :
*
*
*
*
*********
*
*
*
*
*
*
*
*
*********
*
*
*
*
Input : n = 7
Output :
*
*
*
*******
*
*
*
*
*
*
*******
*
*
*
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print Pyramid pattern#include <iostream>using namespace std; // function to print right arrow patternvoid rightpattern(int n){ // for printing upper portion int c1 = (n - 1) / 2; // for printing lower portion int c2 = 3 * n / 2 - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // checking conditions to print right arrow if (j - i == c1 || i + j == c2 || i == c1) cout << "*"; // otherwise print space else cout << " "; } // for jumping to next line cout << "\n"; }} // function to print left arrow patternvoid leftpattern(int n){ char s = ' '; char st = '*'; // for printing upper part for (int i = (n - 1) / 2; i > 0; i--) cout << string(i, s) << st << endl; // for printing middle part for (int i = 0; i < n; i++) cout << "*"; cout << endl; // for printing lower part for (int i = 1; i <= (n - 1) / 2; i++) cout << string(i, s) << st << endl; cout << endl;} // Driver programint main(){ int n = 9; // Must be odd // function calling to print right arrow rightpattern(n); cout << endl << endl; // function calling to print left arrow leftpattern(n); return 0;}
// Java program to print Pyramid patternclass GFG{ // function to print right arrow patternstatic void rightpattern(int n){ // for printing upper portion int c1 = (n - 1) / 2; // for printing lower portion int c2 = 3 * n / 2 - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // checking conditions to print // right arrow if (j - i == c1 || i + j == c2 || i == c1) { System.out.print("*"); } // otherwise print space else { System.out.print(" "); } } // for jumping to next line System.out.print("\n"); }} static void string(int n){ for (int i = n; i > 0; i--) { System.out.print(" "); }} // function to print left arrow patternstatic void leftpattern(int n){ char s = ' '; char st = '*'; // for printing upper part for (int i = (n - 1) / 2; i > 0; i--) { string(i); System.out.println(st); } // for printing middle part for (int i = 0; i < n; i++) { System.out.print("*"); } System.out.println(); // for printing lower part for (int i = 1; i <= (n - 1) / 2; i++) { string(i); System.out.println(st); } System.out.println();} // Driver Codepublic static void main(String args[]){ int n = 9; // Must be odd // function calling to print // right arrow rightpattern(n); System.out.println("\n"); // function calling to print // left arrow leftpattern(n);}} // This code is contributed// by PrinciRaj1992
# Python3 program to print Pyramid pattern # function to print right arrow patterndef rightpattern(n): # for printing upper portion c1 = (n - 1) // 2; # for printing lower portion c2 = 3 * n // 2 - 1; for i in range(n): for j in range(n): # checking conditions to print # right arrow if (j - i == c1 or i + j == c2 or i == c1): print("*", end = ""); # otherwise print space else: print(" ", end = ""); # for jumping to next line print(); def string(n): for i in range(n): print(" ", end = ""); # function to print left arrow patterndef leftpattern(n): s = ' '; st = '*'; # for printing upper part for i in range((n - 1) // 2, 0, -1): string(i); print(st); # for printing middle part for i in range(n): print("*", end = ""); print(); # for printing lower part for i in range(1, ((n - 1) // 2) + 1): string(i); print(st); print(); # Driver Codeif __name__ == '__main__': n = 9; # Must be odd # function calling to print # right arrow rightpattern(n); print(""); # function calling to print # left arrow leftpattern(n); # This code is contributed by PrinciRaj1992
// C# program to print Pyramid patternusing System; class GFG{ // function to print right arrow patternstatic void rightpattern(int n){ // for printing upper portion int c1 = (n - 1) / 2; // for printing lower portion int c2 = 3 * n / 2 - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // checking conditions to print // right arrow if (j - i == c1 || i + j == c2 || i == c1) { Console.Write("*"); } // otherwise print space else { Console.Write(" "); } } // for jumping to next line Console.Write("\n"); }} static void String(int n){ for (int i = n; i > 0; i--) { Console.Write(" "); }} // function to print left arrow patternstatic void leftpattern(int n){ char s = ' '; char st = '*'; // for printing upper part for (int i = (n - 1) / 2; i > 0; i--) { String(i); Console.WriteLine(st); } // for printing middle part for (int i = 0; i < n; i++) { Console.Write("*"); } Console.WriteLine(); // for printing lower part for (int i = 1; i <= (n - 1) / 2; i++) { String(i); Console.WriteLine(st); } Console.WriteLine();} // Driver Codepublic static void Main(){ int n = 9; // Must be odd // function calling to print // right arrow rightpattern(n); Console.WriteLine("\n"); // function calling to print // left arrow leftpattern(n);}} // This code is contributed// by Akanksha Rai
<?php // function to print right arrow patternfunction rightpattern($n){ // for printing upper portion $c1 = ($n - 1) / 2; // for printing lower portion $c2 = floor(3 * $n / 2 - 1); for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // checking conditions to // print right arrow if (($j - $i) == $c1 || ($i + $j) == $c2 || $i == $c1) echo "*"; // otherwise print space else echo " "; } // for jumping to next line echo "\n"; }} // function to print left arrow patternfunction leftpattern($n){ $s = ' '; $st = '*'; // for printing upper part for ($i = ($n - 1) / 2; $i > 0; $i--) { for($j = 0; $j < $i; $j++) echo " "; echo $st."\n"; } // for printing middle part for ($i = 0; $i < $n; $i++) echo "*"; echo "\n"; // for printing lower part for ($i = 1; $i <= ($n - 1) / 2; $i++) { for($j = 0; $j < $i; $j++) echo " "; echo $st."\n"; } echo "\n";} // Driver Code $n = 9; // Must be odd // function calling to // print right arrow rightpattern($n); echo "\n\n"; // function calling to // print left arrow leftpattern($n); // This code is contributed by mits ?>
<script> // function to print right arrow pattern function rightpattern(n) { // for printing upper portion var c1 = (n - 1) / 2; // for printing lower portion var c2 = Math.floor((3 * n) / 2 - 1); for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { // checking conditions to // print right arrow if (j - i === c1 || i + j === c2 || i === c1) document.write("*"); // otherwise print space else document.write(" "); } // for jumping to next line document.write("<br>"); } } // function to print left // arrow pattern function leftpattern(n) { var s = " "; var st = "*"; // for printing upper part for (var i = (n - 1) / 2; i > 0; i--) { for (var j = 0; j < i; j++) document.write(" "); document.write(st + "<br>"); } // for printing middle part for (var i = 0; i < n; i++) document.write("*"); document.write("<br>"); // for printing lower part for (var i = 1; i <= (n - 1) / 2; i++) { for (var j = 0; j < i; j++) document.write(" "); document.write(st + "<br>"); } document.write("<br>"); } // Driver Code var n = 9; // Must be odd // function calling to // print right arrow rightpattern(n); document.write("<br><br>"); // function calling to // print left arrow leftpattern(n); </script>
Output:
*
*
*
*
*********
*
*
*
*
*
*
*
*
*********
*
*
*
*
Time Complexity: O(n^2)
Mithun Kumar
princiraj1992
Akanksha_Rai
gfg_sal_gfg
rdtank
pattern-printing
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "Write to program to print the right arrow pattern and the left arrow pattern formed of stars. Input is an odd number n which represents height and width of pattern to be printed.Examples: "
},
{
"code": null,
"e": 480,
"s": 218,
"text": "Input : n = 9\nOutput :\n *\n * \n * \n *\n*********\n *\n *\n *\n *\n\n\n *\n *\n *\n *\n*********\n * \n *\n *\n *\n\n\nInput : n = 7\nOutput :\n *\n *\n *\n*******\n *\n *\n *\n\n\n *\n *\n *\n*******\n *\n *\n *"
},
{
"code": null,
"e": 488,
"s": 484,
"text": "C++"
},
{
"code": null,
"e": 493,
"s": 488,
"text": "Java"
},
{
"code": null,
"e": 501,
"s": 493,
"text": "Python3"
},
{
"code": null,
"e": 504,
"s": 501,
"text": "C#"
},
{
"code": null,
"e": 508,
"s": 504,
"text": "PHP"
},
{
"code": null,
"e": 519,
"s": 508,
"text": "Javascript"
},
{
"code": "// C++ program to print Pyramid pattern#include <iostream>using namespace std; // function to print right arrow patternvoid rightpattern(int n){ // for printing upper portion int c1 = (n - 1) / 2; // for printing lower portion int c2 = 3 * n / 2 - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // checking conditions to print right arrow if (j - i == c1 || i + j == c2 || i == c1) cout << \"*\"; // otherwise print space else cout << \" \"; } // for jumping to next line cout << \"\\n\"; }} // function to print left arrow patternvoid leftpattern(int n){ char s = ' '; char st = '*'; // for printing upper part for (int i = (n - 1) / 2; i > 0; i--) cout << string(i, s) << st << endl; // for printing middle part for (int i = 0; i < n; i++) cout << \"*\"; cout << endl; // for printing lower part for (int i = 1; i <= (n - 1) / 2; i++) cout << string(i, s) << st << endl; cout << endl;} // Driver programint main(){ int n = 9; // Must be odd // function calling to print right arrow rightpattern(n); cout << endl << endl; // function calling to print left arrow leftpattern(n); return 0;}",
"e": 1820,
"s": 519,
"text": null
},
{
"code": "// Java program to print Pyramid patternclass GFG{ // function to print right arrow patternstatic void rightpattern(int n){ // for printing upper portion int c1 = (n - 1) / 2; // for printing lower portion int c2 = 3 * n / 2 - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // checking conditions to print // right arrow if (j - i == c1 || i + j == c2 || i == c1) { System.out.print(\"*\"); } // otherwise print space else { System.out.print(\" \"); } } // for jumping to next line System.out.print(\"\\n\"); }} static void string(int n){ for (int i = n; i > 0; i--) { System.out.print(\" \"); }} // function to print left arrow patternstatic void leftpattern(int n){ char s = ' '; char st = '*'; // for printing upper part for (int i = (n - 1) / 2; i > 0; i--) { string(i); System.out.println(st); } // for printing middle part for (int i = 0; i < n; i++) { System.out.print(\"*\"); } System.out.println(); // for printing lower part for (int i = 1; i <= (n - 1) / 2; i++) { string(i); System.out.println(st); } System.out.println();} // Driver Codepublic static void main(String args[]){ int n = 9; // Must be odd // function calling to print // right arrow rightpattern(n); System.out.println(\"\\n\"); // function calling to print // left arrow leftpattern(n);}} // This code is contributed// by PrinciRaj1992",
"e": 3461,
"s": 1820,
"text": null
},
{
"code": "# Python3 program to print Pyramid pattern # function to print right arrow patterndef rightpattern(n): # for printing upper portion c1 = (n - 1) // 2; # for printing lower portion c2 = 3 * n // 2 - 1; for i in range(n): for j in range(n): # checking conditions to print # right arrow if (j - i == c1 or i + j == c2 or i == c1): print(\"*\", end = \"\"); # otherwise print space else: print(\" \", end = \"\"); # for jumping to next line print(); def string(n): for i in range(n): print(\" \", end = \"\"); # function to print left arrow patterndef leftpattern(n): s = ' '; st = '*'; # for printing upper part for i in range((n - 1) // 2, 0, -1): string(i); print(st); # for printing middle part for i in range(n): print(\"*\", end = \"\"); print(); # for printing lower part for i in range(1, ((n - 1) // 2) + 1): string(i); print(st); print(); # Driver Codeif __name__ == '__main__': n = 9; # Must be odd # function calling to print # right arrow rightpattern(n); print(\"\"); # function calling to print # left arrow leftpattern(n); # This code is contributed by PrinciRaj1992",
"e": 4796,
"s": 3461,
"text": null
},
{
"code": "// C# program to print Pyramid patternusing System; class GFG{ // function to print right arrow patternstatic void rightpattern(int n){ // for printing upper portion int c1 = (n - 1) / 2; // for printing lower portion int c2 = 3 * n / 2 - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // checking conditions to print // right arrow if (j - i == c1 || i + j == c2 || i == c1) { Console.Write(\"*\"); } // otherwise print space else { Console.Write(\" \"); } } // for jumping to next line Console.Write(\"\\n\"); }} static void String(int n){ for (int i = n; i > 0; i--) { Console.Write(\" \"); }} // function to print left arrow patternstatic void leftpattern(int n){ char s = ' '; char st = '*'; // for printing upper part for (int i = (n - 1) / 2; i > 0; i--) { String(i); Console.WriteLine(st); } // for printing middle part for (int i = 0; i < n; i++) { Console.Write(\"*\"); } Console.WriteLine(); // for printing lower part for (int i = 1; i <= (n - 1) / 2; i++) { String(i); Console.WriteLine(st); } Console.WriteLine();} // Driver Codepublic static void Main(){ int n = 9; // Must be odd // function calling to print // right arrow rightpattern(n); Console.WriteLine(\"\\n\"); // function calling to print // left arrow leftpattern(n);}} // This code is contributed// by Akanksha Rai",
"e": 6415,
"s": 4796,
"text": null
},
{
"code": "<?php // function to print right arrow patternfunction rightpattern($n){ // for printing upper portion $c1 = ($n - 1) / 2; // for printing lower portion $c2 = floor(3 * $n / 2 - 1); for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // checking conditions to // print right arrow if (($j - $i) == $c1 || ($i + $j) == $c2 || $i == $c1) echo \"*\"; // otherwise print space else echo \" \"; } // for jumping to next line echo \"\\n\"; }} // function to print left arrow patternfunction leftpattern($n){ $s = ' '; $st = '*'; // for printing upper part for ($i = ($n - 1) / 2; $i > 0; $i--) { for($j = 0; $j < $i; $j++) echo \" \"; echo $st.\"\\n\"; } // for printing middle part for ($i = 0; $i < $n; $i++) echo \"*\"; echo \"\\n\"; // for printing lower part for ($i = 1; $i <= ($n - 1) / 2; $i++) { for($j = 0; $j < $i; $j++) echo \" \"; echo $st.\"\\n\"; } echo \"\\n\";} // Driver Code $n = 9; // Must be odd // function calling to // print right arrow rightpattern($n); echo \"\\n\\n\"; // function calling to // print left arrow leftpattern($n); // This code is contributed by mits ?>",
"e": 7795,
"s": 6415,
"text": null
},
{
"code": "<script> // function to print right arrow pattern function rightpattern(n) { // for printing upper portion var c1 = (n - 1) / 2; // for printing lower portion var c2 = Math.floor((3 * n) / 2 - 1); for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { // checking conditions to // print right arrow if (j - i === c1 || i + j === c2 || i === c1) document.write(\"*\"); // otherwise print space else document.write(\" \"); } // for jumping to next line document.write(\"<br>\"); } } // function to print left // arrow pattern function leftpattern(n) { var s = \" \"; var st = \"*\"; // for printing upper part for (var i = (n - 1) / 2; i > 0; i--) { for (var j = 0; j < i; j++) document.write(\" \"); document.write(st + \"<br>\"); } // for printing middle part for (var i = 0; i < n; i++) document.write(\"*\"); document.write(\"<br>\"); // for printing lower part for (var i = 1; i <= (n - 1) / 2; i++) { for (var j = 0; j < i; j++) document.write(\" \"); document.write(st + \"<br>\"); } document.write(\"<br>\"); } // Driver Code var n = 9; // Must be odd // function calling to // print right arrow rightpattern(n); document.write(\"<br><br>\"); // function calling to // print left arrow leftpattern(n); </script>",
"e": 9408,
"s": 7795,
"text": null
},
{
"code": null,
"e": 9418,
"s": 9408,
"text": "Output: "
},
{
"code": null,
"e": 9553,
"s": 9418,
"text": " *\n * \n * \n *\n*********\n *\n *\n *\n *\n\n\n *\n *\n *\n *\n*********\n *\n *\n *\n *"
},
{
"code": null,
"e": 9578,
"s": 9553,
"text": "Time Complexity: O(n^2) "
},
{
"code": null,
"e": 9591,
"s": 9578,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 9605,
"s": 9591,
"text": "princiraj1992"
},
{
"code": null,
"e": 9618,
"s": 9605,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9630,
"s": 9618,
"text": "gfg_sal_gfg"
},
{
"code": null,
"e": 9637,
"s": 9630,
"text": "rdtank"
},
{
"code": null,
"e": 9654,
"s": 9637,
"text": "pattern-printing"
},
{
"code": null,
"e": 9673,
"s": 9654,
"text": "School Programming"
},
{
"code": null,
"e": 9690,
"s": 9673,
"text": "pattern-printing"
}
] |
Perl | Variables and its Types | 18 Apr, 2022
The reserved memory locations to store values are the Variables. This means that creating a variable, reserves a space in memory. Data type of a variable helps the interpreter to allocate memory and decide what to be stored in the reserved memory. Therefore, variables can store integers, decimals, or strings with the assignment of different data types to the variables.Perl has the following three basic data types namely –
Scalars
Arrays
Hashes
Hence, three types of variables will be used in Perl. A scalar variable can store either a number, a string, or a reference and will precede by a dollar sign ($). An array variable will store ordered lists of scalars and precede by @ sign. The Hash variable will be used to store sets of key/value pairs and will precede by sign %.
Perl variables need not to be declared explicitly to reserve memory space. Just like other programming languages, the operand to the left of the ‘=’ operator is basically the name of the variable, and the operand to the right of the ‘=’ operator is basically the value stored in the variable. For example:
$age = 40; $name = “XYZ”; $rollno = 22; Here 40, “XYZ” and 22 are the values assigned to $age, $name and $roll no variables, respectively.
A scalar is a single unit of data. It is possible that the data might be an integer number, floating point, a character, a string, a paragraph, or an entire web page. Here is an example of using scalar variables
Perl
#!/usr/bin/perl # Assigning values to scalar# variables$age = 40; $name = "XYZ";$rollno = 22; # Printing variable valuesprint "Age = $age\n";print "Name = $name\n";print "Roll no = $rollno\n";
Output:
Age = 40
Name = XYZ
Roll no = 22
Variable that stores an ordered list of scalar values is of array type. Variables of Array Datatype are preceded by an “at” (@) sign. The dollar sign ($) is used to refer a single element of an array with the variable name followed by the index of the element in square brackets. Here is an example of how to use an array variable:
Perl
#!/usr/bin/perl # Assigning values to Array variables@ages = (55, 80, 44); # @ is used to declare # array variables @names = ("XYZ", "LGH", "KMR"); # Printing values of Arraysprint "\$ages[0] = $ages[0]\n";print "\$ages[1] = $ages[1]\n";print "\$ages[2] = $ages[2]\n";print "\$names[0] = $names[0]\n";print "\$names[1] = $names[1]\n";print "\$names[2] = $names[2]\n";
Here we used ‘\’ before the ‘$’ sign just to print it as a statement. Otherwise Perl will by default understand it as a variable and will print the value stored in it. When executed, following result will be produced – Output:
$ages[0] = 55
$ages[1] = 80
$ages[2] = 44
$names[0] = XYZ
$names[1] = LGH
$names[2] = KMR
A hash is a set of key/value pairs. Variables of the Hash type are preceded by a modulus (%) sign. Keys are used to refer to a single variable in the Hash. To access these elements, Hash variable name followed by the Key associated with the value is used in curly brackets. Following is a simple example to show Hash Variable:
Perl
#!/usr/bin/perl # Defining Hash variable using '%'%data = ('XYZ', 55, 'LGH', 80, 'KMR', 44); # Printing values of Hash variablesprint "\$data{'XYZ'} = $data{'XYZ'}\n";print "\$data{'LGH'} = $data{'LGH'}\n";print "\$data{'KMR'} = $data{'KMR'}\n";
Output:
$data{'XYZ'} = 55
$data{'LGH'} = 80
$data{'KMR'} = 44
Based on the Context, Perl treats the same variable differently i.e., situation where a variable is being used. Example:
Perl
#!/usr/bin/perl # Defining Array variable@names = ('XYZ', 'LGH', 'KMR'); # Assigning values of array variable# to another array variable@copy = @names; # Assigning values of Array variable# to a scalar variable$size = @names; # Printing the values of new variables.print "Given names are : @copy\n";print "Number of names are : $size\n";
Output:
Given names are : XYZ LGH KMR
Number of names are : 3
Here @names is an array, which has been used in two different contexts. First, we copied it into any other array, i.e., list, so it returned all the elements assuming that context is list context. Next, the same array is tried to be stored in a scalar, which further returned just the number of elements in this array by default assuming it to be a scalar context. Following table displays the various contexts:
anikakapoor
sumitgumber28
perl-data-types
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Basic Syntax of a Perl Program
Perl | ne operator
Perl | Opening and Reading a File
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Perl | Writing to a File
Perl | File Handling Introduction
Perl | Multidimensional Hashes
Perl | Data Types
How to Install Perl on Windows? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 455,
"s": 28,
"text": "The reserved memory locations to store values are the Variables. This means that creating a variable, reserves a space in memory. Data type of a variable helps the interpreter to allocate memory and decide what to be stored in the reserved memory. Therefore, variables can store integers, decimals, or strings with the assignment of different data types to the variables.Perl has the following three basic data types namely – "
},
{
"code": null,
"e": 463,
"s": 455,
"text": "Scalars"
},
{
"code": null,
"e": 470,
"s": 463,
"text": "Arrays"
},
{
"code": null,
"e": 477,
"s": 470,
"text": "Hashes"
},
{
"code": null,
"e": 813,
"s": 477,
"text": "Hence, three types of variables will be used in Perl. A scalar variable can store either a number, a string, or a reference and will precede by a dollar sign ($). An array variable will store ordered lists of scalars and precede by @ sign. The Hash variable will be used to store sets of key/value pairs and will precede by sign %. "
},
{
"code": null,
"e": 1120,
"s": 813,
"text": "Perl variables need not to be declared explicitly to reserve memory space. Just like other programming languages, the operand to the left of the ‘=’ operator is basically the name of the variable, and the operand to the right of the ‘=’ operator is basically the value stored in the variable. For example: "
},
{
"code": null,
"e": 1262,
"s": 1120,
"text": "$age = 40; $name = “XYZ”; $rollno = 22; Here 40, “XYZ” and 22 are the values assigned to $age, $name and $roll no variables, respectively. "
},
{
"code": null,
"e": 1476,
"s": 1262,
"text": "A scalar is a single unit of data. It is possible that the data might be an integer number, floating point, a character, a string, a paragraph, or an entire web page. Here is an example of using scalar variables "
},
{
"code": null,
"e": 1481,
"s": 1476,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Assigning values to scalar# variables$age = 40; $name = \"XYZ\";$rollno = 22; # Printing variable valuesprint \"Age = $age\\n\";print \"Name = $name\\n\";print \"Roll no = $rollno\\n\";",
"e": 1677,
"s": 1481,
"text": null
},
{
"code": null,
"e": 1686,
"s": 1677,
"text": "Output: "
},
{
"code": null,
"e": 1720,
"s": 1686,
"text": "Age = 40\nName = XYZ\nRoll no = 22 "
},
{
"code": null,
"e": 2053,
"s": 1720,
"text": "Variable that stores an ordered list of scalar values is of array type. Variables of Array Datatype are preceded by an “at” (@) sign. The dollar sign ($) is used to refer a single element of an array with the variable name followed by the index of the element in square brackets. Here is an example of how to use an array variable: "
},
{
"code": null,
"e": 2058,
"s": 2053,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Assigning values to Array variables@ages = (55, 80, 44); # @ is used to declare # array variables @names = (\"XYZ\", \"LGH\", \"KMR\"); # Printing values of Arraysprint \"\\$ages[0] = $ages[0]\\n\";print \"\\$ages[1] = $ages[1]\\n\";print \"\\$ages[2] = $ages[2]\\n\";print \"\\$names[0] = $names[0]\\n\";print \"\\$names[1] = $names[1]\\n\";print \"\\$names[2] = $names[2]\\n\";",
"e": 2455,
"s": 2058,
"text": null
},
{
"code": null,
"e": 2683,
"s": 2455,
"text": "Here we used ‘\\’ before the ‘$’ sign just to print it as a statement. Otherwise Perl will by default understand it as a variable and will print the value stored in it. When executed, following result will be produced – Output: "
},
{
"code": null,
"e": 2774,
"s": 2683,
"text": "$ages[0] = 55\n$ages[1] = 80\n$ages[2] = 44\n$names[0] = XYZ\n$names[1] = LGH\n$names[2] = KMR "
},
{
"code": null,
"e": 3103,
"s": 2774,
"text": "A hash is a set of key/value pairs. Variables of the Hash type are preceded by a modulus (%) sign. Keys are used to refer to a single variable in the Hash. To access these elements, Hash variable name followed by the Key associated with the value is used in curly brackets. Following is a simple example to show Hash Variable: "
},
{
"code": null,
"e": 3108,
"s": 3103,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Defining Hash variable using '%'%data = ('XYZ', 55, 'LGH', 80, 'KMR', 44); # Printing values of Hash variablesprint \"\\$data{'XYZ'} = $data{'XYZ'}\\n\";print \"\\$data{'LGH'} = $data{'LGH'}\\n\";print \"\\$data{'KMR'} = $data{'KMR'}\\n\";",
"e": 3354,
"s": 3108,
"text": null
},
{
"code": null,
"e": 3363,
"s": 3354,
"text": "Output: "
},
{
"code": null,
"e": 3418,
"s": 3363,
"text": "$data{'XYZ'} = 55\n$data{'LGH'} = 80\n$data{'KMR'} = 44 "
},
{
"code": null,
"e": 3541,
"s": 3418,
"text": "Based on the Context, Perl treats the same variable differently i.e., situation where a variable is being used. Example: "
},
{
"code": null,
"e": 3546,
"s": 3541,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Defining Array variable@names = ('XYZ', 'LGH', 'KMR'); # Assigning values of array variable# to another array variable@copy = @names; # Assigning values of Array variable# to a scalar variable$size = @names; # Printing the values of new variables.print \"Given names are : @copy\\n\";print \"Number of names are : $size\\n\";",
"e": 3884,
"s": 3546,
"text": null
},
{
"code": null,
"e": 3893,
"s": 3884,
"text": "Output: "
},
{
"code": null,
"e": 3947,
"s": 3893,
"text": "Given names are : XYZ LGH KMR\nNumber of names are : 3"
},
{
"code": null,
"e": 4360,
"s": 3947,
"text": "Here @names is an array, which has been used in two different contexts. First, we copied it into any other array, i.e., list, so it returned all the elements assuming that context is list context. Next, the same array is tried to be stored in a scalar, which further returned just the number of elements in this array by default assuming it to be a scalar context. Following table displays the various contexts: "
},
{
"code": null,
"e": 4372,
"s": 4360,
"text": "anikakapoor"
},
{
"code": null,
"e": 4386,
"s": 4372,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4402,
"s": 4386,
"text": "perl-data-types"
},
{
"code": null,
"e": 4407,
"s": 4402,
"text": "Perl"
},
{
"code": null,
"e": 4412,
"s": 4407,
"text": "Perl"
},
{
"code": null,
"e": 4510,
"s": 4412,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4551,
"s": 4510,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 4589,
"s": 4551,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 4608,
"s": 4589,
"text": "Perl | ne operator"
},
{
"code": null,
"e": 4642,
"s": 4608,
"text": "Perl | Opening and Reading a File"
},
{
"code": null,
"e": 4742,
"s": 4642,
"text": "Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)"
},
{
"code": null,
"e": 4767,
"s": 4742,
"text": "Perl | Writing to a File"
},
{
"code": null,
"e": 4801,
"s": 4767,
"text": "Perl | File Handling Introduction"
},
{
"code": null,
"e": 4832,
"s": 4801,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 4850,
"s": 4832,
"text": "Perl | Data Types"
}
] |
Java program to swap two numbers using XOR operator | Following is a program to swap two numbers using XOR operator.
public class ab31_SwapTwoNumberUsingXOR {
public static void main(String args[]){
int a,b;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a value :");
a = sc.nextInt();
System.out.println("Enter b value :");
b = sc.nextInt();
a = a^b;
b = a^b;
a = a^b;
System.out.println("Value of the variable a after swapping : "+a);
System.out.println("Value of the variable b after swapping : "+b);
}
}
Enter a value :
55
Enter b value :
64
Value of the variable a after swapping : 64
Value of the variable b after swapping : 55 | [
{
"code": null,
"e": 1250,
"s": 1187,
"text": "Following is a program to swap two numbers using XOR operator."
},
{
"code": null,
"e": 1729,
"s": 1250,
"text": "public class ab31_SwapTwoNumberUsingXOR {\n public static void main(String args[]){\n int a,b;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a value :\");\n a = sc.nextInt();\n System.out.println(\"Enter b value :\");\n b = sc.nextInt();\n a = a^b;\n b = a^b;\n a = a^b;\n System.out.println(\"Value of the variable a after swapping : \"+a);\n System.out.println(\"Value of the variable b after swapping : \"+b);\n }\n}"
},
{
"code": null,
"e": 1855,
"s": 1729,
"text": "Enter a value :\n55\nEnter b value :\n64\nValue of the variable a after swapping : 64\nValue of the variable b after swapping : 55"
}
] |
How to Use Material Text Input Layout in Android? | 23 Oct, 2020
Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Text Input Layout. So in this article, we’ll implement the Text Input Layout in android using the Material design library.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Add Required Dependency
Include google material design components dependency in the build.gradle file. After adding the dependencies don’t forget to click on the “Sync Now” button present at the top right corner.
implementation ‘com.google.android.material:material:1.3.0-alpha02’
Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below.
Step 3: Change the Base application theme
Go to app -> src -> main -> res -> values -> styles.xml and change the base application theme. Below is the code for the styles.xml file.
XML
<resources> <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
Step 4: Working with the activity_main.xml file
Inside the activity_main.xml file use the following code. It will result in the following design.
Below is the complete code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context=".MainActivity"> <com.google.android.material.textfield.TextInputLayout style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter password" app:endIconMode="password_toggle"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout>
Step 5: Inside the “styles.xml” file write the following to make the outline of the desired choice.
XML
<style name="Cut" parent="ShapeAppearance.MaterialComponents.MediumComponent"> <item name="cornerFamily">cut</item> <item name="cornerSize">12dp</item></style> <style name="Rounded" parent="ShapeAppearance.MaterialComponents.SmallComponent"> <item name="cornerFamily">rounded</item> <item name="cornerSize">16dp</item></style>
Step 6: Now use them inside the shapeAppearance property of TextInputLayout. It will result in the following design.
XML
<com.google.android.material.textfield.TextInputLayout style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter password" app:endIconMode="password_toggle"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter password" app:endIconMode="password_toggle" app:endIconTint="@color/colorAccent" app:shapeAppearance="@style/Cut"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter text" app:endIconMode="clear_text" app:endIconTint="@color/colorPrimaryDark" app:shapeAppearance="@style/Rounded"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout>
android
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Activity Lifecycle in Android with Demo App
Introduction to Android Development
Data Binding in Android with Example | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 706,
"s": 28,
"text": "Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Text Input Layout. So in this article, we’ll implement the Text Input Layout in android using the Material design library. "
},
{
"code": null,
"e": 735,
"s": 706,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 846,
"s": 735,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio."
},
{
"code": null,
"e": 878,
"s": 846,
"text": "Step 2: Add Required Dependency"
},
{
"code": null,
"e": 1069,
"s": 878,
"text": "Include google material design components dependency in the build.gradle file. After adding the dependencies don’t forget to click on the “Sync Now” button present at the top right corner. "
},
{
"code": null,
"e": 1137,
"s": 1069,
"text": "implementation ‘com.google.android.material:material:1.3.0-alpha02’"
},
{
"code": null,
"e": 1308,
"s": 1137,
"text": "Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below."
},
{
"code": null,
"e": 1350,
"s": 1308,
"text": "Step 3: Change the Base application theme"
},
{
"code": null,
"e": 1488,
"s": 1350,
"text": "Go to app -> src -> main -> res -> values -> styles.xml and change the base application theme. Below is the code for the styles.xml file."
},
{
"code": null,
"e": 1492,
"s": 1488,
"text": "XML"
},
{
"code": "<resources> <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.Light.NoActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> </style> </resources>",
"e": 1844,
"s": 1492,
"text": null
},
{
"code": null,
"e": 1892,
"s": 1844,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1991,
"s": 1892,
"text": "Inside the activity_main.xml file use the following code. It will result in the following design."
},
{
"code": null,
"e": 2050,
"s": 1991,
"text": "Below is the complete code for the activity_main.xml file."
},
{
"code": null,
"e": 2054,
"s": 2050,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" tools:context=\".MainActivity\"> <com.google.android.material.textfield.TextInputLayout style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Enter password\" app:endIconMode=\"password_toggle\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout>",
"e": 2973,
"s": 2054,
"text": null
},
{
"code": null,
"e": 3074,
"s": 2973,
"text": "Step 5: Inside the “styles.xml” file write the following to make the outline of the desired choice. "
},
{
"code": null,
"e": 3078,
"s": 3074,
"text": "XML"
},
{
"code": "<style name=\"Cut\" parent=\"ShapeAppearance.MaterialComponents.MediumComponent\"> <item name=\"cornerFamily\">cut</item> <item name=\"cornerSize\">12dp</item></style> <style name=\"Rounded\" parent=\"ShapeAppearance.MaterialComponents.SmallComponent\"> <item name=\"cornerFamily\">rounded</item> <item name=\"cornerSize\">16dp</item></style>",
"e": 3434,
"s": 3078,
"text": null
},
{
"code": null,
"e": 3551,
"s": 3434,
"text": "Step 6: Now use them inside the shapeAppearance property of TextInputLayout. It will result in the following design."
},
{
"code": null,
"e": 3555,
"s": 3551,
"text": "XML"
},
{
"code": "<com.google.android.material.textfield.TextInputLayout style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Enter password\" app:endIconMode=\"password_toggle\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Enter password\" app:endIconMode=\"password_toggle\" app:endIconTint=\"@color/colorAccent\" app:shapeAppearance=\"@style/Cut\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Enter text\" app:endIconMode=\"clear_text\" app:endIconTint=\"@color/colorPrimaryDark\" app:shapeAppearance=\"@style/Rounded\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout>",
"e": 5300,
"s": 3555,
"text": null
},
{
"code": null,
"e": 5308,
"s": 5300,
"text": "android"
},
{
"code": null,
"e": 5316,
"s": 5308,
"text": "Android"
},
{
"code": null,
"e": 5324,
"s": 5316,
"text": "Android"
},
{
"code": null,
"e": 5422,
"s": 5324,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5491,
"s": 5422,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 5523,
"s": 5491,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 5572,
"s": 5523,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 5611,
"s": 5572,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 5653,
"s": 5611,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 5704,
"s": 5653,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 5727,
"s": 5704,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 5771,
"s": 5727,
"text": "Activity Lifecycle in Android with Demo App"
},
{
"code": null,
"e": 5807,
"s": 5771,
"text": "Introduction to Android Development"
}
] |
How to Change Image Dynamically when User Scrolls using JavaScript ? | 19 Jan, 2022
We are going to add the functionality to our web-page so that whenever the user scrolls up or scrolls down on the image, then the image changes. We have used only 3 images but it can easily be expanded for multiple images.We are keeping the images on top of each other, this makes sure only one image is visible at a time. When we scroll, we decrement the z-coordinate of the current image and increments the z-coordinate of the new image. By doing this the new image overlays the old image and it comes on top of all images and becomes visible.
HTML Code: It is used to create a basic structure to include images.
html
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title> Change Image Dynamically when User Scrolls </title></head> <body><h1>GeeksforGeeks</h1><b>A Computer Science Portal for Geeks</b> <div id="scroll-image"> <img src="CSS.png" class="test" /> <img src="html.png" class="test" /> <img src="php.png" class="test" /> </div></body> </html>
CSS Code: Css is used to design the structure. The position property is the most important things here. It will make all the images to appear on top of each other.
html
<style> body { text-align: center; } h1 { color: green; } img { position: absolute; left: 300px; }</style>
Javascript code: In this section we will add JavaScript code to perform the scrolling on the image.
javascript
<script> window.onload = function() { // Index of current image // which is on display var imageIndex = 0; // Object array of all the // images of class test var images = document.getElementsByClassName('test'); // This tells us if mouse if over // image or not, We only change // image if mouse if over it var isMouseOverImage = false; // Object of parent element // containing all images var scrollImages = document.getElementById('scroll-image'); // Stores the current scroll co-ordinates // so that the window don't scroll down // while scrolling the images var x, y; // This function sets the scroll to x, y function noScroll() { window.scrollTo(x, y); } // The following event id fired once when // We hover mouse over the images scrollImages.addEventListener( "mouseenter", function() { // We store the current page // offset to x,y x = window.pageXOffset; y = window.pageYOffset; // We add the following event to // window object, so if we scroll // down after mouse is over the // image we can avoid scrolling // the window window.addEventListener("scroll", noScroll); // We set isMouseOverImage to // true, this means Mouse is // now over the image isMouseOverImage = true; }); // The following function is fired // when mouse is no longer over // the images scrollImages.addEventListener( "mouseleave", function() { // We set isMouseOverImage to // false, this means mouse is // not over the image isMouseOverImage = false; // We remove the event we previously // added because we are no longer // over the image, the scroll will // now scroll the window window.removeEventListener( "scroll", noScroll); }); // The following function is called // when we move mouse wheel over // the images scrollImages.addEventListener( "wheel", function(e) { // We check if we are over // image or not if (isMouseOverImage) { var nextImageIndex; // The following condition // finds the next image // index depending if we // scroll up or scroll down if (e.deltaY > 0) nextImageIndex = (imageIndex + 1) % images.length; else nextImageIndex = (imageIndex - 1 + images.length) % images.length; // We set the z index of current // image to 0 images[imageIndex].style.zIndex = "0"; // We set the z index of next // image to 1, this makes // The new image appear on top // of old image images[nextImageIndex].style.zIndex = "1"; imageIndex = nextImageIndex; } }); }</script>
Final Solution: In this section we will combine the above three section.
JavaScript
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title> Change image dynamically when user scrolls </title> <style> body { text-align: center; } h1 { color: green; } img { position: absolute; left: 300px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <div id="scroll-image"> <img src="CSS.png" class="test" /> <img src="html.png" class="test" /> <img src="php.png" class="test" /> </div> <script> window.onload = function() { // Index of current image // which is on display var imageIndex = 0; // Object array of all the // images of class test var images = document.getElementsByClassName('test'); // This tells us if mouse if over // image or not, We only change // image if mouse if over it var isMouseOverImage = false; // Object of parent element // containing all images var scrollImages = document.getElementById('scroll-image'); // Stores the current scroll co-ordinates // so that the window don't scroll down // while scrolling the images var x, y; // This function sets the scroll to x, y function noScroll() { window.scrollTo(x, y); } // The following event id fired once when // We hover mouse over the images scrollImages.addEventListener( "mouseenter", function() { // We store the current page // offset to x,y x = window.pageXOffset; y = window.pageYOffset; // We add the following event to // window object, so if we scroll // down after mouse is over the // image we can avoid scrolling // the window window.addEventListener("scroll", noScroll); // We set isMouseOverImage to // true, this means Mouse is // now over the image isMouseOverImage = true; }); // The following function is fired // when mouse is no longer over // the images scrollImages.addEventListener( "mouseleave", function() { // We set isMouseOverImage to // false, this means mouse is // not over the image isMouseOverImage = false; // We remove the event we previously // added because we are no longer // over the image, the scroll will // now scroll the window window.removeEventListener( "scroll", noScroll); }); // The following function is called // when we move mouse wheel over // the images scrollImages.addEventListener( "wheel", function(e) { // We check if we are over // image or not if (isMouseOverImage) { var nextImageIndex; // The following condition // finds the next image // index depending if we // scroll up or scroll down if (e.deltaY > 0) nextImageIndex = (imageIndex + 1) % images.length; else nextImageIndex = (imageIndex - 1 + images.length) % images.length; // We set the z index of current // image to 0 images[imageIndex].style.zIndex = "0"; // We set the z index of next // image to 1, this makes // The new image appear on top // of old image images[nextImageIndex].style.zIndex = "1"; imageIndex = nextImageIndex; } }); } </script></body> </html>
Output:
Note: The above code will change image only if mouse if over the image.
arorakashish0911
Vijay Sirra
rajeev0719singh
rkbhola5
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
How to auto-resize an image to fit a div container using CSS?
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 575,
"s": 28,
"text": "We are going to add the functionality to our web-page so that whenever the user scrolls up or scrolls down on the image, then the image changes. We have used only 3 images but it can easily be expanded for multiple images.We are keeping the images on top of each other, this makes sure only one image is visible at a time. When we scroll, we decrement the z-coordinate of the current image and increments the z-coordinate of the new image. By doing this the new image overlays the old image and it comes on top of all images and becomes visible. "
},
{
"code": null,
"e": 646,
"s": 575,
"text": "HTML Code: It is used to create a basic structure to include images. "
},
{
"code": null,
"e": 651,
"s": 646,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <title> Change Image Dynamically when User Scrolls </title></head> <body><h1>GeeksforGeeks</h1><b>A Computer Science Portal for Geeks</b> <div id=\"scroll-image\"> <img src=\"CSS.png\" class=\"test\" /> <img src=\"html.png\" class=\"test\" /> <img src=\"php.png\" class=\"test\" /> </div></body> </html> ",
"e": 1064,
"s": 651,
"text": null
},
{
"code": null,
"e": 1229,
"s": 1064,
"text": "CSS Code: Css is used to design the structure. The position property is the most important things here. It will make all the images to appear on top of each other. "
},
{
"code": null,
"e": 1234,
"s": 1229,
"text": "html"
},
{
"code": "<style> body { text-align: center; } h1 { color: green; } img { position: absolute; left: 300px; }</style>",
"e": 1387,
"s": 1234,
"text": null
},
{
"code": null,
"e": 1488,
"s": 1387,
"text": "Javascript code: In this section we will add JavaScript code to perform the scrolling on the image. "
},
{
"code": null,
"e": 1499,
"s": 1488,
"text": "javascript"
},
{
"code": "<script> window.onload = function() { // Index of current image // which is on display var imageIndex = 0; // Object array of all the // images of class test var images = document.getElementsByClassName('test'); // This tells us if mouse if over // image or not, We only change // image if mouse if over it var isMouseOverImage = false; // Object of parent element // containing all images var scrollImages = document.getElementById('scroll-image'); // Stores the current scroll co-ordinates // so that the window don't scroll down // while scrolling the images var x, y; // This function sets the scroll to x, y function noScroll() { window.scrollTo(x, y); } // The following event id fired once when // We hover mouse over the images scrollImages.addEventListener( \"mouseenter\", function() { // We store the current page // offset to x,y x = window.pageXOffset; y = window.pageYOffset; // We add the following event to // window object, so if we scroll // down after mouse is over the // image we can avoid scrolling // the window window.addEventListener(\"scroll\", noScroll); // We set isMouseOverImage to // true, this means Mouse is // now over the image isMouseOverImage = true; }); // The following function is fired // when mouse is no longer over // the images scrollImages.addEventListener( \"mouseleave\", function() { // We set isMouseOverImage to // false, this means mouse is // not over the image isMouseOverImage = false; // We remove the event we previously // added because we are no longer // over the image, the scroll will // now scroll the window window.removeEventListener( \"scroll\", noScroll); }); // The following function is called // when we move mouse wheel over // the images scrollImages.addEventListener( \"wheel\", function(e) { // We check if we are over // image or not if (isMouseOverImage) { var nextImageIndex; // The following condition // finds the next image // index depending if we // scroll up or scroll down if (e.deltaY > 0) nextImageIndex = (imageIndex + 1) % images.length; else nextImageIndex = (imageIndex - 1 + images.length) % images.length; // We set the z index of current // image to 0 images[imageIndex].style.zIndex = \"0\"; // We set the z index of next // image to 1, this makes // The new image appear on top // of old image images[nextImageIndex].style.zIndex = \"1\"; imageIndex = nextImageIndex; } }); }</script>",
"e": 4999,
"s": 1499,
"text": null
},
{
"code": null,
"e": 5074,
"s": 4999,
"text": "Final Solution: In this section we will combine the above three section. "
},
{
"code": null,
"e": 5085,
"s": 5074,
"text": "JavaScript"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <title> Change image dynamically when user scrolls </title> <style> body { text-align: center; } h1 { color: green; } img { position: absolute; left: 300px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <div id=\"scroll-image\"> <img src=\"CSS.png\" class=\"test\" /> <img src=\"html.png\" class=\"test\" /> <img src=\"php.png\" class=\"test\" /> </div> <script> window.onload = function() { // Index of current image // which is on display var imageIndex = 0; // Object array of all the // images of class test var images = document.getElementsByClassName('test'); // This tells us if mouse if over // image or not, We only change // image if mouse if over it var isMouseOverImage = false; // Object of parent element // containing all images var scrollImages = document.getElementById('scroll-image'); // Stores the current scroll co-ordinates // so that the window don't scroll down // while scrolling the images var x, y; // This function sets the scroll to x, y function noScroll() { window.scrollTo(x, y); } // The following event id fired once when // We hover mouse over the images scrollImages.addEventListener( \"mouseenter\", function() { // We store the current page // offset to x,y x = window.pageXOffset; y = window.pageYOffset; // We add the following event to // window object, so if we scroll // down after mouse is over the // image we can avoid scrolling // the window window.addEventListener(\"scroll\", noScroll); // We set isMouseOverImage to // true, this means Mouse is // now over the image isMouseOverImage = true; }); // The following function is fired // when mouse is no longer over // the images scrollImages.addEventListener( \"mouseleave\", function() { // We set isMouseOverImage to // false, this means mouse is // not over the image isMouseOverImage = false; // We remove the event we previously // added because we are no longer // over the image, the scroll will // now scroll the window window.removeEventListener( \"scroll\", noScroll); }); // The following function is called // when we move mouse wheel over // the images scrollImages.addEventListener( \"wheel\", function(e) { // We check if we are over // image or not if (isMouseOverImage) { var nextImageIndex; // The following condition // finds the next image // index depending if we // scroll up or scroll down if (e.deltaY > 0) nextImageIndex = (imageIndex + 1) % images.length; else nextImageIndex = (imageIndex - 1 + images.length) % images.length; // We set the z index of current // image to 0 images[imageIndex].style.zIndex = \"0\"; // We set the z index of next // image to 1, this makes // The new image appear on top // of old image images[nextImageIndex].style.zIndex = \"1\"; imageIndex = nextImageIndex; } }); } </script></body> </html>",
"e": 9657,
"s": 5085,
"text": null
},
{
"code": null,
"e": 9667,
"s": 9657,
"text": "Output: "
},
{
"code": null,
"e": 9740,
"s": 9667,
"text": "Note: The above code will change image only if mouse if over the image. "
},
{
"code": null,
"e": 9757,
"s": 9740,
"text": "arorakashish0911"
},
{
"code": null,
"e": 9769,
"s": 9757,
"text": "Vijay Sirra"
},
{
"code": null,
"e": 9785,
"s": 9769,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 9794,
"s": 9785,
"text": "rkbhola5"
},
{
"code": null,
"e": 9803,
"s": 9794,
"text": "CSS-Misc"
},
{
"code": null,
"e": 9813,
"s": 9803,
"text": "HTML-Misc"
},
{
"code": null,
"e": 9829,
"s": 9813,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 9833,
"s": 9829,
"text": "CSS"
},
{
"code": null,
"e": 9838,
"s": 9833,
"text": "HTML"
},
{
"code": null,
"e": 9849,
"s": 9838,
"text": "JavaScript"
},
{
"code": null,
"e": 9866,
"s": 9849,
"text": "Web Technologies"
},
{
"code": null,
"e": 9893,
"s": 9866,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 9898,
"s": 9893,
"text": "HTML"
},
{
"code": null,
"e": 9996,
"s": 9898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10035,
"s": 9996,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 10074,
"s": 10035,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 10113,
"s": 10074,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 10175,
"s": 10113,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 10204,
"s": 10175,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 10228,
"s": 10204,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 10281,
"s": 10228,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 10341,
"s": 10281,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 10402,
"s": 10341,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Program to check if two given matrices are identical | 23 Jun, 2022
The below program checks if two square matrices of size 4*4 are identical or not. For any two matrices to be equal, a number of rows and columns in both the matrix should be equal and the corresponding elements should also be equal.
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to check if two// given matrices are identical#include <bits/stdc++.h>#define N 4using namespace std; // This function returns 1 if A[][] and B[][] are identical// otherwise returns 0int areSame(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i][j] != B[i][j]) return 0; return 1;} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; if (areSame(A, B)) cout << "Matrices are identical"; else cout << "Matrices are not identical"; return 0;}//This code is contributed by Shivi_Aggarwal
// C Program to check if two// given matrices are identical#include <stdio.h>#define N 4 // This function returns 1 if A[][] and B[][] are identical// otherwise returns 0int areSame(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i][j] != B[i][j]) return 0; return 1;} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; if (areSame(A, B)) printf("Matrices are identical"); else printf("Matrices are not identical"); return 0;}
// Java Program to check if two// given matrices are identical class GFG{ static final int N = 4; // This function returns 1 if A[][] // and B[][] are identical // otherwise returns 0 static int areSame(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i][j] != B[i][j]) return 0; return 1; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; if (areSame(A, B) == 1) System.out.print("Matrices are identical"); else System.out.print("Matrices are not identical"); }} // This code is contributed by Anant Agarwal.
# Python3 Program to check if two# given matrices are identical N = 4 # This function returns 1# if A[][] and B[][] are identical# otherwise returns 0def areSame(A,B): for i in range(N): for j in range(N): if (A[i][j] != B[i][j]): return 0 return 1 # driver codeA= [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B= [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] if (areSame(A, B)==1): print("Matrices are identical")else: print("Matrices are not identical") # This code is contributed# by Anant Agarwal.
// C# Program to check if two// given matrices are identicalusing System; class GFG { static int N = 4; // This function returns 1 if A[][] // and B[][] are identical // otherwise returns 0 static int areSame(int [,]A, int [,]B) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i,j] != B[i,j]) return 0; return 1; } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int [,]B = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; if (areSame(A, B) == 1) Console.WriteLine("Matrices " + "are identical"); else Console.WriteLine("Matrices " + "are not identical"); }} // This code is contributed by anuj_67.
<?php// PHP Program to check if two// given matrices are identical // function returns 1 if A[][]// and B[][] are identical// otherwise returns 0function areSame($A, $B){ for($i = 0; $i < 4; $i++) for ($j = 0; $j < 4; $j++) if ($A[$i][$j] != $B[$i][$j]) return 0; return 1;} // Driver Code$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $B = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); if (areSame($A, $B) == 1) echo "Matrices are identical"; else echo "Matrices are not identical"; // This code is contributed by Anuj_67?>
<script> // Javascript Program to check if two// given matrices are identical const N = 4; // This function returns 1 if A[][]// and B[][] are identical// otherwise returns 0function areSame(A, B){ let i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i][j] != B[i][j]) return 0; return 1;} let A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]; let B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]; if (areSame(A, B)) document.write("Matrices are identical"); else document.write("Matrices are not identical"); </script>
Matrices are identical
The program can be extended for rectangular matrices. The following post can be useful for extending this program. How to pass a 2D array as a parameter in C?
Time complexity: O(n2).Auxiliary space: O(1).
vt_m
Shivi_Aggarwal
subhammahato348
rishavmahato348
hardikkoriintern
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unique paths in a Grid with Obstacles
Find the longest path in a matrix with given constraints
Find median in row wise sorted matrix
Zigzag (or diagonal) traversal of Matrix
A Boolean Matrix Question
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 287,
"s": 53,
"text": "The below program checks if two square matrices of size 4*4 are identical or not. For any two matrices to be equal, a number of rows and columns in both the matrix should be equal and the corresponding elements should also be equal. "
},
{
"code": null,
"e": 303,
"s": 287,
"text": "Implementation:"
},
{
"code": null,
"e": 307,
"s": 303,
"text": "C++"
},
{
"code": null,
"e": 309,
"s": 307,
"text": "C"
},
{
"code": null,
"e": 314,
"s": 309,
"text": "Java"
},
{
"code": null,
"e": 322,
"s": 314,
"text": "Python3"
},
{
"code": null,
"e": 325,
"s": 322,
"text": "C#"
},
{
"code": null,
"e": 329,
"s": 325,
"text": "PHP"
},
{
"code": null,
"e": 340,
"s": 329,
"text": "Javascript"
},
{
"code": "// C++ Program to check if two// given matrices are identical#include <bits/stdc++.h>#define N 4using namespace std; // This function returns 1 if A[][] and B[][] are identical// otherwise returns 0int areSame(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i][j] != B[i][j]) return 0; return 1;} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; if (areSame(A, B)) cout << \"Matrices are identical\"; else cout << \"Matrices are not identical\"; return 0;}//This code is contributed by Shivi_Aggarwal",
"e": 1174,
"s": 340,
"text": null
},
{
"code": "// C Program to check if two// given matrices are identical#include <stdio.h>#define N 4 // This function returns 1 if A[][] and B[][] are identical// otherwise returns 0int areSame(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i][j] != B[i][j]) return 0; return 1;} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; if (areSame(A, B)) printf(\"Matrices are identical\"); else printf(\"Matrices are not identical\"); return 0;}",
"e": 1936,
"s": 1174,
"text": null
},
{
"code": "// Java Program to check if two// given matrices are identical class GFG{ static final int N = 4; // This function returns 1 if A[][] // and B[][] are identical // otherwise returns 0 static int areSame(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i][j] != B[i][j]) return 0; return 1; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; if (areSame(A, B) == 1) System.out.print(\"Matrices are identical\"); else System.out.print(\"Matrices are not identical\"); }} // This code is contributed by Anant Agarwal.",
"e": 2935,
"s": 1936,
"text": null
},
{
"code": "# Python3 Program to check if two# given matrices are identical N = 4 # This function returns 1# if A[][] and B[][] are identical# otherwise returns 0def areSame(A,B): for i in range(N): for j in range(N): if (A[i][j] != B[i][j]): return 0 return 1 # driver codeA= [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B= [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] if (areSame(A, B)==1): print(\"Matrices are identical\")else: print(\"Matrices are not identical\") # This code is contributed# by Anant Agarwal.",
"e": 3551,
"s": 2935,
"text": null
},
{
"code": "// C# Program to check if two// given matrices are identicalusing System; class GFG { static int N = 4; // This function returns 1 if A[][] // and B[][] are identical // otherwise returns 0 static int areSame(int [,]A, int [,]B) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i,j] != B[i,j]) return 0; return 1; } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int [,]B = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; if (areSame(A, B) == 1) Console.WriteLine(\"Matrices \" + \"are identical\"); else Console.WriteLine(\"Matrices \" + \"are not identical\"); }} // This code is contributed by anuj_67.",
"e": 4575,
"s": 3551,
"text": null
},
{
"code": "<?php// PHP Program to check if two// given matrices are identical // function returns 1 if A[][]// and B[][] are identical// otherwise returns 0function areSame($A, $B){ for($i = 0; $i < 4; $i++) for ($j = 0; $j < 4; $j++) if ($A[$i][$j] != $B[$i][$j]) return 0; return 1;} // Driver Code$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $B = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); if (areSame($A, $B) == 1) echo \"Matrices are identical\"; else echo \"Matrices are not identical\"; // This code is contributed by Anuj_67?>",
"e": 5307,
"s": 4575,
"text": null
},
{
"code": "<script> // Javascript Program to check if two// given matrices are identical const N = 4; // This function returns 1 if A[][]// and B[][] are identical// otherwise returns 0function areSame(A, B){ let i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (A[i][j] != B[i][j]) return 0; return 1;} let A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]; let B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]; if (areSame(A, B)) document.write(\"Matrices are identical\"); else document.write(\"Matrices are not identical\"); </script>",
"e": 6014,
"s": 5307,
"text": null
},
{
"code": null,
"e": 6037,
"s": 6014,
"text": "Matrices are identical"
},
{
"code": null,
"e": 6196,
"s": 6037,
"text": "The program can be extended for rectangular matrices. The following post can be useful for extending this program. How to pass a 2D array as a parameter in C?"
},
{
"code": null,
"e": 6242,
"s": 6196,
"text": "Time complexity: O(n2).Auxiliary space: O(1)."
},
{
"code": null,
"e": 6247,
"s": 6242,
"text": "vt_m"
},
{
"code": null,
"e": 6262,
"s": 6247,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 6278,
"s": 6262,
"text": "subhammahato348"
},
{
"code": null,
"e": 6294,
"s": 6278,
"text": "rishavmahato348"
},
{
"code": null,
"e": 6311,
"s": 6294,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 6318,
"s": 6311,
"text": "Matrix"
},
{
"code": null,
"e": 6337,
"s": 6318,
"text": "School Programming"
},
{
"code": null,
"e": 6344,
"s": 6337,
"text": "Matrix"
},
{
"code": null,
"e": 6442,
"s": 6344,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6480,
"s": 6442,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 6537,
"s": 6480,
"text": "Find the longest path in a matrix with given constraints"
},
{
"code": null,
"e": 6575,
"s": 6537,
"text": "Find median in row wise sorted matrix"
},
{
"code": null,
"e": 6616,
"s": 6575,
"text": "Zigzag (or diagonal) traversal of Matrix"
},
{
"code": null,
"e": 6642,
"s": 6616,
"text": "A Boolean Matrix Question"
},
{
"code": null,
"e": 6660,
"s": 6642,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6685,
"s": 6660,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6701,
"s": 6685,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 6724,
"s": 6701,
"text": "Introduction To PYTHON"
}
] |
Largest subarray with equal number of 0s and 1s | 21 Feb, 2022
Given an array containing only 0s and 1s, find the largest subarray which contains equal no of 0s and 1s. The expected time complexity is O(n).
Examples:
Input: arr[] = {1, 0, 1, 1, 1, 0, 0}
Output: 1 to 6
(Starting and Ending indexes of output subarray)
Input: arr[] = {1, 1, 1, 1}
Output: No such subarray
Input: arr[] = {0, 0, 1, 1, 0}
Output: 0 to 3 Or 1 to 4
Method 1: Brute Force.
Approach: The brute force approach in these type of questions is to generate all the possible sub-arrays. Then firstly check whether the sub-array has equal number of 0’s and 1’s or not. To make this process easy take cumulative sum of the sub-arrays taking 0’s as -1 and 1’s as it is. The point where cumulative sum = 0 will signify that the sub-array from starting till that point has equal number of 0’s and 1’s. Now as this is a valid sub-array, compare it’s size with the maximum size of such sub-array found till now.
Algorithm :
Use a starting a pointer which signifies the starting point of the sub-array.Take a variable sum=0 which will take the cumulative sum of all the sub-array elements.Initialize it with value 1 if the value at starting point=1 else initialize it with -1.Now start an inner loop and start taking the cumulative sum of elements following the same logic.If the cumulative sum (value of sum)=0 it signifies that the sub-array has equal number of 0’s and 1’s.Now compare its size with the size of the largest sub-array if it is greater store the first index of such sub-array in a variable and update the value of size.Print the sub-array with the starting index and size returned by the above algorithm.
Use a starting a pointer which signifies the starting point of the sub-array.
Take a variable sum=0 which will take the cumulative sum of all the sub-array elements.
Initialize it with value 1 if the value at starting point=1 else initialize it with -1.
Now start an inner loop and start taking the cumulative sum of elements following the same logic.
If the cumulative sum (value of sum)=0 it signifies that the sub-array has equal number of 0’s and 1’s.
Now compare its size with the size of the largest sub-array if it is greater store the first index of such sub-array in a variable and update the value of size.
Print the sub-array with the starting index and size returned by the above algorithm.
Pseudo Code:
Run a loop from i=0 to n-2
if(arr[i]==1)
sum=1
else
sum=-1
Run inner loop from j=i+1 to n-1
sum+=arr[j]
if(sum==0)
if(j-i+1>max_size)
start_index=i
max_size=j-i+1
Run a loop from i=start_index till max_size-1
print(arr[i])
C++
C
Java
Python3
C#
PHP
Javascript
// A simple C++ program to find the largest// subarray with equal number of 0s and 1s#include <bits/stdc++.h> using namespace std; // This function Prints the starting and ending// indexes of the largest subarray with equal// number of 0s and 1s. Also returns the size// of such subarray. int findSubArray(int arr[], int n){ int sum = 0; int maxsize = -1, startindex; // Pick a starting point as i for (int i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (int j = i + 1; j < n; j++) { (arr[j] == 0) ? (sum += -1) : (sum += 1); // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } if (maxsize == -1) cout << "No such subarray"; else cout << startindex << " to " << startindex + maxsize - 1; return maxsize;} /* Driver code*/int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int size = sizeof(arr) / sizeof(arr[0]); findSubArray(arr, size); return 0;} // This code is contributed by rathbhupendra
// A simple program to find the largest subarray// with equal number of 0s and 1s #include <stdio.h> // This function Prints the starting and ending// indexes of the largest subarray with equal// number of 0s and 1s. Also returns the size// of such subarray. int findSubArray(int arr[], int n){ int sum = 0; int maxsize = -1, startindex; // Pick a starting point as i for (int i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (int j = i + 1; j < n; j++) { (arr[j] == 0) ? (sum += -1) : (sum += 1); // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } if (maxsize == -1) printf("No such subarray"); else printf("%d to %d", startindex, startindex + maxsize - 1); return maxsize;} /* Driver program to test above functions*/ int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int size = sizeof(arr) / sizeof(arr[0]); findSubArray(arr, size); return 0;}
class LargestSubArray { // This function Prints the starting and ending // indexes of the largest subarray with equal // number of 0s and 1s. Also returns the size // of such subarray. int findSubArray(int arr[], int n) { int sum = 0; int maxsize = -1, startindex = 0; int endindex = 0; // Pick a starting point as i for (int i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (int j = i + 1; j < n; j++) { if (arr[j] == 0) sum += -1; else sum += 1; // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } endindex = startindex + maxsize - 1; if (maxsize == -1) System.out.println("No such subarray"); else System.out.println(startindex + " to " + endindex); return maxsize; } /* Driver program to test the above functions */ public static void main(String[] args) { LargestSubArray sub; sub = new LargestSubArray(); int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int size = arr.length; sub.findSubArray(arr, size); }}
# A simple program to find the largest subarray# with equal number of 0s and 1s # This function Prints the starting and ending# indexes of the largest subarray with equal# number of 0s and 1s. Also returns the size# of such subarray.def findSubArray(arr, n): sum = 0 maxsize = -1 # Pick a starting point as i for i in range(0, n-1): sum = -1 if(arr[i] == 0) else 1 # Consider all subarrays starting from i for j in range(i + 1, n): sum = sum + (-1) if (arr[j] == 0) else sum + 1 # If this is a 0 sum subarray, then # compare it with maximum size subarray # calculated so far if (sum == 0 and maxsize < j-i + 1): maxsize = j - i + 1 startindex = i if (maxsize == -1): print("No such subarray"); else: print(startindex, "to", startindex + maxsize-1); return maxsize # Driver program to test above functionsarr = [1, 0, 0, 1, 0, 1, 1]size = len(arr)findSubArray(arr, size) # This code is contributed by Smitha Dinesh Semwal
// A simple program to find the largest subarray// with equal number of 0s and 1susing System; class GFG { // This function Prints the starting and ending // indexes of the largest subarray with equal // number of 0s and 1s. Also returns the size // of such subarray. static int findSubArray(int[] arr, int n) { int sum = 0; int maxsize = -1, startindex = 0; int endindex = 0; // Pick a starting point as i for (int i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (int j = i + 1; j < n; j++) { if (arr[j] == 0) sum += -1; else sum += 1; // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } endindex = startindex + maxsize - 1; if (maxsize == -1) Console.WriteLine("No such subarray"); else Console.WriteLine(startindex + " to " + endindex); return maxsize; } // Driver program public static void Main() { int[] arr = { 1, 0, 0, 1, 0, 1, 1 }; int size = arr.Length; findSubArray(arr, size); }} // This code is contributed by Sam007
<?php// A simple program to find the// largest subarray with equal// number of 0s and 1s // This function Prints the starting// and ending indexes of the largest// subarray with equal number of 0s// and 1s. Also returns the size of// such subarray.function findSubArray(&$arr, $n){ $sum = 0; $maxsize = -1; // Pick a starting point as i for ($i = 0; $i < $n - 1; $i++) { $sum = ($arr[$i] == 0) ? -1 : 1; // Consider all subarrays // starting from i for ($j = $i + 1; $j < $n; $j++) { ($arr[$j] == 0) ? ($sum += -1) : ($sum += 1); // If this is a 0 sum subarray, // then compare it with maximum // size subarray calculated so far if ($sum == 0 && $maxsize < $j - $i + 1) { $maxsize = $j - $i + 1; $startindex = $i; } } } if ($maxsize == -1) echo "No such subarray"; else echo $startindex. " to " . ($startindex + $maxsize - 1); return $maxsize;} // Driver Code$arr = array(1, 0, 0, 1, 0, 1, 1);$size = sizeof($arr); findSubArray($arr, $size); // This code is contributed// by ChitraNayal?>
<script> // This function Prints the starting and ending // indexes of the largest subarray with equal // number of 0s and 1s. Also returns the size // of such subarray. function findSubArray(arr,n) { let sum = 0; let maxsize = -1, startindex = 0; let endindex = 0; // Pick a starting point as i for (let i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (let j = i + 1; j < n; j++) { if (arr[j] == 0) sum += -1; else sum += 1; // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } endindex = startindex + maxsize - 1; if (maxsize == -1) document.write("No such subarray"); else document.write(startindex + " to " + endindex); return maxsize; } /* Driver program to test the above functions */ let arr=[1, 0, 0, 1, 0, 1, 1]; let size = arr.length; findSubArray(arr, size); // This code is contributed by avanitrachhadiya2155 </script>
Output:
0 to 5
Complexity Analysis:
Time Complexity: O(n^2). As all the possible sub-arrays are generated using a pair of nested loops.
Auxiliary Space: O(1). As no extra data structure is used which takes auxiliary space.
Method 2: Hashmap.
Approach: The concept of taking cumulative sum, taking 0’s as -1 will help us in optimizing the approach. While taking the cumulative sum, there are two cases when there can be a sub-array with equal number of 0’s and 1’s.
When cumulative sum=0, which signifies that sub-array from index (0) till present index has equal number of 0’s and 1’s.When we encounter a cumulative sum value which we have already encountered before, which means that sub-array from the previous index+1 till the present index has equal number of 0’s and 1’s as they give a cumulative sum of 0 .
When cumulative sum=0, which signifies that sub-array from index (0) till present index has equal number of 0’s and 1’s.
When we encounter a cumulative sum value which we have already encountered before, which means that sub-array from the previous index+1 till the present index has equal number of 0’s and 1’s as they give a cumulative sum of 0 .
In a nutshell this problem is equivalent to finding two indexes i & j in array[] such that array[i] = array[j] and (j-i) is maximum. To store the first occurrence of each unique cumulative sum value we use a hash_map wherein if we get that value again we can find the sub-array size and compare it with the maximum size found till now.
Algorithm :
Let input array be arr[] of size n and max_size be the size of output sub-array.Create a temporary array sumleft[] of size n. Store the sum of all elements from arr[0] to arr[i] in sumleft[i].There are two cases, the output sub-array may start from 0th index or may start from some other index. We will return the max of the values obtained by two cases.To find the maximum length sub-array starting from 0th index, scan the sumleft[] and find the maximum i where sumleft[i] = 0.Now, we need to find the subarray where subarray sum is 0 and start index is not 0. This problem is equivalent to finding two indexes i & j in sumleft[] such that sumleft[i] = sumleft[j] and j-i is maximum. To solve this, we create a hash table with size = max-min+1 where min is the minimum value in the sumleft[] and max is the maximum value in the sumleft[]. Hash the leftmost occurrences of all different values in sumleft[]. The size of hash is chosen as max-min+1 because there can be these many different possible values in sumleft[]. Initialize all values in hash as -1.To fill and use hash[], traverse sumleft[] from 0 to n-1. If a value is not present in hash[], then store its index in hash. If the value is present, then calculate the difference of current index of sumleft[] and previously stored value in hash[]. If this difference is more than maxsize, then update the maxsize.To handle corner cases (all 1s and all 0s), we initialize maxsize as -1. If the maxsize remains -1, then print there is no such subarray.
Let input array be arr[] of size n and max_size be the size of output sub-array.
Create a temporary array sumleft[] of size n. Store the sum of all elements from arr[0] to arr[i] in sumleft[i].
There are two cases, the output sub-array may start from 0th index or may start from some other index. We will return the max of the values obtained by two cases.
To find the maximum length sub-array starting from 0th index, scan the sumleft[] and find the maximum i where sumleft[i] = 0.
Now, we need to find the subarray where subarray sum is 0 and start index is not 0. This problem is equivalent to finding two indexes i & j in sumleft[] such that sumleft[i] = sumleft[j] and j-i is maximum. To solve this, we create a hash table with size = max-min+1 where min is the minimum value in the sumleft[] and max is the maximum value in the sumleft[]. Hash the leftmost occurrences of all different values in sumleft[]. The size of hash is chosen as max-min+1 because there can be these many different possible values in sumleft[]. Initialize all values in hash as -1.
To fill and use hash[], traverse sumleft[] from 0 to n-1. If a value is not present in hash[], then store its index in hash. If the value is present, then calculate the difference of current index of sumleft[] and previously stored value in hash[]. If this difference is more than maxsize, then update the maxsize.
To handle corner cases (all 1s and all 0s), we initialize maxsize as -1. If the maxsize remains -1, then print there is no such subarray.
Pseudo Code:
int sum_left[n]
Run a loop from i=0 to n-1
if(arr[i]==0)
sumleft[i] = sumleft[i-1]+-1
else
sumleft[i] = sumleft[i-1]+ 1
if (sumleft[i] > max)
max = sumleft[i];
Run a loop from i=0 to n-1
if (sumleft[i] == 0)
{
maxsize = i+1;
startindex = 0;
}
// Case 2: fill hash table value. If already
then use it
if (hash[sumleft[i]-min] == -1)
hash[sumleft[i]-min] = i;
else
{
if ((i - hash[sumleft[i]-min]) > maxsize)
{
maxsize = i - hash[sumleft[i]-min];
startindex = hash[sumleft[i]-min] + 1;
}
}
return maxsize
C++
C
Java
Python3
C#
Javascript
// C++ program to find largest subarray with equal number of// 0's and 1's. #include <bits/stdc++.h>using namespace std; // Returns largest subarray with equal number of 0s and 1s int maxLen(int arr[], int n){ // Creates an empty hashMap hM unordered_map<int, int> hM; int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result int ending_index = -1; for (int i = 0; i < n; i++) arr[i] = (arr[i] == 0) ? -1 : 1; // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) { max_len = i + 1; ending_index = i; } // If this sum is seen before, then update max_len // if required if (hM.find(sum) != hM.end()) { if (max_len < i - hM[sum]) { max_len = i - hM[sum]; ending_index = i; } } else // Else put this sum in hash table hM[sum] = i; } for (int i = 0; i < n; i++) arr[i] = (arr[i] == -1) ? 0 : 1; printf("%d to %d\n", ending_index - max_len + 1, ending_index); return max_len;} // Driver method int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); maxLen(arr, n); return 0;} // This code is contributed by Aditya Goel
// A O(n) program to find the largest subarray// with equal number of 0s and 1s #include <stdio.h>#include <stdlib.h> // A utility function to get maximum of two// integers int max(int a, int b) { return a > b ? a : b; } // This function Prints the starting and ending// indexes of the largest subarray with equal// number of 0s and 1s. Also returns the size// of such subarray. int findSubArray(int arr[], int n){ // variables to store result values int maxsize = -1, startindex; // Create an auxiliary array sunmleft[]. // sumleft[i] will be sum of array // elements from arr[0] to arr[i] int sumleft[n]; // For min and max values in sumleft[] int min, max; int i; // Fill sumleft array and get min and max // values in it. Consider 0 values in arr[] // as -1 sumleft[0] = ((arr[0] == 0) ? -1 : 1); min = arr[0]; max = arr[0]; for (i = 1; i < n; i++) { sumleft[i] = sumleft[i - 1] + ((arr[i] == 0) ? -1 : 1); if (sumleft[i] < min) min = sumleft[i]; if (sumleft[i] > max) max = sumleft[i]; } // Now calculate the max value of j - i such // that sumleft[i] = sumleft[j]. The idea is // to create a hash table to store indexes of all // visited values. // If you see a value again, that it is a case of // sumleft[i] = sumleft[j]. Check if this j-i is // more than maxsize. // The optimum size of hash will be max-min+1 as // these many different values of sumleft[i] are // possible. Since we use optimum size, we need // to shift all values in sumleft[] by min before // using them as an index in hash[]. int hash[max - min + 1]; // Initialize hash table for (i = 0; i < max - min + 1; i++) hash[i] = -1; for (i = 0; i < n; i++) { // Case 1: when the subarray starts from // index 0 if (sumleft[i] == 0) { maxsize = i + 1; startindex = 0; } // Case 2: fill hash table value. If already // filled, then use it if (hash[sumleft[i] - min] == -1) hash[sumleft[i] - min] = i; else { if ((i - hash[sumleft[i] - min]) > maxsize) { maxsize = i - hash[sumleft[i] - min]; startindex = hash[sumleft[i] - min] + 1; } } } if (maxsize == -1) printf("No such subarray"); else printf("%d to %d", startindex, startindex + maxsize - 1); return maxsize;} /* Driver program to test above functions */int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int size = sizeof(arr) / sizeof(arr[0]); findSubArray(arr, size); return 0;}
import java.util.HashMap; class LargestSubArray1 { // Returns largest subarray with // equal number of 0s and 1s int maxLen(int arr[], int n) { // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); // Initialize sum of elements int sum = 0; // Initialize result int max_len = 0; int ending_index = -1; int start_index = 0; for (int i = 0; i < n; i++) { arr[i] = (arr[i] == 0) ? -1 : 1; } // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) { max_len = i + 1; ending_index = i; } // If this sum is seen before, // then update max_len if required if (hM.containsKey(sum)) { if (max_len < i - hM.get(sum)) { max_len = i - hM.get(sum); ending_index = i; } } else // Else put this sum in hash table hM.put(sum, i); } for (int i = 0; i < n; i++) { arr[i] = (arr[i] == -1) ? 0 : 1; } int end = ending_index - max_len + 1; System.out.println(end + " to " + ending_index); return max_len; } /* Driver program to test the above functions */ public static void main(String[] args) { LargestSubArray1 sub = new LargestSubArray1(); int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.length; sub.maxLen(arr, n); }} // This code has been by Mayank Jaiswal(mayank_24)
# Python 3 program to find largest# subarray with equal number of# 0's and 1's. # Returns largest subarray with# equal number of 0s and 1sdef maxLen(arr, n): # NOTE: Dictionary in python in # implemented as Hash Maps. # Create an empty hash map (dictionary) hash_map = {} curr_sum = 0 max_len = 0 ending_index = -1 for i in range (0, n): if(arr[i] == 0): arr[i] = -1 else: arr[i] = 1 # Traverse through the given array for i in range (0, n): # Add current element to sum curr_sum = curr_sum + arr[i] # To handle sum = 0 at last index if (curr_sum == 0): max_len = i + 1 ending_index = i # If this sum is seen before, if curr_sum in hash_map: # If max_len is smaller than new subarray # Update max_len and ending_index if max_len < i - hash_map[curr_sum]: max_len = i - hash_map[curr_sum] ending_index = i else: # else put this sum in dictionary hash_map[curr_sum] = i for i in range (0, n): if(arr[i] == -1): arr[i] = 0 else: arr[i] = 1 print (ending_index - max_len + 1, end =" ") print ("to", end = " ") print (ending_index) return max_len # Driver Codearr = [1, 0, 0, 1, 0, 1, 1]n = len(arr) maxLen(arr, n) # This code is contributed# by Tarun Garg
// C# program to find the largest subarray// with equal number of 0s and 1susing System;using System.Collections.Generic; class LargestSubArray1 { // Returns largest subarray with // equal number of 0s and 1s public virtual int maxLen(int[] arr, int n) { // Creates an empty Dictionary hM Dictionary<int, int> hM = new Dictionary<int, int>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result int ending_index = -1; int start_index = 0; for (int i = 0; i < n; i++) { arr[i] = (arr[i] == 0) ? -1 : 1; } // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) { max_len = i + 1; ending_index = i; } // If this sum is seen before, // then update max_len // if required if (hM.ContainsKey(sum)) { if (max_len < i - hM[sum]) { max_len = i - hM[sum]; ending_index = i; } } else // Else put this sum in hash table { hM[sum] = i; } } for (int i = 0; i < n; i++) { arr[i] = (arr[i] == -1) ? 0 : 1; } int end = ending_index - max_len + 1; Console.WriteLine(end + " to " + ending_index); return max_len; } // Driver Code public static void Main(string[] args) { LargestSubArray1 sub = new LargestSubArray1(); int[] arr = new int[] { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.Length; sub.maxLen(arr, n); }} // This code is contributed by Shrikant13
<script> // Javascript program to find largest// subarray with equal number of// 0's and 1's. // Returns largest subarray with equal// number of 0s and 1sfunction maxLen(arr, n){ // Creates an empty hashMap hM let hM = new Map(); // Initialize sum of elements let sum = 0; // Initialize result let max_len = 0; let ending_index = -1; for(let i = 0; i < n; i++) arr[i] = (arr[i] == 0) ? -1 : 1; // Traverse through the given array for(let i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) { max_len = i + 1; ending_index = i; } // If this sum is seen before, then // update max_len if required if (hM.has(sum)) { if (max_len < i - hM[sum]) { max_len = i - hM[sum]; ending_index = i; } } // Else put this sum in hash table else hM[sum] = i; } for(let i = 0; i < n; i++) arr[i] = (arr[i] == -1) ? 0 : 1; document.write(ending_index - max_len + 1 + " to " + ending_index); return max_len;} // Driver codelet arr = [ 1, 0, 0, 1, 0, 1, 1 ];let n = arr.length; maxLen(arr, n); // This code is contributed by gfgking </script>
Output:
0 to 5
Complexity Analysis:
Time Complexity: O(n). As the given array is traversed only once.
Auxiliary Space: O(n). As hash_map has been used which takes extra space.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Vijay Akkaladevi
ukasp
shrikanth13
Shivi_Aggarwal
rathbhupendra
tarun2207
bidibaaz123
ninjapro
khushboogoyal499
rahulsharma9
avanitrachhadiya2155
gfgking
manav23lohani
surindertarika1234
surinderdawra388
Amazon
MakeMyTrip
Morgan Stanley
Paytm
prefix-sum
Arrays
Hash
Paytm
Morgan Stanley
Amazon
MakeMyTrip
prefix-sum
Arrays
Hash
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
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
What is Hashing | A Complete Tutorial
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Hashing | Set 1 (Introduction)
Internal Working of HashMap in Java
Longest Consecutive Subsequence | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 197,
"s": 52,
"text": "Given an array containing only 0s and 1s, find the largest subarray which contains equal no of 0s and 1s. The expected time complexity is O(n). "
},
{
"code": null,
"e": 208,
"s": 197,
"text": "Examples: "
},
{
"code": null,
"e": 421,
"s": 208,
"text": "Input: arr[] = {1, 0, 1, 1, 1, 0, 0}\nOutput: 1 to 6 \n(Starting and Ending indexes of output subarray)\n\nInput: arr[] = {1, 1, 1, 1}\nOutput: No such subarray\n\nInput: arr[] = {0, 0, 1, 1, 0}\nOutput: 0 to 3 Or 1 to 4"
},
{
"code": null,
"e": 444,
"s": 421,
"text": "Method 1: Brute Force."
},
{
"code": null,
"e": 969,
"s": 444,
"text": "Approach: The brute force approach in these type of questions is to generate all the possible sub-arrays. Then firstly check whether the sub-array has equal number of 0’s and 1’s or not. To make this process easy take cumulative sum of the sub-arrays taking 0’s as -1 and 1’s as it is. The point where cumulative sum = 0 will signify that the sub-array from starting till that point has equal number of 0’s and 1’s. Now as this is a valid sub-array, compare it’s size with the maximum size of such sub-array found till now. "
},
{
"code": null,
"e": 982,
"s": 969,
"text": "Algorithm : "
},
{
"code": null,
"e": 1679,
"s": 982,
"text": "Use a starting a pointer which signifies the starting point of the sub-array.Take a variable sum=0 which will take the cumulative sum of all the sub-array elements.Initialize it with value 1 if the value at starting point=1 else initialize it with -1.Now start an inner loop and start taking the cumulative sum of elements following the same logic.If the cumulative sum (value of sum)=0 it signifies that the sub-array has equal number of 0’s and 1’s.Now compare its size with the size of the largest sub-array if it is greater store the first index of such sub-array in a variable and update the value of size.Print the sub-array with the starting index and size returned by the above algorithm."
},
{
"code": null,
"e": 1757,
"s": 1679,
"text": "Use a starting a pointer which signifies the starting point of the sub-array."
},
{
"code": null,
"e": 1845,
"s": 1757,
"text": "Take a variable sum=0 which will take the cumulative sum of all the sub-array elements."
},
{
"code": null,
"e": 1933,
"s": 1845,
"text": "Initialize it with value 1 if the value at starting point=1 else initialize it with -1."
},
{
"code": null,
"e": 2031,
"s": 1933,
"text": "Now start an inner loop and start taking the cumulative sum of elements following the same logic."
},
{
"code": null,
"e": 2135,
"s": 2031,
"text": "If the cumulative sum (value of sum)=0 it signifies that the sub-array has equal number of 0’s and 1’s."
},
{
"code": null,
"e": 2296,
"s": 2135,
"text": "Now compare its size with the size of the largest sub-array if it is greater store the first index of such sub-array in a variable and update the value of size."
},
{
"code": null,
"e": 2382,
"s": 2296,
"text": "Print the sub-array with the starting index and size returned by the above algorithm."
},
{
"code": null,
"e": 2396,
"s": 2382,
"text": "Pseudo Code: "
},
{
"code": null,
"e": 2671,
"s": 2396,
"text": "Run a loop from i=0 to n-2\n if(arr[i]==1)\n sum=1\n else\n sum=-1\n Run inner loop from j=i+1 to n-1\n sum+=arr[j]\n if(sum==0)\n if(j-i+1>max_size)\n start_index=i\n max_size=j-i+1\nRun a loop from i=start_index till max_size-1\nprint(arr[i])"
},
{
"code": null,
"e": 2675,
"s": 2671,
"text": "C++"
},
{
"code": null,
"e": 2677,
"s": 2675,
"text": "C"
},
{
"code": null,
"e": 2682,
"s": 2677,
"text": "Java"
},
{
"code": null,
"e": 2690,
"s": 2682,
"text": "Python3"
},
{
"code": null,
"e": 2693,
"s": 2690,
"text": "C#"
},
{
"code": null,
"e": 2697,
"s": 2693,
"text": "PHP"
},
{
"code": null,
"e": 2708,
"s": 2697,
"text": "Javascript"
},
{
"code": "// A simple C++ program to find the largest// subarray with equal number of 0s and 1s#include <bits/stdc++.h> using namespace std; // This function Prints the starting and ending// indexes of the largest subarray with equal// number of 0s and 1s. Also returns the size// of such subarray. int findSubArray(int arr[], int n){ int sum = 0; int maxsize = -1, startindex; // Pick a starting point as i for (int i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (int j = i + 1; j < n; j++) { (arr[j] == 0) ? (sum += -1) : (sum += 1); // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } if (maxsize == -1) cout << \"No such subarray\"; else cout << startindex << \" to \" << startindex + maxsize - 1; return maxsize;} /* Driver code*/int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int size = sizeof(arr) / sizeof(arr[0]); findSubArray(arr, size); return 0;} // This code is contributed by rathbhupendra",
"e": 3974,
"s": 2708,
"text": null
},
{
"code": "// A simple program to find the largest subarray// with equal number of 0s and 1s #include <stdio.h> // This function Prints the starting and ending// indexes of the largest subarray with equal// number of 0s and 1s. Also returns the size// of such subarray. int findSubArray(int arr[], int n){ int sum = 0; int maxsize = -1, startindex; // Pick a starting point as i for (int i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (int j = i + 1; j < n; j++) { (arr[j] == 0) ? (sum += -1) : (sum += 1); // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } if (maxsize == -1) printf(\"No such subarray\"); else printf(\"%d to %d\", startindex, startindex + maxsize - 1); return maxsize;} /* Driver program to test above functions*/ int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int size = sizeof(arr) / sizeof(arr[0]); findSubArray(arr, size); return 0;}",
"e": 5184,
"s": 3974,
"text": null
},
{
"code": "class LargestSubArray { // This function Prints the starting and ending // indexes of the largest subarray with equal // number of 0s and 1s. Also returns the size // of such subarray. int findSubArray(int arr[], int n) { int sum = 0; int maxsize = -1, startindex = 0; int endindex = 0; // Pick a starting point as i for (int i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (int j = i + 1; j < n; j++) { if (arr[j] == 0) sum += -1; else sum += 1; // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } endindex = startindex + maxsize - 1; if (maxsize == -1) System.out.println(\"No such subarray\"); else System.out.println(startindex + \" to \" + endindex); return maxsize; } /* Driver program to test the above functions */ public static void main(String[] args) { LargestSubArray sub; sub = new LargestSubArray(); int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int size = arr.length; sub.findSubArray(arr, size); }}",
"e": 6665,
"s": 5184,
"text": null
},
{
"code": "# A simple program to find the largest subarray# with equal number of 0s and 1s # This function Prints the starting and ending# indexes of the largest subarray with equal# number of 0s and 1s. Also returns the size# of such subarray.def findSubArray(arr, n): sum = 0 maxsize = -1 # Pick a starting point as i for i in range(0, n-1): sum = -1 if(arr[i] == 0) else 1 # Consider all subarrays starting from i for j in range(i + 1, n): sum = sum + (-1) if (arr[j] == 0) else sum + 1 # If this is a 0 sum subarray, then # compare it with maximum size subarray # calculated so far if (sum == 0 and maxsize < j-i + 1): maxsize = j - i + 1 startindex = i if (maxsize == -1): print(\"No such subarray\"); else: print(startindex, \"to\", startindex + maxsize-1); return maxsize # Driver program to test above functionsarr = [1, 0, 0, 1, 0, 1, 1]size = len(arr)findSubArray(arr, size) # This code is contributed by Smitha Dinesh Semwal",
"e": 7793,
"s": 6665,
"text": null
},
{
"code": "// A simple program to find the largest subarray// with equal number of 0s and 1susing System; class GFG { // This function Prints the starting and ending // indexes of the largest subarray with equal // number of 0s and 1s. Also returns the size // of such subarray. static int findSubArray(int[] arr, int n) { int sum = 0; int maxsize = -1, startindex = 0; int endindex = 0; // Pick a starting point as i for (int i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (int j = i + 1; j < n; j++) { if (arr[j] == 0) sum += -1; else sum += 1; // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } endindex = startindex + maxsize - 1; if (maxsize == -1) Console.WriteLine(\"No such subarray\"); else Console.WriteLine(startindex + \" to \" + endindex); return maxsize; } // Driver program public static void Main() { int[] arr = { 1, 0, 0, 1, 0, 1, 1 }; int size = arr.Length; findSubArray(arr, size); }} // This code is contributed by Sam007",
"e": 9286,
"s": 7793,
"text": null
},
{
"code": "<?php// A simple program to find the// largest subarray with equal// number of 0s and 1s // This function Prints the starting// and ending indexes of the largest// subarray with equal number of 0s// and 1s. Also returns the size of// such subarray.function findSubArray(&$arr, $n){ $sum = 0; $maxsize = -1; // Pick a starting point as i for ($i = 0; $i < $n - 1; $i++) { $sum = ($arr[$i] == 0) ? -1 : 1; // Consider all subarrays // starting from i for ($j = $i + 1; $j < $n; $j++) { ($arr[$j] == 0) ? ($sum += -1) : ($sum += 1); // If this is a 0 sum subarray, // then compare it with maximum // size subarray calculated so far if ($sum == 0 && $maxsize < $j - $i + 1) { $maxsize = $j - $i + 1; $startindex = $i; } } } if ($maxsize == -1) echo \"No such subarray\"; else echo $startindex. \" to \" . ($startindex + $maxsize - 1); return $maxsize;} // Driver Code$arr = array(1, 0, 0, 1, 0, 1, 1);$size = sizeof($arr); findSubArray($arr, $size); // This code is contributed// by ChitraNayal?>",
"e": 10496,
"s": 9286,
"text": null
},
{
"code": "<script> // This function Prints the starting and ending // indexes of the largest subarray with equal // number of 0s and 1s. Also returns the size // of such subarray. function findSubArray(arr,n) { let sum = 0; let maxsize = -1, startindex = 0; let endindex = 0; // Pick a starting point as i for (let i = 0; i < n - 1; i++) { sum = (arr[i] == 0) ? -1 : 1; // Consider all subarrays starting from i for (let j = i + 1; j < n; j++) { if (arr[j] == 0) sum += -1; else sum += 1; // If this is a 0 sum subarray, then // compare it with maximum size subarray // calculated so far if (sum == 0 && maxsize < j - i + 1) { maxsize = j - i + 1; startindex = i; } } } endindex = startindex + maxsize - 1; if (maxsize == -1) document.write(\"No such subarray\"); else document.write(startindex + \" to \" + endindex); return maxsize; } /* Driver program to test the above functions */ let arr=[1, 0, 0, 1, 0, 1, 1]; let size = arr.length; findSubArray(arr, size); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 11920,
"s": 10496,
"text": null
},
{
"code": null,
"e": 11929,
"s": 11920,
"text": "Output: "
},
{
"code": null,
"e": 11937,
"s": 11929,
"text": " 0 to 5"
},
{
"code": null,
"e": 11959,
"s": 11937,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 12059,
"s": 11959,
"text": "Time Complexity: O(n^2). As all the possible sub-arrays are generated using a pair of nested loops."
},
{
"code": null,
"e": 12146,
"s": 12059,
"text": "Auxiliary Space: O(1). As no extra data structure is used which takes auxiliary space."
},
{
"code": null,
"e": 12165,
"s": 12146,
"text": "Method 2: Hashmap."
},
{
"code": null,
"e": 12389,
"s": 12165,
"text": "Approach: The concept of taking cumulative sum, taking 0’s as -1 will help us in optimizing the approach. While taking the cumulative sum, there are two cases when there can be a sub-array with equal number of 0’s and 1’s. "
},
{
"code": null,
"e": 12737,
"s": 12389,
"text": "When cumulative sum=0, which signifies that sub-array from index (0) till present index has equal number of 0’s and 1’s.When we encounter a cumulative sum value which we have already encountered before, which means that sub-array from the previous index+1 till the present index has equal number of 0’s and 1’s as they give a cumulative sum of 0 ."
},
{
"code": null,
"e": 12858,
"s": 12737,
"text": "When cumulative sum=0, which signifies that sub-array from index (0) till present index has equal number of 0’s and 1’s."
},
{
"code": null,
"e": 13086,
"s": 12858,
"text": "When we encounter a cumulative sum value which we have already encountered before, which means that sub-array from the previous index+1 till the present index has equal number of 0’s and 1’s as they give a cumulative sum of 0 ."
},
{
"code": null,
"e": 13422,
"s": 13086,
"text": "In a nutshell this problem is equivalent to finding two indexes i & j in array[] such that array[i] = array[j] and (j-i) is maximum. To store the first occurrence of each unique cumulative sum value we use a hash_map wherein if we get that value again we can find the sub-array size and compare it with the maximum size found till now."
},
{
"code": null,
"e": 13436,
"s": 13422,
"text": "Algorithm : "
},
{
"code": null,
"e": 14945,
"s": 13436,
"text": "Let input array be arr[] of size n and max_size be the size of output sub-array.Create a temporary array sumleft[] of size n. Store the sum of all elements from arr[0] to arr[i] in sumleft[i].There are two cases, the output sub-array may start from 0th index or may start from some other index. We will return the max of the values obtained by two cases.To find the maximum length sub-array starting from 0th index, scan the sumleft[] and find the maximum i where sumleft[i] = 0.Now, we need to find the subarray where subarray sum is 0 and start index is not 0. This problem is equivalent to finding two indexes i & j in sumleft[] such that sumleft[i] = sumleft[j] and j-i is maximum. To solve this, we create a hash table with size = max-min+1 where min is the minimum value in the sumleft[] and max is the maximum value in the sumleft[]. Hash the leftmost occurrences of all different values in sumleft[]. The size of hash is chosen as max-min+1 because there can be these many different possible values in sumleft[]. Initialize all values in hash as -1.To fill and use hash[], traverse sumleft[] from 0 to n-1. If a value is not present in hash[], then store its index in hash. If the value is present, then calculate the difference of current index of sumleft[] and previously stored value in hash[]. If this difference is more than maxsize, then update the maxsize.To handle corner cases (all 1s and all 0s), we initialize maxsize as -1. If the maxsize remains -1, then print there is no such subarray."
},
{
"code": null,
"e": 15026,
"s": 14945,
"text": "Let input array be arr[] of size n and max_size be the size of output sub-array."
},
{
"code": null,
"e": 15139,
"s": 15026,
"text": "Create a temporary array sumleft[] of size n. Store the sum of all elements from arr[0] to arr[i] in sumleft[i]."
},
{
"code": null,
"e": 15302,
"s": 15139,
"text": "There are two cases, the output sub-array may start from 0th index or may start from some other index. We will return the max of the values obtained by two cases."
},
{
"code": null,
"e": 15428,
"s": 15302,
"text": "To find the maximum length sub-array starting from 0th index, scan the sumleft[] and find the maximum i where sumleft[i] = 0."
},
{
"code": null,
"e": 16007,
"s": 15428,
"text": "Now, we need to find the subarray where subarray sum is 0 and start index is not 0. This problem is equivalent to finding two indexes i & j in sumleft[] such that sumleft[i] = sumleft[j] and j-i is maximum. To solve this, we create a hash table with size = max-min+1 where min is the minimum value in the sumleft[] and max is the maximum value in the sumleft[]. Hash the leftmost occurrences of all different values in sumleft[]. The size of hash is chosen as max-min+1 because there can be these many different possible values in sumleft[]. Initialize all values in hash as -1."
},
{
"code": null,
"e": 16322,
"s": 16007,
"text": "To fill and use hash[], traverse sumleft[] from 0 to n-1. If a value is not present in hash[], then store its index in hash. If the value is present, then calculate the difference of current index of sumleft[] and previously stored value in hash[]. If this difference is more than maxsize, then update the maxsize."
},
{
"code": null,
"e": 16460,
"s": 16322,
"text": "To handle corner cases (all 1s and all 0s), we initialize maxsize as -1. If the maxsize remains -1, then print there is no such subarray."
},
{
"code": null,
"e": 16474,
"s": 16460,
"text": "Pseudo Code: "
},
{
"code": null,
"e": 17178,
"s": 16474,
"text": "int sum_left[n]\nRun a loop from i=0 to n-1\n if(arr[i]==0)\n sumleft[i] = sumleft[i-1]+-1\n else\n sumleft[i] = sumleft[i-1]+ 1\n if (sumleft[i] > max)\n max = sumleft[i];\n\n\nRun a loop from i=0 to n-1\n if (sumleft[i] == 0)\n {\n maxsize = i+1;\n startindex = 0;\n }\n \n // Case 2: fill hash table value. If already\n then use it\n\n if (hash[sumleft[i]-min] == -1)\n hash[sumleft[i]-min] = i;\n else\n {\n if ((i - hash[sumleft[i]-min]) > maxsize)\n {\n maxsize = i - hash[sumleft[i]-min];\n startindex = hash[sumleft[i]-min] + 1;\n }\n }\n\nreturn maxsize"
},
{
"code": null,
"e": 17182,
"s": 17178,
"text": "C++"
},
{
"code": null,
"e": 17184,
"s": 17182,
"text": "C"
},
{
"code": null,
"e": 17189,
"s": 17184,
"text": "Java"
},
{
"code": null,
"e": 17197,
"s": 17189,
"text": "Python3"
},
{
"code": null,
"e": 17200,
"s": 17197,
"text": "C#"
},
{
"code": null,
"e": 17211,
"s": 17200,
"text": "Javascript"
},
{
"code": "// C++ program to find largest subarray with equal number of// 0's and 1's. #include <bits/stdc++.h>using namespace std; // Returns largest subarray with equal number of 0s and 1s int maxLen(int arr[], int n){ // Creates an empty hashMap hM unordered_map<int, int> hM; int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result int ending_index = -1; for (int i = 0; i < n; i++) arr[i] = (arr[i] == 0) ? -1 : 1; // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) { max_len = i + 1; ending_index = i; } // If this sum is seen before, then update max_len // if required if (hM.find(sum) != hM.end()) { if (max_len < i - hM[sum]) { max_len = i - hM[sum]; ending_index = i; } } else // Else put this sum in hash table hM[sum] = i; } for (int i = 0; i < n; i++) arr[i] = (arr[i] == -1) ? 0 : 1; printf(\"%d to %d\\n\", ending_index - max_len + 1, ending_index); return max_len;} // Driver method int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); maxLen(arr, n); return 0;} // This code is contributed by Aditya Goel",
"e": 18626,
"s": 17211,
"text": null
},
{
"code": "// A O(n) program to find the largest subarray// with equal number of 0s and 1s #include <stdio.h>#include <stdlib.h> // A utility function to get maximum of two// integers int max(int a, int b) { return a > b ? a : b; } // This function Prints the starting and ending// indexes of the largest subarray with equal// number of 0s and 1s. Also returns the size// of such subarray. int findSubArray(int arr[], int n){ // variables to store result values int maxsize = -1, startindex; // Create an auxiliary array sunmleft[]. // sumleft[i] will be sum of array // elements from arr[0] to arr[i] int sumleft[n]; // For min and max values in sumleft[] int min, max; int i; // Fill sumleft array and get min and max // values in it. Consider 0 values in arr[] // as -1 sumleft[0] = ((arr[0] == 0) ? -1 : 1); min = arr[0]; max = arr[0]; for (i = 1; i < n; i++) { sumleft[i] = sumleft[i - 1] + ((arr[i] == 0) ? -1 : 1); if (sumleft[i] < min) min = sumleft[i]; if (sumleft[i] > max) max = sumleft[i]; } // Now calculate the max value of j - i such // that sumleft[i] = sumleft[j]. The idea is // to create a hash table to store indexes of all // visited values. // If you see a value again, that it is a case of // sumleft[i] = sumleft[j]. Check if this j-i is // more than maxsize. // The optimum size of hash will be max-min+1 as // these many different values of sumleft[i] are // possible. Since we use optimum size, we need // to shift all values in sumleft[] by min before // using them as an index in hash[]. int hash[max - min + 1]; // Initialize hash table for (i = 0; i < max - min + 1; i++) hash[i] = -1; for (i = 0; i < n; i++) { // Case 1: when the subarray starts from // index 0 if (sumleft[i] == 0) { maxsize = i + 1; startindex = 0; } // Case 2: fill hash table value. If already // filled, then use it if (hash[sumleft[i] - min] == -1) hash[sumleft[i] - min] = i; else { if ((i - hash[sumleft[i] - min]) > maxsize) { maxsize = i - hash[sumleft[i] - min]; startindex = hash[sumleft[i] - min] + 1; } } } if (maxsize == -1) printf(\"No such subarray\"); else printf(\"%d to %d\", startindex, startindex + maxsize - 1); return maxsize;} /* Driver program to test above functions */int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int size = sizeof(arr) / sizeof(arr[0]); findSubArray(arr, size); return 0;}",
"e": 21320,
"s": 18626,
"text": null
},
{
"code": "import java.util.HashMap; class LargestSubArray1 { // Returns largest subarray with // equal number of 0s and 1s int maxLen(int arr[], int n) { // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); // Initialize sum of elements int sum = 0; // Initialize result int max_len = 0; int ending_index = -1; int start_index = 0; for (int i = 0; i < n; i++) { arr[i] = (arr[i] == 0) ? -1 : 1; } // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) { max_len = i + 1; ending_index = i; } // If this sum is seen before, // then update max_len if required if (hM.containsKey(sum)) { if (max_len < i - hM.get(sum)) { max_len = i - hM.get(sum); ending_index = i; } } else // Else put this sum in hash table hM.put(sum, i); } for (int i = 0; i < n; i++) { arr[i] = (arr[i] == -1) ? 0 : 1; } int end = ending_index - max_len + 1; System.out.println(end + \" to \" + ending_index); return max_len; } /* Driver program to test the above functions */ public static void main(String[] args) { LargestSubArray1 sub = new LargestSubArray1(); int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.length; sub.maxLen(arr, n); }} // This code has been by Mayank Jaiswal(mayank_24)",
"e": 23071,
"s": 21320,
"text": null
},
{
"code": "# Python 3 program to find largest# subarray with equal number of# 0's and 1's. # Returns largest subarray with# equal number of 0s and 1sdef maxLen(arr, n): # NOTE: Dictionary in python in # implemented as Hash Maps. # Create an empty hash map (dictionary) hash_map = {} curr_sum = 0 max_len = 0 ending_index = -1 for i in range (0, n): if(arr[i] == 0): arr[i] = -1 else: arr[i] = 1 # Traverse through the given array for i in range (0, n): # Add current element to sum curr_sum = curr_sum + arr[i] # To handle sum = 0 at last index if (curr_sum == 0): max_len = i + 1 ending_index = i # If this sum is seen before, if curr_sum in hash_map: # If max_len is smaller than new subarray # Update max_len and ending_index if max_len < i - hash_map[curr_sum]: max_len = i - hash_map[curr_sum] ending_index = i else: # else put this sum in dictionary hash_map[curr_sum] = i for i in range (0, n): if(arr[i] == -1): arr[i] = 0 else: arr[i] = 1 print (ending_index - max_len + 1, end =\" \") print (\"to\", end = \" \") print (ending_index) return max_len # Driver Codearr = [1, 0, 0, 1, 0, 1, 1]n = len(arr) maxLen(arr, n) # This code is contributed# by Tarun Garg",
"e": 24550,
"s": 23071,
"text": null
},
{
"code": "// C# program to find the largest subarray// with equal number of 0s and 1susing System;using System.Collections.Generic; class LargestSubArray1 { // Returns largest subarray with // equal number of 0s and 1s public virtual int maxLen(int[] arr, int n) { // Creates an empty Dictionary hM Dictionary<int, int> hM = new Dictionary<int, int>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result int ending_index = -1; int start_index = 0; for (int i = 0; i < n; i++) { arr[i] = (arr[i] == 0) ? -1 : 1; } // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) { max_len = i + 1; ending_index = i; } // If this sum is seen before, // then update max_len // if required if (hM.ContainsKey(sum)) { if (max_len < i - hM[sum]) { max_len = i - hM[sum]; ending_index = i; } } else // Else put this sum in hash table { hM[sum] = i; } } for (int i = 0; i < n; i++) { arr[i] = (arr[i] == -1) ? 0 : 1; } int end = ending_index - max_len + 1; Console.WriteLine(end + \" to \" + ending_index); return max_len; } // Driver Code public static void Main(string[] args) { LargestSubArray1 sub = new LargestSubArray1(); int[] arr = new int[] { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.Length; sub.maxLen(arr, n); }} // This code is contributed by Shrikant13",
"e": 26516,
"s": 24550,
"text": null
},
{
"code": "<script> // Javascript program to find largest// subarray with equal number of// 0's and 1's. // Returns largest subarray with equal// number of 0s and 1sfunction maxLen(arr, n){ // Creates an empty hashMap hM let hM = new Map(); // Initialize sum of elements let sum = 0; // Initialize result let max_len = 0; let ending_index = -1; for(let i = 0; i < n; i++) arr[i] = (arr[i] == 0) ? -1 : 1; // Traverse through the given array for(let i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) { max_len = i + 1; ending_index = i; } // If this sum is seen before, then // update max_len if required if (hM.has(sum)) { if (max_len < i - hM[sum]) { max_len = i - hM[sum]; ending_index = i; } } // Else put this sum in hash table else hM[sum] = i; } for(let i = 0; i < n; i++) arr[i] = (arr[i] == -1) ? 0 : 1; document.write(ending_index - max_len + 1 + \" to \" + ending_index); return max_len;} // Driver codelet arr = [ 1, 0, 0, 1, 0, 1, 1 ];let n = arr.length; maxLen(arr, n); // This code is contributed by gfgking </script>",
"e": 27902,
"s": 26516,
"text": null
},
{
"code": null,
"e": 27911,
"s": 27902,
"text": "Output: "
},
{
"code": null,
"e": 27918,
"s": 27911,
"text": "0 to 5"
},
{
"code": null,
"e": 27940,
"s": 27918,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 28006,
"s": 27940,
"text": "Time Complexity: O(n). As the given array is traversed only once."
},
{
"code": null,
"e": 28080,
"s": 28006,
"text": "Auxiliary Space: O(n). As hash_map has been used which takes extra space."
},
{
"code": null,
"e": 28205,
"s": 28080,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28222,
"s": 28205,
"text": "Vijay Akkaladevi"
},
{
"code": null,
"e": 28228,
"s": 28222,
"text": "ukasp"
},
{
"code": null,
"e": 28240,
"s": 28228,
"text": "shrikanth13"
},
{
"code": null,
"e": 28255,
"s": 28240,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 28269,
"s": 28255,
"text": "rathbhupendra"
},
{
"code": null,
"e": 28279,
"s": 28269,
"text": "tarun2207"
},
{
"code": null,
"e": 28291,
"s": 28279,
"text": "bidibaaz123"
},
{
"code": null,
"e": 28300,
"s": 28291,
"text": "ninjapro"
},
{
"code": null,
"e": 28317,
"s": 28300,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 28330,
"s": 28317,
"text": "rahulsharma9"
},
{
"code": null,
"e": 28351,
"s": 28330,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 28359,
"s": 28351,
"text": "gfgking"
},
{
"code": null,
"e": 28373,
"s": 28359,
"text": "manav23lohani"
},
{
"code": null,
"e": 28392,
"s": 28373,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28409,
"s": 28392,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28416,
"s": 28409,
"text": "Amazon"
},
{
"code": null,
"e": 28427,
"s": 28416,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 28442,
"s": 28427,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 28448,
"s": 28442,
"text": "Paytm"
},
{
"code": null,
"e": 28459,
"s": 28448,
"text": "prefix-sum"
},
{
"code": null,
"e": 28466,
"s": 28459,
"text": "Arrays"
},
{
"code": null,
"e": 28471,
"s": 28466,
"text": "Hash"
},
{
"code": null,
"e": 28477,
"s": 28471,
"text": "Paytm"
},
{
"code": null,
"e": 28492,
"s": 28477,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 28499,
"s": 28492,
"text": "Amazon"
},
{
"code": null,
"e": 28510,
"s": 28499,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 28521,
"s": 28510,
"text": "prefix-sum"
},
{
"code": null,
"e": 28528,
"s": 28521,
"text": "Arrays"
},
{
"code": null,
"e": 28533,
"s": 28528,
"text": "Hash"
},
{
"code": null,
"e": 28631,
"s": 28533,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28699,
"s": 28631,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 28743,
"s": 28699,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 28775,
"s": 28743,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28823,
"s": 28775,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 28837,
"s": 28823,
"text": "Linear Search"
},
{
"code": null,
"e": 28875,
"s": 28837,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 28960,
"s": 28875,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 28991,
"s": 28960,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 29027,
"s": 28991,
"text": "Internal Working of HashMap in Java"
}
] |
Python EasyGUI – Enter Box | 05 Sep, 2020
Enter Box : It is used to get the input from the user, input can be any keyboard input, it takes input in form of string. It displays the title, message to be displayed, place to enter a text and a pair of “Ok”, “Cancel” button which is used confirm the input. Also we can set some default text to the place where user enter text, below is how the enter box looks like
In order to do this we will use enterbox method
Syntax : enterbox(message, title, default_text)
Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is string which is default text
Return : It returns the entered text and None if cancel is pressed
Example :In this we will create a enter box with default text, and will show the specific message on the screen according to the entered text, below is the implementation
# importing easygui modulefrom easygui import * # message to be displayedtext = "Enter your Geek name !!" # window titletitle = "Window Title GfG" # default textd_text = "Enter here.." # creating a enter boxoutput = enterbox(text, title, d_text) # title for the message boxtitle = "Message Box" # creating a messagemessage = "Enterted Name : " + str(output) # creating a message boxmsg = msgbox(message, title)
Output :
Another Example :In this we will create a enter box, and will show the specific message on the screen according to the entered text, below is the implementation
# importing easygui modulefrom easygui import * # message to be displayedtext = "Enter Something" # window titletitle = "Window Title GfG" # creating a enter boxoutput = enterbox(text, title) # title for the message boxtitle = "Message Box" # creating a messagemessage = "Enterted string : " + str(output) # creating a message boxmsg = msgbox(message, title)
Output :
Python-EasyGUI
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 397,
"s": 28,
"text": "Enter Box : It is used to get the input from the user, input can be any keyboard input, it takes input in form of string. It displays the title, message to be displayed, place to enter a text and a pair of “Ok”, “Cancel” button which is used confirm the input. Also we can set some default text to the place where user enter text, below is how the enter box looks like"
},
{
"code": null,
"e": 445,
"s": 397,
"text": "In order to do this we will use enterbox method"
},
{
"code": null,
"e": 493,
"s": 445,
"text": "Syntax : enterbox(message, title, default_text)"
},
{
"code": null,
"e": 660,
"s": 493,
"text": "Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is string which is default text"
},
{
"code": null,
"e": 727,
"s": 660,
"text": "Return : It returns the entered text and None if cancel is pressed"
},
{
"code": null,
"e": 898,
"s": 727,
"text": "Example :In this we will create a enter box with default text, and will show the specific message on the screen according to the entered text, below is the implementation"
},
{
"code": "# importing easygui modulefrom easygui import * # message to be displayedtext = \"Enter your Geek name !!\" # window titletitle = \"Window Title GfG\" # default textd_text = \"Enter here..\" # creating a enter boxoutput = enterbox(text, title, d_text) # title for the message boxtitle = \"Message Box\" # creating a messagemessage = \"Enterted Name : \" + str(output) # creating a message boxmsg = msgbox(message, title)",
"e": 1316,
"s": 898,
"text": null
},
{
"code": null,
"e": 1325,
"s": 1316,
"text": "Output :"
},
{
"code": null,
"e": 1486,
"s": 1325,
"text": "Another Example :In this we will create a enter box, and will show the specific message on the screen according to the entered text, below is the implementation"
},
{
"code": "# importing easygui modulefrom easygui import * # message to be displayedtext = \"Enter Something\" # window titletitle = \"Window Title GfG\" # creating a enter boxoutput = enterbox(text, title) # title for the message boxtitle = \"Message Box\" # creating a messagemessage = \"Enterted string : \" + str(output) # creating a message boxmsg = msgbox(message, title)",
"e": 1853,
"s": 1486,
"text": null
},
{
"code": null,
"e": 1862,
"s": 1853,
"text": "Output :"
},
{
"code": null,
"e": 1877,
"s": 1862,
"text": "Python-EasyGUI"
},
{
"code": null,
"e": 1888,
"s": 1877,
"text": "Python-gui"
},
{
"code": null,
"e": 1895,
"s": 1888,
"text": "Python"
},
{
"code": null,
"e": 1993,
"s": 1895,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2025,
"s": 1993,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2073,
"s": 2052,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2096,
"s": 2073,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2152,
"s": 2096,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2183,
"s": 2152,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2225,
"s": 2183,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2267,
"s": 2225,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2306,
"s": 2267,
"text": "Python | Get unique values from a list"
}
] |
Length of longest subarray with increasing contiguous elements | 08 Jul, 2022
Given an array arr[] of length N, the task is to find the length of the longest subarray which consists of consecutive numbers in increasing order, from the array.
Examples:
Input: arr[] = {2, 3, 4, 6, 7, 8, 9, 10}Output: 5Explanation: Subarray {6, 7, 8, 9, 10} is the longest subarray satisfying the given conditions. Therefore, the required output is 5.
Input: arr[] = {4, 5, 1, 2, 3, 4, 9, 10, 11, 12}Output: 4
Naive Approach: The simplest approach to solve the problem is to traverse the array and for every index i, traverse from over-index and find the length of the longest subarray satisfying the given condition starting from i. Shift i to the index which does not satisfy the condition and check from that index. Finally, print the maximum length of such subarray obtained.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the longest subarray// with increasing contiguous elementsint maxiConsecutiveSubarray(int arr[], int N){ // Stores the length of // required longest subarray int maxi = 0; for (int i = 0; i < N - 1; i++) { // Stores the length of length of longest // such subarray from ith index int cnt = 1, j; for (j = i; j < N; j++) { // If consecutive elements are // increasing and differ by 1 if (arr[j + 1] == arr[j] + 1) { cnt++; } // Otherwise else { break; } } // Update the longest subarray // obtained so far maxi = max(maxi, cnt); i = j; } // Return the length obtained return maxi;} // Driver Codeint main(){ int N = 11; int arr[] = { 1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7 }; cout << maxiConsecutiveSubarray(arr, N); return 0;}
// Java implementation for the above approachimport java.util.*; class GFG{ // Function to find the longest subarray// with increasing contiguous elementspublic static int maxiConsecutiveSubarray(int arr[], int N){ // Stores the length of // required longest subarray int maxi = 0; for(int i = 0; i < N - 1; i++) { // Stores the length of length of // longest such subarray from ith // index int cnt = 1, j; for(j = i; j < N - 1; j++) { // If consecutive elements are // increasing and differ by 1 if (arr[j + 1] == arr[j] + 1) { cnt++; } // Otherwise else { break; } } // Update the longest subarray // obtained so far maxi = Math.max(maxi, cnt); i = j; } // Return the length obtained return maxi;} // Driver Codepublic static void main(String args[]){ int N = 11; int arr[] = { 1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7 }; System.out.println(maxiConsecutiveSubarray(arr, N));}} // This code is contributed by hemanth gadarla
# Python3 implementation for# the above approach # Function to find the longest# subarray with increasing# contiguous elementsdef maxiConsecutiveSubarray(arr, N): # Stores the length of # required longest subarray maxi = 0; for i in range(N - 1): # Stores the length of # length of longest such # subarray from ith index cnt = 1; for j in range(i, N - 1): # If consecutive elements are # increasing and differ by 1 if (arr[j + 1] == arr[j] + 1): cnt += 1; # Otherwise else: break; # Update the longest subarray # obtained so far maxi = max(maxi, cnt); i = j; # Return the length obtained return maxi; # Driver Codeif __name__ == '__main__': N = 11; arr = [1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7]; print(maxiConsecutiveSubarray(arr, N)); # This code is contributed by Rajput-Ji
// C# implementation for the// above approachusing System;class GFG{ // Function to find the longest// subarray with increasing// contiguous elementspublic static int maxiConsecutiveSubarray(int []arr, int N){ // Stores the length of // required longest subarray int maxi = 0; for(int i = 0; i < N - 1; i++) { // Stores the length of // length of longest such // subarray from ith index int cnt = 1, j; for(j = i; j < N - 1; j++) { // If consecutive elements are // increasing and differ by 1 if (arr[j + 1] == arr[j] + 1) { cnt++; } // Otherwise else { break; } } // Update the longest subarray // obtained so far maxi = Math.Max(maxi, cnt); i = j; } // Return the length // obtained return maxi;} // Driver Codepublic static void Main(String []args){ int N = 11; int []arr = {1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7}; Console.WriteLine( maxiConsecutiveSubarray(arr, N));}} // This code is contributed by 29AjayKumar
<script>// Javascript program to implement// the above approach // Function to find the longest subarray// with increasing contiguous elementsfunction maxiConsecutiveSubarray(arr, N){ // Stores the length of // required longest subarray let maxi = 0; for(let i = 0; i < N - 1; i++) { // Stores the length of length of // longest such subarray from ith // index let cnt = 1, j; for(j = i; j < N - 1; j++) { // If consecutive elements are // increasing and differ by 1 if (arr[j + 1] == arr[j] + 1) { cnt++; } // Otherwise else { break; } } // Update the longest subarray // obtained so far maxi = Math.max(maxi, cnt); i = j; } // Return the length obtained return maxi;} // Driver Code let N = 11; let arr = [ 1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7 ]; document.write(maxiConsecutiveSubarray(arr, N)); </script>
3
Time Complexity: O(N2) Auxiliary Space: O(1)
hemanthswarna1506
29AjayKumar
Rajput-Ji
sinhadiptiprakash
avijitmondal1998
sakshi11101
subarray
two-pointer-algorithm
Arrays
Mathematical
Searching
two-pointer-algorithm
Arrays
Searching
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Operators in C / C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 192,
"s": 28,
"text": "Given an array arr[] of length N, the task is to find the length of the longest subarray which consists of consecutive numbers in increasing order, from the array."
},
{
"code": null,
"e": 202,
"s": 192,
"text": "Examples:"
},
{
"code": null,
"e": 384,
"s": 202,
"text": "Input: arr[] = {2, 3, 4, 6, 7, 8, 9, 10}Output: 5Explanation: Subarray {6, 7, 8, 9, 10} is the longest subarray satisfying the given conditions. Therefore, the required output is 5."
},
{
"code": null,
"e": 442,
"s": 384,
"text": "Input: arr[] = {4, 5, 1, 2, 3, 4, 9, 10, 11, 12}Output: 4"
},
{
"code": null,
"e": 812,
"s": 442,
"text": "Naive Approach: The simplest approach to solve the problem is to traverse the array and for every index i, traverse from over-index and find the length of the longest subarray satisfying the given condition starting from i. Shift i to the index which does not satisfy the condition and check from that index. Finally, print the maximum length of such subarray obtained."
},
{
"code": null,
"e": 864,
"s": 812,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 868,
"s": 864,
"text": "C++"
},
{
"code": null,
"e": 873,
"s": 868,
"text": "Java"
},
{
"code": null,
"e": 881,
"s": 873,
"text": "Python3"
},
{
"code": null,
"e": 884,
"s": 881,
"text": "C#"
},
{
"code": null,
"e": 895,
"s": 884,
"text": "Javascript"
},
{
"code": "// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the longest subarray// with increasing contiguous elementsint maxiConsecutiveSubarray(int arr[], int N){ // Stores the length of // required longest subarray int maxi = 0; for (int i = 0; i < N - 1; i++) { // Stores the length of length of longest // such subarray from ith index int cnt = 1, j; for (j = i; j < N; j++) { // If consecutive elements are // increasing and differ by 1 if (arr[j + 1] == arr[j] + 1) { cnt++; } // Otherwise else { break; } } // Update the longest subarray // obtained so far maxi = max(maxi, cnt); i = j; } // Return the length obtained return maxi;} // Driver Codeint main(){ int N = 11; int arr[] = { 1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7 }; cout << maxiConsecutiveSubarray(arr, N); return 0;}",
"e": 1953,
"s": 895,
"text": null
},
{
"code": "// Java implementation for the above approachimport java.util.*; class GFG{ // Function to find the longest subarray// with increasing contiguous elementspublic static int maxiConsecutiveSubarray(int arr[], int N){ // Stores the length of // required longest subarray int maxi = 0; for(int i = 0; i < N - 1; i++) { // Stores the length of length of // longest such subarray from ith // index int cnt = 1, j; for(j = i; j < N - 1; j++) { // If consecutive elements are // increasing and differ by 1 if (arr[j + 1] == arr[j] + 1) { cnt++; } // Otherwise else { break; } } // Update the longest subarray // obtained so far maxi = Math.max(maxi, cnt); i = j; } // Return the length obtained return maxi;} // Driver Codepublic static void main(String args[]){ int N = 11; int arr[] = { 1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7 }; System.out.println(maxiConsecutiveSubarray(arr, N));}} // This code is contributed by hemanth gadarla",
"e": 3205,
"s": 1953,
"text": null
},
{
"code": "# Python3 implementation for# the above approach # Function to find the longest# subarray with increasing# contiguous elementsdef maxiConsecutiveSubarray(arr, N): # Stores the length of # required longest subarray maxi = 0; for i in range(N - 1): # Stores the length of # length of longest such # subarray from ith index cnt = 1; for j in range(i, N - 1): # If consecutive elements are # increasing and differ by 1 if (arr[j + 1] == arr[j] + 1): cnt += 1; # Otherwise else: break; # Update the longest subarray # obtained so far maxi = max(maxi, cnt); i = j; # Return the length obtained return maxi; # Driver Codeif __name__ == '__main__': N = 11; arr = [1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7]; print(maxiConsecutiveSubarray(arr, N)); # This code is contributed by Rajput-Ji",
"e": 4173,
"s": 3205,
"text": null
},
{
"code": "// C# implementation for the// above approachusing System;class GFG{ // Function to find the longest// subarray with increasing// contiguous elementspublic static int maxiConsecutiveSubarray(int []arr, int N){ // Stores the length of // required longest subarray int maxi = 0; for(int i = 0; i < N - 1; i++) { // Stores the length of // length of longest such // subarray from ith index int cnt = 1, j; for(j = i; j < N - 1; j++) { // If consecutive elements are // increasing and differ by 1 if (arr[j + 1] == arr[j] + 1) { cnt++; } // Otherwise else { break; } } // Update the longest subarray // obtained so far maxi = Math.Max(maxi, cnt); i = j; } // Return the length // obtained return maxi;} // Driver Codepublic static void Main(String []args){ int N = 11; int []arr = {1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7}; Console.WriteLine( maxiConsecutiveSubarray(arr, N));}} // This code is contributed by 29AjayKumar",
"e": 5263,
"s": 4173,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach // Function to find the longest subarray// with increasing contiguous elementsfunction maxiConsecutiveSubarray(arr, N){ // Stores the length of // required longest subarray let maxi = 0; for(let i = 0; i < N - 1; i++) { // Stores the length of length of // longest such subarray from ith // index let cnt = 1, j; for(j = i; j < N - 1; j++) { // If consecutive elements are // increasing and differ by 1 if (arr[j + 1] == arr[j] + 1) { cnt++; } // Otherwise else { break; } } // Update the longest subarray // obtained so far maxi = Math.max(maxi, cnt); i = j; } // Return the length obtained return maxi;} // Driver Code let N = 11; let arr = [ 1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7 ]; document.write(maxiConsecutiveSubarray(arr, N)); </script>",
"e": 6378,
"s": 5263,
"text": null
},
{
"code": null,
"e": 6380,
"s": 6378,
"text": "3"
},
{
"code": null,
"e": 6425,
"s": 6380,
"text": "Time Complexity: O(N2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6443,
"s": 6425,
"text": "hemanthswarna1506"
},
{
"code": null,
"e": 6455,
"s": 6443,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6465,
"s": 6455,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6483,
"s": 6465,
"text": "sinhadiptiprakash"
},
{
"code": null,
"e": 6500,
"s": 6483,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 6512,
"s": 6500,
"text": "sakshi11101"
},
{
"code": null,
"e": 6521,
"s": 6512,
"text": "subarray"
},
{
"code": null,
"e": 6543,
"s": 6521,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 6550,
"s": 6543,
"text": "Arrays"
},
{
"code": null,
"e": 6563,
"s": 6550,
"text": "Mathematical"
},
{
"code": null,
"e": 6573,
"s": 6563,
"text": "Searching"
},
{
"code": null,
"e": 6595,
"s": 6573,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 6602,
"s": 6595,
"text": "Arrays"
},
{
"code": null,
"e": 6612,
"s": 6602,
"text": "Searching"
},
{
"code": null,
"e": 6625,
"s": 6612,
"text": "Mathematical"
},
{
"code": null,
"e": 6723,
"s": 6625,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6791,
"s": 6723,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 6835,
"s": 6791,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 6867,
"s": 6835,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6915,
"s": 6867,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 6929,
"s": 6915,
"text": "Linear Search"
},
{
"code": null,
"e": 6959,
"s": 6929,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 7002,
"s": 6959,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7062,
"s": 7002,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 7077,
"s": 7062,
"text": "C++ Data Types"
}
] |
How to Impute Missing Values in R? | 04 Jan, 2022
In this article, we will discuss how to impute missing values in R programming language.
In most datasets, there might be missing values either because it wasn’t entered or due to some error. Replacing these missing values with another value is known as Data Imputation. There are several ways of imputation. Common ones include replacing with average, minimum, or maximum value in that column/feature. Different datasets and features will require one type of imputation method. For example, considering a dataset of sales performance of a company, if the feature loss has missing values then it would be more logical to replace a minimum value.
Let’s impute the missing values of one column of data, i.e marks1 with the mean value of this entire column.
Syntax :
mean(x, trim = 0, na.rm = FALSE, ...)
Parameter:
x – any object
trim – observations to be trimmed from each end of x before the mean is computed
na.rm – FALSE to remove NA values
Example: Imputing missing values
R
# create a adataframedata <- data.frame(marks1 = c(NA, 22, NA, 49, 75), marks2 = c(81, 14, NA, 61, 12), marks3 = c(78.5, 19.325, NA, 28, 48.002)) # impute manuallydata$marks1[is.na(data$marks1)] <- mean(data$marks1, na.rm = T) data
Output:
Using the function impute( ) inside Hmisc library let’s impute the column marks2 of data with the median value of this entire column.
Example: Impute missing values
R
# install and load the required packages install.packages("Hmisc")library(Hmisc) # create a adataframedata <- data.frame(marks1 = c(NA, 22, NA, 49, 75), marks2 = c(81, 14, NA, 61, 12), marks3 = c(78.5, 19.325, NA, 28, 48.002)) # fill missing values of marks2 with medianimpute(data$marks2, median)
Output:
imputing with Median value
Using the function impute( ) inside Hmisc library let’s impute the column marks2 of data with a constant value.
Example: Impute missing values
R
# install and load the required packagesinstall.packages("Hmisc")library(Hmisc) # create a adataframedata <- data.frame(marks1 = c(NA, 22, NA, 49, 75), marks2 = c(81, 14, NA, 61, 12), marks3 = c(78.5, 19.325, NA, 28, 48.002)) # impute with a specific number# replace NA with 2000impute(data$marks3, 2000)
Output:
Impute with a specific Constant value
This can be done by imputing Median value of each column with NA using apply( ) function.
Syntax:
apply(X, MARGIN, FUN, ...)
Parameter:
X – an array, including a matrix
MARGIN – a vector
FUN – the function to be applied
Example: Impute the entire dataset
R
# create a adataframedata <- data.frame(marks1 = c(NA, 22, NA, 49, 75), marks2 = c(81, 14, NA, 61, 12), marks3 = c(78.5, 19.325, NA, 28, 48.002)) # getting median of each column using apply() all_column_median <- apply(data, 2, median, na.rm=TRUE) # imputing median value with NA for(i in colnames(data)) data[,i][is.na(data[,i])] <- all_column_median[i] data
Output:
Picked
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 117,
"s": 28,
"text": "In this article, we will discuss how to impute missing values in R programming language."
},
{
"code": null,
"e": 674,
"s": 117,
"text": "In most datasets, there might be missing values either because it wasn’t entered or due to some error. Replacing these missing values with another value is known as Data Imputation. There are several ways of imputation. Common ones include replacing with average, minimum, or maximum value in that column/feature. Different datasets and features will require one type of imputation method. For example, considering a dataset of sales performance of a company, if the feature loss has missing values then it would be more logical to replace a minimum value."
},
{
"code": null,
"e": 783,
"s": 674,
"text": "Let’s impute the missing values of one column of data, i.e marks1 with the mean value of this entire column."
},
{
"code": null,
"e": 793,
"s": 783,
"text": "Syntax :"
},
{
"code": null,
"e": 831,
"s": 793,
"text": "mean(x, trim = 0, na.rm = FALSE, ...)"
},
{
"code": null,
"e": 842,
"s": 831,
"text": "Parameter:"
},
{
"code": null,
"e": 857,
"s": 842,
"text": "x – any object"
},
{
"code": null,
"e": 938,
"s": 857,
"text": "trim – observations to be trimmed from each end of x before the mean is computed"
},
{
"code": null,
"e": 972,
"s": 938,
"text": "na.rm – FALSE to remove NA values"
},
{
"code": null,
"e": 1005,
"s": 972,
"text": "Example: Imputing missing values"
},
{
"code": null,
"e": 1007,
"s": 1005,
"text": "R"
},
{
"code": "# create a adataframedata <- data.frame(marks1 = c(NA, 22, NA, 49, 75), marks2 = c(81, 14, NA, 61, 12), marks3 = c(78.5, 19.325, NA, 28, 48.002)) # impute manuallydata$marks1[is.na(data$marks1)] <- mean(data$marks1, na.rm = T) data",
"e": 1279,
"s": 1007,
"text": null
},
{
"code": null,
"e": 1287,
"s": 1279,
"text": "Output:"
},
{
"code": null,
"e": 1421,
"s": 1287,
"text": "Using the function impute( ) inside Hmisc library let’s impute the column marks2 of data with the median value of this entire column."
},
{
"code": null,
"e": 1452,
"s": 1421,
"text": "Example: Impute missing values"
},
{
"code": null,
"e": 1454,
"s": 1452,
"text": "R"
},
{
"code": "# install and load the required packages install.packages(\"Hmisc\")library(Hmisc) # create a adataframedata <- data.frame(marks1 = c(NA, 22, NA, 49, 75), marks2 = c(81, 14, NA, 61, 12), marks3 = c(78.5, 19.325, NA, 28, 48.002)) # fill missing values of marks2 with medianimpute(data$marks2, median)",
"e": 1820,
"s": 1454,
"text": null
},
{
"code": null,
"e": 1828,
"s": 1820,
"text": "Output:"
},
{
"code": null,
"e": 1855,
"s": 1828,
"text": "imputing with Median value"
},
{
"code": null,
"e": 1967,
"s": 1855,
"text": "Using the function impute( ) inside Hmisc library let’s impute the column marks2 of data with a constant value."
},
{
"code": null,
"e": 1998,
"s": 1967,
"text": "Example: Impute missing values"
},
{
"code": null,
"e": 2000,
"s": 1998,
"text": "R"
},
{
"code": "# install and load the required packagesinstall.packages(\"Hmisc\")library(Hmisc) # create a adataframedata <- data.frame(marks1 = c(NA, 22, NA, 49, 75), marks2 = c(81, 14, NA, 61, 12), marks3 = c(78.5, 19.325, NA, 28, 48.002)) # impute with a specific number# replace NA with 2000impute(data$marks3, 2000) ",
"e": 2375,
"s": 2000,
"text": null
},
{
"code": null,
"e": 2383,
"s": 2375,
"text": "Output:"
},
{
"code": null,
"e": 2422,
"s": 2383,
"text": " Impute with a specific Constant value"
},
{
"code": null,
"e": 2512,
"s": 2422,
"text": "This can be done by imputing Median value of each column with NA using apply( ) function."
},
{
"code": null,
"e": 2521,
"s": 2512,
"text": "Syntax: "
},
{
"code": null,
"e": 2548,
"s": 2521,
"text": "apply(X, MARGIN, FUN, ...)"
},
{
"code": null,
"e": 2559,
"s": 2548,
"text": "Parameter:"
},
{
"code": null,
"e": 2592,
"s": 2559,
"text": "X – an array, including a matrix"
},
{
"code": null,
"e": 2610,
"s": 2592,
"text": "MARGIN – a vector"
},
{
"code": null,
"e": 2643,
"s": 2610,
"text": "FUN – the function to be applied"
},
{
"code": null,
"e": 2679,
"s": 2643,
"text": "Example: Impute the entire dataset "
},
{
"code": null,
"e": 2681,
"s": 2679,
"text": "R"
},
{
"code": "# create a adataframedata <- data.frame(marks1 = c(NA, 22, NA, 49, 75), marks2 = c(81, 14, NA, 61, 12), marks3 = c(78.5, 19.325, NA, 28, 48.002)) # getting median of each column using apply() all_column_median <- apply(data, 2, median, na.rm=TRUE) # imputing median value with NA for(i in colnames(data)) data[,i][is.na(data[,i])] <- all_column_median[i] data",
"e": 3111,
"s": 2681,
"text": null
},
{
"code": null,
"e": 3119,
"s": 3111,
"text": "Output:"
},
{
"code": null,
"e": 3126,
"s": 3119,
"text": "Picked"
},
{
"code": null,
"e": 3138,
"s": 3126,
"text": "R-DataFrame"
},
{
"code": null,
"e": 3149,
"s": 3138,
"text": "R Language"
},
{
"code": null,
"e": 3247,
"s": 3149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3299,
"s": 3247,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3357,
"s": 3299,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3392,
"s": 3357,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3430,
"s": 3392,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3479,
"s": 3430,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3496,
"s": 3479,
"text": "R - if statement"
},
{
"code": null,
"e": 3533,
"s": 3496,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3576,
"s": 3533,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3613,
"s": 3576,
"text": "How to import an Excel File into R ?"
}
] |
Fix() and Format() Function in MS Access | 02 Sep, 2020
1. Fix() Function :In MS Access, the fix() function returns the integer part of a number. In this function, a number will be pass as a parameter and it will return the integer part of that number.
Syntax :
Fix(number)
Example-1 :
SELECT Fix(-75.43) AS FixNum;
Output –
Example-2 :
SELECT Fix(23.93) AS FixNum;
Output –
2. Format() function :In MS Access, the format function will return a number in a specified format. In this function, the value will be passed as the first parameter and the format will be pass as second parameter. And it will return the converted format.
Syntax :
Format(value, format)
Example-1 :
SELECT Format(0.55, "Percent")
AS FormattedPercentage;
Output –
Example-2 :
SELECT Format(0.0000000004500121424255, "Scientific")
AS FormattedScientific;
Output –
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 225,
"s": 28,
"text": "1. Fix() Function :In MS Access, the fix() function returns the integer part of a number. In this function, a number will be pass as a parameter and it will return the integer part of that number."
},
{
"code": null,
"e": 234,
"s": 225,
"text": "Syntax :"
},
{
"code": null,
"e": 247,
"s": 234,
"text": "Fix(number) "
},
{
"code": null,
"e": 259,
"s": 247,
"text": "Example-1 :"
},
{
"code": null,
"e": 289,
"s": 259,
"text": "SELECT Fix(-75.43) AS FixNum;"
},
{
"code": null,
"e": 298,
"s": 289,
"text": "Output –"
},
{
"code": null,
"e": 310,
"s": 298,
"text": "Example-2 :"
},
{
"code": null,
"e": 339,
"s": 310,
"text": "SELECT Fix(23.93) AS FixNum;"
},
{
"code": null,
"e": 348,
"s": 339,
"text": "Output –"
},
{
"code": null,
"e": 604,
"s": 348,
"text": "2. Format() function :In MS Access, the format function will return a number in a specified format. In this function, the value will be passed as the first parameter and the format will be pass as second parameter. And it will return the converted format."
},
{
"code": null,
"e": 613,
"s": 604,
"text": "Syntax :"
},
{
"code": null,
"e": 636,
"s": 613,
"text": "Format(value, format) "
},
{
"code": null,
"e": 648,
"s": 636,
"text": "Example-1 :"
},
{
"code": null,
"e": 704,
"s": 648,
"text": "SELECT Format(0.55, \"Percent\") \nAS FormattedPercentage;"
},
{
"code": null,
"e": 713,
"s": 704,
"text": "Output –"
},
{
"code": null,
"e": 725,
"s": 713,
"text": "Example-2 :"
},
{
"code": null,
"e": 804,
"s": 725,
"text": "SELECT Format(0.0000000004500121424255, \"Scientific\") \nAS FormattedScientific;"
},
{
"code": null,
"e": 813,
"s": 804,
"text": "Output –"
},
{
"code": null,
"e": 822,
"s": 813,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 833,
"s": 822,
"text": "SQL-Server"
},
{
"code": null,
"e": 837,
"s": 833,
"text": "SQL"
},
{
"code": null,
"e": 841,
"s": 837,
"text": "SQL"
}
] |
Python program to find middle of a linked list using one traversal | 06 Jul, 2022
Given a singly linked list, find the middle of the linked list. Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3.
Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2. Method 2: Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list.
Python3
# Python 3 program to find the middle of a # given linked list # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Function to get the middle of # the linked list def printMiddle(self): slow_ptr = self.head fast_ptr = self.head if self.head is not None: while (fast_ptr is not None and fast_ptr.next is not None): fast_ptr = fast_ptr.next.next slow_ptr = slow_ptr.next print("The middle element is: ", slow_ptr.data) # Driver codelist1 = LinkedList()list1.push(5)list1.push(4)list1.push(2)list1.push(3)list1.push(1)list1.printMiddle()
Output:
The middle element is: 2
Method 3: Initialized the temp variable as head Initialized count to Zero Take loop till head will become Null(i.e end of the list) and increment the temp node when count is odd only, in this way temp will traverse till mid element and head will traverse all linked list. Print the data of temp.
Python3
# Python 3 program to find the middle of a # given linked list class Node: def __init__(self, value): self.data = value self.next = None class LinkedList: def __init__(self): self.head = None # create Node and make linked list def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printMiddle(self): temp = self.head count = 0 while self.head: # only update when count is odd if (count & 1): temp = temp.next self.head = self.head.next # increment count in each iteration count += 1 print(temp.data) # Driver codellist = LinkedList() llist.push(1)llist.push(20) llist.push(100) llist.push(15) llist.push(35)llist.printMiddle()# code has been contributed by - Yogesh Joshi
100
simmytarika5
Python DSA-exercises
Python LinkedList-exercises
Python-Data-Structures
Technical Scripter 2018
Linked List
Python Programs
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Rearrange a given linked list in-place.
Types of Linked List
Find first node of loop in a linked list
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 264,
"s": 52,
"text": "Given a singly linked list, find the middle of the linked list. Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3."
},
{
"code": null,
"e": 593,
"s": 264,
"text": "Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2. Method 2: Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list. "
},
{
"code": null,
"e": 601,
"s": 593,
"text": "Python3"
},
{
"code": "# Python 3 program to find the middle of a # given linked list # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Function to get the middle of # the linked list def printMiddle(self): slow_ptr = self.head fast_ptr = self.head if self.head is not None: while (fast_ptr is not None and fast_ptr.next is not None): fast_ptr = fast_ptr.next.next slow_ptr = slow_ptr.next print(\"The middle element is: \", slow_ptr.data) # Driver codelist1 = LinkedList()list1.push(5)list1.push(4)list1.push(2)list1.push(3)list1.push(1)list1.printMiddle()",
"e": 1523,
"s": 601,
"text": null
},
{
"code": null,
"e": 1531,
"s": 1523,
"text": "Output:"
},
{
"code": null,
"e": 1557,
"s": 1531,
"text": "The middle element is: 2"
},
{
"code": null,
"e": 1854,
"s": 1557,
"text": "Method 3: Initialized the temp variable as head Initialized count to Zero Take loop till head will become Null(i.e end of the list) and increment the temp node when count is odd only, in this way temp will traverse till mid element and head will traverse all linked list. Print the data of temp. "
},
{
"code": null,
"e": 1862,
"s": 1854,
"text": "Python3"
},
{
"code": "# Python 3 program to find the middle of a # given linked list class Node: def __init__(self, value): self.data = value self.next = None class LinkedList: def __init__(self): self.head = None # create Node and make linked list def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printMiddle(self): temp = self.head count = 0 while self.head: # only update when count is odd if (count & 1): temp = temp.next self.head = self.head.next # increment count in each iteration count += 1 print(temp.data) # Driver codellist = LinkedList() llist.push(1)llist.push(20) llist.push(100) llist.push(15) llist.push(35)llist.printMiddle()# code has been contributed by - Yogesh Joshi",
"e": 2802,
"s": 1862,
"text": null
},
{
"code": null,
"e": 2806,
"s": 2802,
"text": "100"
},
{
"code": null,
"e": 2819,
"s": 2806,
"text": "simmytarika5"
},
{
"code": null,
"e": 2840,
"s": 2819,
"text": "Python DSA-exercises"
},
{
"code": null,
"e": 2868,
"s": 2840,
"text": "Python LinkedList-exercises"
},
{
"code": null,
"e": 2891,
"s": 2868,
"text": "Python-Data-Structures"
},
{
"code": null,
"e": 2915,
"s": 2891,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 2927,
"s": 2915,
"text": "Linked List"
},
{
"code": null,
"e": 2943,
"s": 2927,
"text": "Python Programs"
},
{
"code": null,
"e": 2955,
"s": 2943,
"text": "Linked List"
},
{
"code": null,
"e": 3053,
"s": 2955,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3085,
"s": 3053,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 3149,
"s": 3085,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 3189,
"s": 3149,
"text": "Rearrange a given linked list in-place."
},
{
"code": null,
"e": 3210,
"s": 3189,
"text": "Types of Linked List"
},
{
"code": null,
"e": 3251,
"s": 3210,
"text": "Find first node of loop in a linked list"
},
{
"code": null,
"e": 3294,
"s": 3251,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3316,
"s": 3294,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3355,
"s": 3316,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3393,
"s": 3355,
"text": "Python | Convert a list to dictionary"
}
] |
MongoDB – Query Documents using Mongo Shell | 14 Jun, 2022
MongoDB provides you read operations to retrieve documents from the collection or query a collection for a document. You can perform read operations using the db.collection.find() method. This method selects or views the documents from the collection and returns the cursor to the selected document.
find() is a mongo shell method, which can be used in the multi-document transactions. The documents displayed by this method are in non-structured form. If you want to get data in a structured form, then use pretty() method with find() method.
db.collection.find().pretty()
This method iterates the cursor automatically to display the first 20 documents of the collection. If you want this method will display more than 20 documents, then type it to continue the iteration.
Syntax:
db.collection.find(filter, projection)
Parameters:
filter: It is an optional parameter. It specifies the selection filter with the help of query operators. And if you want to get all the documents present in the collection, then omit these parameters or pass an empty document in the method. The type of this parameter is a Document.
projection: It is an optional parameter. It specifies that only those fields return to the document that matches the given query filter. And if you want to get all the fields in the document, then omit this parameter.
Return: This method returns a cursor to the documents that match the specified query criteria. When you use find() method, it returns documents which means the method is actually returning the cursor to the documents.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: contributor
Document: five documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are selecting all the documents of the contributor collection and displaying on the screen using db.collection.find() method.
Syntax:
db.contributor.find()
In this example, we are selecting all the documents of the contributor collection and displaying them in the organized form using db.collection.find() method with pretty() method.
Syntax:
db.contributor.find().pretty()
In this example, we are selecting only those documents that satisfy the given condition, i.e, language: “C#”. Or in other words, we are selecting only those contributors who are working with C# language.
Syntax:
db.collection.find({field: value})
In this example, we are selecting only those documents that satisfy the given condition, here the condition is created using query operators. Or in words, we are selecting only those contributors who are working with C# or Java language.
Syntax:
db.collection.find({field: {operator: value}})
Here, we are using $in operator. This operator is used to matches any of the values specified in the given array.
db.contributor.find({language: {$in:[ "Java", "C#"]}}).pretty()
In this example, we are creating a compound query in which we specify the condition for more than one field using logical AND. Here the logical AND connects the clauses of a compound query so that the query selects only those documents in the collection that satisfy all the conditions. Or in other words, in this example, we are retrieving only those contributors that are from the CSE branch and working with the Java language.
In this example, we are creating a compound query in which we specify the condition using $or operator. Here the $or operator connects the clauses of a compound query so that the query selects only those documents in the collection that satisfy at least one condition. Or in other words, in this example, we are retrieving only those contributors that are from the CSE branch or working with the Java language.
In this example, we are setting filter using both AND and OR operators. or in other words, in this example, we are retrieving only those contributors that are from the ECE branch and either age is 23 or working with the Java language.
gulshankumarar231
khushb99
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
Mounting a Volume Inside Docker Container
Fuzzy Logic | Introduction | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 329,
"s": 28,
"text": "MongoDB provides you read operations to retrieve documents from the collection or query a collection for a document. You can perform read operations using the db.collection.find() method. This method selects or views the documents from the collection and returns the cursor to the selected document. "
},
{
"code": null,
"e": 575,
"s": 329,
"text": "find() is a mongo shell method, which can be used in the multi-document transactions. The documents displayed by this method are in non-structured form. If you want to get data in a structured form, then use pretty() method with find() method. "
},
{
"code": null,
"e": 605,
"s": 575,
"text": "db.collection.find().pretty()"
},
{
"code": null,
"e": 807,
"s": 605,
"text": "This method iterates the cursor automatically to display the first 20 documents of the collection. If you want this method will display more than 20 documents, then type it to continue the iteration. "
},
{
"code": null,
"e": 817,
"s": 807,
"text": "Syntax: "
},
{
"code": null,
"e": 856,
"s": 817,
"text": "db.collection.find(filter, projection)"
},
{
"code": null,
"e": 870,
"s": 856,
"text": "Parameters: "
},
{
"code": null,
"e": 1153,
"s": 870,
"text": "filter: It is an optional parameter. It specifies the selection filter with the help of query operators. And if you want to get all the documents present in the collection, then omit these parameters or pass an empty document in the method. The type of this parameter is a Document."
},
{
"code": null,
"e": 1371,
"s": 1153,
"text": "projection: It is an optional parameter. It specifies that only those fields return to the document that matches the given query filter. And if you want to get all the fields in the document, then omit this parameter."
},
{
"code": null,
"e": 1589,
"s": 1371,
"text": "Return: This method returns a cursor to the documents that match the specified query criteria. When you use find() method, it returns documents which means the method is actually returning the cursor to the documents."
},
{
"code": null,
"e": 1602,
"s": 1591,
"text": "Examples: "
},
{
"code": null,
"e": 1652,
"s": 1602,
"text": "In the following examples, we are working with: "
},
{
"code": null,
"e": 1804,
"s": 1652,
"text": "Database: GeeksforGeeks\nCollection: contributor\nDocument: five documents that contain the details of the contributors in the form of field-value pairs."
},
{
"code": null,
"e": 1955,
"s": 1808,
"text": "In this example, we are selecting all the documents of the contributor collection and displaying on the screen using db.collection.find() method. "
},
{
"code": null,
"e": 1965,
"s": 1955,
"text": "Syntax: "
},
{
"code": null,
"e": 1987,
"s": 1965,
"text": "db.contributor.find()"
},
{
"code": null,
"e": 2172,
"s": 1991,
"text": "In this example, we are selecting all the documents of the contributor collection and displaying them in the organized form using db.collection.find() method with pretty() method. "
},
{
"code": null,
"e": 2182,
"s": 2172,
"text": "Syntax: "
},
{
"code": null,
"e": 2213,
"s": 2182,
"text": "db.contributor.find().pretty()"
},
{
"code": null,
"e": 2422,
"s": 2217,
"text": "In this example, we are selecting only those documents that satisfy the given condition, i.e, language: “C#”. Or in other words, we are selecting only those contributors who are working with C# language. "
},
{
"code": null,
"e": 2432,
"s": 2422,
"text": "Syntax: "
},
{
"code": null,
"e": 2467,
"s": 2432,
"text": "db.collection.find({field: value})"
},
{
"code": null,
"e": 2710,
"s": 2471,
"text": "In this example, we are selecting only those documents that satisfy the given condition, here the condition is created using query operators. Or in words, we are selecting only those contributors who are working with C# or Java language. "
},
{
"code": null,
"e": 2720,
"s": 2710,
"text": "Syntax: "
},
{
"code": null,
"e": 2767,
"s": 2720,
"text": "db.collection.find({field: {operator: value}})"
},
{
"code": null,
"e": 2883,
"s": 2767,
"text": "Here, we are using $in operator. This operator is used to matches any of the values specified in the given array. "
},
{
"code": null,
"e": 2947,
"s": 2883,
"text": "db.contributor.find({language: {$in:[ \"Java\", \"C#\"]}}).pretty()"
},
{
"code": null,
"e": 3383,
"s": 2951,
"text": "In this example, we are creating a compound query in which we specify the condition for more than one field using logical AND. Here the logical AND connects the clauses of a compound query so that the query selects only those documents in the collection that satisfy all the conditions. Or in other words, in this example, we are retrieving only those contributors that are from the CSE branch and working with the Java language. "
},
{
"code": null,
"e": 3798,
"s": 3385,
"text": "In this example, we are creating a compound query in which we specify the condition using $or operator. Here the $or operator connects the clauses of a compound query so that the query selects only those documents in the collection that satisfy at least one condition. Or in other words, in this example, we are retrieving only those contributors that are from the CSE branch or working with the Java language. "
},
{
"code": null,
"e": 4034,
"s": 3798,
"text": "In this example, we are setting filter using both AND and OR operators. or in other words, in this example, we are retrieving only those contributors that are from the ECE branch and either age is 23 or working with the Java language. "
},
{
"code": null,
"e": 4054,
"s": 4036,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 4063,
"s": 4054,
"text": "khushb99"
},
{
"code": null,
"e": 4071,
"s": 4063,
"text": "MongoDB"
},
{
"code": null,
"e": 4097,
"s": 4071,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 4195,
"s": 4097,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4231,
"s": 4195,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 4275,
"s": 4231,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 4311,
"s": 4275,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 4335,
"s": 4311,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 4370,
"s": 4335,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 4411,
"s": 4370,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 4459,
"s": 4411,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 4500,
"s": 4459,
"text": "Monolithic vs Microservices architecture"
},
{
"code": null,
"e": 4542,
"s": 4500,
"text": "Mounting a Volume Inside Docker Container"
}
] |
How to make sliders in Plotly? | 01 Oct, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
In plotly, a slider is a Tkinter object with which a user can set the values by moving an indicator. A slider can be vertically and horizontally arranged. In plotly, the slider can be formed by using the Scale method().
Example 1:
Python3
import plotly.graph_objects as pximport plotly.express as goimport numpy as np df = go.data.tips() x = df['total_bill']y = df['day'] plot = px.Figure(data=[px.Scatter( x=x, y=y, mode='lines',)]) plot.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, step="day", stepmode="backward"), ]) ), rangeslider=dict( visible=True ), )) plot.show()
Output:
Example 2:
Python3
import plotly.express as px df = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip", animation_frame="day", color="sex",) fig["layout"].pop("updatemenus")fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. "
},
{
"code": null,
"e": 554,
"s": 333,
"text": "In plotly, a slider is a Tkinter object with which a user can set the values by moving an indicator. A slider can be vertically and horizontally arranged. In plotly, the slider can be formed by using the Scale method(). "
},
{
"code": null,
"e": 565,
"s": 554,
"text": "Example 1:"
},
{
"code": null,
"e": 573,
"s": 565,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as pximport plotly.express as goimport numpy as np df = go.data.tips() x = df['total_bill']y = df['day'] plot = px.Figure(data=[px.Scatter( x=x, y=y, mode='lines',)]) plot.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, step=\"day\", stepmode=\"backward\"), ]) ), rangeslider=dict( visible=True ), )) plot.show()",
"e": 1074,
"s": 573,
"text": null
},
{
"code": null,
"e": 1082,
"s": 1074,
"text": "Output:"
},
{
"code": null,
"e": 1093,
"s": 1082,
"text": "Example 2:"
},
{
"code": null,
"e": 1101,
"s": 1093,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.tips() fig = px.scatter(df, x=\"total_bill\", y=\"tip\", animation_frame=\"day\", color=\"sex\",) fig[\"layout\"].pop(\"updatemenus\")fig.show()",
"e": 1311,
"s": 1101,
"text": null
},
{
"code": null,
"e": 1320,
"s": 1311,
"text": "Output: "
},
{
"code": null,
"e": 1336,
"s": 1322,
"text": "Python-Plotly"
},
{
"code": null,
"e": 1343,
"s": 1336,
"text": "Python"
},
{
"code": null,
"e": 1441,
"s": 1343,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1473,
"s": 1441,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1500,
"s": 1473,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1521,
"s": 1500,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1544,
"s": 1521,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1600,
"s": 1544,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1631,
"s": 1600,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1673,
"s": 1631,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1715,
"s": 1673,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1754,
"s": 1715,
"text": "Python | Get unique values from a list"
}
] |
Node.js fs.mkdir() Method | 12 Oct, 2021
The fs.mkdir() method i Node.js is used to create a directory asynchronously.
Syntax
fs.mkdir(path, mode, callback)
Parameters: This method accept three parameters as mentioned above and described below:
path: This parameter holds the path of the directory has to be created.
mode: This parameter holds the recursive boolean value. The mode option is used to set the directory permission, by default it is 0777.
callback: This parameter holds the callback function that contains error. The recursive option if set to true will not give an error message if the directory to be created already exists.
Below examples illustrate the use of fs.mkdir() method in Node.js:
Example 1:
// Node.js program to demonstrate the // fs.mkdir() Method // Include fs and path moduleconst fs = require('fs');const path = require('path'); fs.mkdir(path.join(__dirname, 'test'), (err) => { if (err) { return console.error(err); } console.log('Directory created successfully!');});
Output:
Directory created successfully!
Directory Structure Before running the code:
Directory Structure After running the code:
Note: If you will run this program again, then it will display an error message as the directory already exists. To overcome this error we will use the recursive option.
Example 2: This example illustrate the use to recursive option.
// Node.js program to demonstrate the // fs.mkdir() Method // Include fs and path moduleconst fs = require('fs');const path = require('path'); fs.mkdir(path.join(__dirname, 'test'), { recursive: true }, (err) => { if (err) { return console.error(err); } console.log('Directory created successfully!'); });
Output:
Directory created successfully!
Reference: https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback
Node.js-fs-module
Picked
Node.js
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": "\n12 Oct, 2021"
},
{
"code": null,
"e": 130,
"s": 52,
"text": "The fs.mkdir() method i Node.js is used to create a directory asynchronously."
},
{
"code": null,
"e": 137,
"s": 130,
"text": "Syntax"
},
{
"code": null,
"e": 168,
"s": 137,
"text": "fs.mkdir(path, mode, callback)"
},
{
"code": null,
"e": 256,
"s": 168,
"text": "Parameters: This method accept three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 328,
"s": 256,
"text": "path: This parameter holds the path of the directory has to be created."
},
{
"code": null,
"e": 464,
"s": 328,
"text": "mode: This parameter holds the recursive boolean value. The mode option is used to set the directory permission, by default it is 0777."
},
{
"code": null,
"e": 652,
"s": 464,
"text": "callback: This parameter holds the callback function that contains error. The recursive option if set to true will not give an error message if the directory to be created already exists."
},
{
"code": null,
"e": 719,
"s": 652,
"text": "Below examples illustrate the use of fs.mkdir() method in Node.js:"
},
{
"code": null,
"e": 730,
"s": 719,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // fs.mkdir() Method // Include fs and path moduleconst fs = require('fs');const path = require('path'); fs.mkdir(path.join(__dirname, 'test'), (err) => { if (err) { return console.error(err); } console.log('Directory created successfully!');});",
"e": 1035,
"s": 730,
"text": null
},
{
"code": null,
"e": 1043,
"s": 1035,
"text": "Output:"
},
{
"code": null,
"e": 1075,
"s": 1043,
"text": "Directory created successfully!"
},
{
"code": null,
"e": 1120,
"s": 1075,
"text": "Directory Structure Before running the code:"
},
{
"code": null,
"e": 1164,
"s": 1120,
"text": "Directory Structure After running the code:"
},
{
"code": null,
"e": 1334,
"s": 1164,
"text": "Note: If you will run this program again, then it will display an error message as the directory already exists. To overcome this error we will use the recursive option."
},
{
"code": null,
"e": 1398,
"s": 1334,
"text": "Example 2: This example illustrate the use to recursive option."
},
{
"code": "// Node.js program to demonstrate the // fs.mkdir() Method // Include fs and path moduleconst fs = require('fs');const path = require('path'); fs.mkdir(path.join(__dirname, 'test'), { recursive: true }, (err) => { if (err) { return console.error(err); } console.log('Directory created successfully!'); });",
"e": 1724,
"s": 1398,
"text": null
},
{
"code": null,
"e": 1732,
"s": 1724,
"text": "Output:"
},
{
"code": null,
"e": 1764,
"s": 1732,
"text": "Directory created successfully!"
},
{
"code": null,
"e": 1840,
"s": 1764,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback"
},
{
"code": null,
"e": 1858,
"s": 1840,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 1865,
"s": 1858,
"text": "Picked"
},
{
"code": null,
"e": 1873,
"s": 1865,
"text": "Node.js"
},
{
"code": null,
"e": 1890,
"s": 1873,
"text": "Web Technologies"
}
] |
Python | Flatten given list of dictionaries | 12 Jan, 2022
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries.
Given below are a few methods to solve the given task.
Method #1: Using Naive Method
Python3
# Python code to demonstrate# to flatten list of dictionaries # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionaryprint ("initial dictionary", str(ini_dict)) # code to flatten list of dictionaryres = {}for d in ini_dict: res.update(d) # printing resultprint ("result", str(res))
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result {'b': 2, 'a': 1, 'c': 3}
Method #2: Using dict comprehension
Python3
# Python code to demonstrate# to flatten list of dictionaries # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionaryprint ("initial dictionary", str(ini_dict)) # code to flatten list of dictionaryres = {k: v for d in ini_dict for k, v in d.items()} # printing resultprint ("result", str(res))
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result {'a': 1, 'c': 3, 'b': 2}
Method #3: Using reduce
Python3
# Python code to demonstrate# to flatten list of dictionariesfrom functools import reduce # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionaryprint ("initial dictionary", str(ini_dict)) # code to flatten list of dictionaryres = reduce(lambda d, src: d.update(src) or d, ini_dict, {}) # printing resultprint ("result", str(res))
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result {'a': 1, 'c': 3, 'b': 2}
Method #4: Using collections.ChainMap
Python3
# Python code to demonstrate# to flatten list of # dictionaries from collections import ChainMap # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionaryprint ("initial dictionary", str(ini_dict)) # code to flatten list of dictionaryres = ChainMap(*ini_dict) # printing resultprint ("result", str(res))
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result ChainMap({'a': 1}, {'b': 2}, {'c': 3})
rajeev0719singh
Python dictionary-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries."
},
{
"code": null,
"e": 205,
"s": 150,
"text": "Given below are a few methods to solve the given task."
},
{
"code": null,
"e": 235,
"s": 205,
"text": "Method #1: Using Naive Method"
},
{
"code": null,
"e": 243,
"s": 235,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to flatten list of dictionaries # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionaryprint (\"initial dictionary\", str(ini_dict)) # code to flatten list of dictionaryres = {}for d in ini_dict: res.update(d) # printing resultprint (\"result\", str(res))",
"e": 574,
"s": 243,
"text": null
},
{
"code": null,
"e": 657,
"s": 574,
"text": "initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]\nresult {'b': 2, 'a': 1, 'c': 3}\n"
},
{
"code": null,
"e": 695,
"s": 659,
"text": "Method #2: Using dict comprehension"
},
{
"code": null,
"e": 703,
"s": 695,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to flatten list of dictionaries # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionaryprint (\"initial dictionary\", str(ini_dict)) # code to flatten list of dictionaryres = {k: v for d in ini_dict for k, v in d.items()} # printing resultprint (\"result\", str(res))",
"e": 1043,
"s": 703,
"text": null
},
{
"code": null,
"e": 1126,
"s": 1043,
"text": "initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]\nresult {'a': 1, 'c': 3, 'b': 2}\n"
},
{
"code": null,
"e": 1151,
"s": 1126,
"text": " Method #3: Using reduce"
},
{
"code": null,
"e": 1159,
"s": 1151,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to flatten list of dictionariesfrom functools import reduce # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionaryprint (\"initial dictionary\", str(ini_dict)) # code to flatten list of dictionaryres = reduce(lambda d, src: d.update(src) or d, ini_dict, {}) # printing resultprint (\"result\", str(res))",
"e": 1537,
"s": 1159,
"text": null
},
{
"code": null,
"e": 1620,
"s": 1537,
"text": "initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]\nresult {'a': 1, 'c': 3, 'b': 2}\n"
},
{
"code": null,
"e": 1659,
"s": 1620,
"text": " Method #4: Using collections.ChainMap"
},
{
"code": null,
"e": 1667,
"s": 1659,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to flatten list of # dictionaries from collections import ChainMap # Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionaryprint (\"initial dictionary\", str(ini_dict)) # code to flatten list of dictionaryres = ChainMap(*ini_dict) # printing resultprint (\"result\", str(res))",
"e": 2016,
"s": 1667,
"text": null
},
{
"code": null,
"e": 2113,
"s": 2016,
"text": "initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]\nresult ChainMap({'a': 1}, {'b': 2}, {'c': 3})\n"
},
{
"code": null,
"e": 2129,
"s": 2113,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 2156,
"s": 2129,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2163,
"s": 2156,
"text": "Python"
},
{
"code": null,
"e": 2261,
"s": 2163,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2293,
"s": 2261,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2320,
"s": 2293,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2341,
"s": 2320,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2364,
"s": 2341,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2420,
"s": 2364,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2451,
"s": 2420,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2493,
"s": 2451,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2535,
"s": 2493,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2574,
"s": 2535,
"text": "Python | Get unique values from a list"
}
] |
semanage - Unix, Linux Command | # View SELinux user mappings
$ semanage user -l
# Allow joe to login as staff_u
$ semanage login -a -s staff_u joe
# Add file-context for everything under /web (used by restorecon)
$ semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
# Allow Apache to listen on port 81
$ semanage port -a -t http_port_t -p tcp 81 | [] |
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set – 1 | 18 Jan, 2022
Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Similarly, in Ruby, the if-else statement is used to test the specified condition.
if statement
if-else statement
if – elsif ladder
Ternary statement
if statement
If statement in Ruby is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.Syntax:
if (condition)
# statements to be executed
end
Flowchart:
Example:
Ruby
# Ruby program to illustrate if statement a = 20 # if condition to check whether# your age is enough for votingif a >= 18 puts "You are eligible to vote."end
Output:
You are eligible to vote.
if – else Statement
In this ‘if’ statement used to execute block of code when the condition is true and ‘else’ statement is used to execute a block of code when the condition is false.Syntax:
if(condition)
# code if the condition is true
else
# code if the condition is false
end
Flowchart:
Example:
Ruby
# Ruby program to illustrate# if - else statement a = 15 # if condition to check# whether age is enough for votingif a >= 18 puts "You are eligible to vote."else puts "You are not eligible to vote."
Output:
You are not eligible to vote.
If – elsif – else ladder Statement
Here, a user can decide among multiple options. ‘if’ statements are executed from the top down. As soon as one of the conditions controlling the ‘if’ is true, the statement associated with that ‘if’ is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.Syntax:
if(condition1)
# code to be executed if condition1is true
elsif(condition2)
# code to be executed if condition2 is true
else(condition3)
# code to be executed if condition3 is true
end
Flowchart:
Example:
Ruby
# Ruby program to illustrate the# if - else - if statement a = 78 if a < 50 puts "Student is failed" elsif a >= 50 && a <= 60 puts "Student gets D grade" elsif a >= 70 && a <= 80 puts "Student gets B grade" elsif a >= 80 && a <= 90 puts "Student gets A grade" elsif a >= 90 && a <= 100 puts "Student gets A+ grade" end
Output:
Student gets B grade
Ternary Statement
In Ruby ternary statement is also termed as the shortened if statement. It will first evaluate the expression for true or false value and then execute one of the statements. If the expression is true, then the true statement is executed else false statement will get executed.Syntax:
test-expression ? if-true-expression : if-false-expression
Example:
Ruby
# Ruby program to illustrate the# Ternary statement # variablevar = 5; # ternary statementa = (var > 2) ? true : false ;puts a
Output:
true
saurabh1990aror
sumitgumber28
Ruby-Basics
Ruby-Decision-Making
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Ruby | String capitalize() Method | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 547,
"s": 52,
"text": "Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Similarly, in Ruby, the if-else statement is used to test the specified condition. "
},
{
"code": null,
"e": 562,
"s": 549,
"text": "if statement"
},
{
"code": null,
"e": 580,
"s": 562,
"text": "if-else statement"
},
{
"code": null,
"e": 598,
"s": 580,
"text": "if – elsif ladder"
},
{
"code": null,
"e": 616,
"s": 598,
"text": "Ternary statement"
},
{
"code": null,
"e": 631,
"s": 618,
"text": "if statement"
},
{
"code": null,
"e": 841,
"s": 631,
"text": "If statement in Ruby is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.Syntax: "
},
{
"code": null,
"e": 899,
"s": 841,
"text": "if (condition) \n \n # statements to be executed \n \nend "
},
{
"code": null,
"e": 911,
"s": 899,
"text": "Flowchart: "
},
{
"code": null,
"e": 921,
"s": 911,
"text": "Example: "
},
{
"code": null,
"e": 926,
"s": 921,
"text": "Ruby"
},
{
"code": "# Ruby program to illustrate if statement a = 20 # if condition to check whether# your age is enough for votingif a >= 18 puts \"You are eligible to vote.\"end",
"e": 1085,
"s": 926,
"text": null
},
{
"code": null,
"e": 1095,
"s": 1085,
"text": "Output: "
},
{
"code": null,
"e": 1121,
"s": 1095,
"text": "You are eligible to vote."
},
{
"code": null,
"e": 1143,
"s": 1123,
"text": "if – else Statement"
},
{
"code": null,
"e": 1317,
"s": 1143,
"text": "In this ‘if’ statement used to execute block of code when the condition is true and ‘else’ statement is used to execute a block of code when the condition is false.Syntax: "
},
{
"code": null,
"e": 1425,
"s": 1317,
"text": "if(condition) \n\n # code if the condition is true \n\nelse \n\n # code if the condition is false \nend "
},
{
"code": null,
"e": 1437,
"s": 1425,
"text": "Flowchart: "
},
{
"code": null,
"e": 1448,
"s": 1437,
"text": "Example: "
},
{
"code": null,
"e": 1453,
"s": 1448,
"text": "Ruby"
},
{
"code": "# Ruby program to illustrate# if - else statement a = 15 # if condition to check# whether age is enough for votingif a >= 18 puts \"You are eligible to vote.\"else puts \"You are not eligible to vote.\"",
"e": 1654,
"s": 1453,
"text": null
},
{
"code": null,
"e": 1664,
"s": 1654,
"text": "Output: "
},
{
"code": null,
"e": 1694,
"s": 1664,
"text": "You are not eligible to vote."
},
{
"code": null,
"e": 1731,
"s": 1696,
"text": "If – elsif – else ladder Statement"
},
{
"code": null,
"e": 2074,
"s": 1731,
"text": "Here, a user can decide among multiple options. ‘if’ statements are executed from the top down. As soon as one of the conditions controlling the ‘if’ is true, the statement associated with that ‘if’ is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.Syntax: "
},
{
"code": null,
"e": 2278,
"s": 2074,
"text": "if(condition1) \n\n# code to be executed if condition1is true\n \nelsif(condition2)\n \n# code to be executed if condition2 is true \n\nelse(condition3) \n\n# code to be executed if condition3 is true \nend "
},
{
"code": null,
"e": 2290,
"s": 2278,
"text": "Flowchart: "
},
{
"code": null,
"e": 2300,
"s": 2290,
"text": "Example: "
},
{
"code": null,
"e": 2305,
"s": 2300,
"text": "Ruby"
},
{
"code": "# Ruby program to illustrate the# if - else - if statement a = 78 if a < 50 puts \"Student is failed\" elsif a >= 50 && a <= 60 puts \"Student gets D grade\" elsif a >= 70 && a <= 80 puts \"Student gets B grade\" elsif a >= 80 && a <= 90 puts \"Student gets A grade\" elsif a >= 90 && a <= 100 puts \"Student gets A+ grade\" end",
"e": 2651,
"s": 2305,
"text": null
},
{
"code": null,
"e": 2661,
"s": 2651,
"text": "Output: "
},
{
"code": null,
"e": 2682,
"s": 2661,
"text": "Student gets B grade"
},
{
"code": null,
"e": 2702,
"s": 2684,
"text": "Ternary Statement"
},
{
"code": null,
"e": 2987,
"s": 2702,
"text": "In Ruby ternary statement is also termed as the shortened if statement. It will first evaluate the expression for true or false value and then execute one of the statements. If the expression is true, then the true statement is executed else false statement will get executed.Syntax: "
},
{
"code": null,
"e": 3047,
"s": 2987,
"text": "test-expression ? if-true-expression : if-false-expression "
},
{
"code": null,
"e": 3058,
"s": 3047,
"text": "Example: "
},
{
"code": null,
"e": 3063,
"s": 3058,
"text": "Ruby"
},
{
"code": "# Ruby program to illustrate the# Ternary statement # variablevar = 5; # ternary statementa = (var > 2) ? true : false ;puts a",
"e": 3190,
"s": 3063,
"text": null
},
{
"code": null,
"e": 3200,
"s": 3190,
"text": "Output: "
},
{
"code": null,
"e": 3205,
"s": 3200,
"text": "true"
},
{
"code": null,
"e": 3223,
"s": 3207,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 3237,
"s": 3223,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3249,
"s": 3237,
"text": "Ruby-Basics"
},
{
"code": null,
"e": 3270,
"s": 3249,
"text": "Ruby-Decision-Making"
},
{
"code": null,
"e": 3275,
"s": 3270,
"text": "Ruby"
},
{
"code": null,
"e": 3373,
"s": 3275,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3419,
"s": 3373,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 3446,
"s": 3419,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 3470,
"s": 3446,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 3501,
"s": 3470,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 3544,
"s": 3501,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 3566,
"s": 3544,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 3610,
"s": 3566,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 3640,
"s": 3610,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 3658,
"s": 3640,
"text": "Ruby | Data Types"
}
] |
ReactJS Chakra-UI Card Component | 30 Jul, 2021
Chakra UI is a modern component library for React created by Segun Adebayo to build front-end applications. It provides accessibility, simplicity, and modularity making it a powerful library with over 50 components. Chakra UI comes with concise and scrutable documentation making it easier to build an accessible component and speed up the building process. At the time of writing the Chakra-UI GitHub repository has 19.4k stars and has been forked 1.6k times. If you are a fan of emoticon and styled-system then adopting Chakra is a no-brainer, the library is built using those technologies as the foundation. In this article, we’ll learn how to create a card component using Chakra-UI.
Approach: Since Chakra UI doesn’t have an existing card component, we will be using their flexible and abstract components to create the complete card.
In the App.js file, import Box, Image, Stack, Badge, Flex, Spacer and Text components.
Box: It is the most abstract component, it renders a div element by default. Can easily create responsive styles and pass styles via props.
Image: The image component is used for displaying images as well as for styling and adding responsive styles,
Stack: It is a layout component used to stack elements together and apply a space between them.
Flex and Spacer: Used to create a responsive layout where the child elements occupy 100% of the width keeping the equal spacing between them.
Text: It is used to render text and paragraphs within an interface.
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 Chakra UI modules using the following command:npm i @chakra-ui/react @emotion/react@^11
@emotion/styled@^11 framer-motion@^4
Step 3: After creating the ReactJS application, Install Chakra UI modules using the following command:
npm i @chakra-ui/react @emotion/react@^11
@emotion/styled@^11 framer-motion@^4
Project Structure: It will look like the following.
Project Structure
Below is the implementation of the above approach:
Example:
App.js
import React from "react";import { Box, Image, Badge, Text, Stack, useColorMode, Button, Flex, Spacer } from "@chakra-ui/react"; function App() { // Hook to toggle dark mode const { colorMode, toggleColorMode} = useColorMode(); return ( <div className="app"> <Button onClick={toggleColorMode} mt={5}> Toggle { colorMode === "light" ? "Dark" : "Light"} </Button> <Box w="300px" rounded="20px" overflow="hidden" bg={ colorMode === "dark" ? "gray .700": "gray.200"} mt={10}> <Image src="https://media.geeksforgeeks.org/wp-content/uploads/20210727094649/img1.jpg" alt="Card Image" boxSize="300px"> </Image> <Box p={5}> <Stack align="center"> <Badge variant="solid" colorScheme="green" rounded="full" px={2}> GeeksForGeeks </Badge> </Stack> <Stack align="center"> <Text as="h2" fontWeight="normal" my={2} > A Computer Science Portal for Geeks </Text> <Text fontWeight="light"> A platform for students to study CSE concepts. </Text> </Stack> <Flex> <Spacer /> <Button variant="solid" colorScheme="green" size="sm"> Learn More </Button> </Flex> </Box> </Box> </div> );} export default App;
For Chakra UI to work, you need to set up the ChakraProvider at the root of your application.
index.js
import React from 'react';import ReactDOM from 'react-dom';import App from './App';import { ChakraProvider, ColorModeScript } from "@chakra-ui/react"; ReactDOM.render( <React.StrictMode> <ChakraProvider> <ColorModeScript initialColorMode="light"></ColorModeScript> <App /> </ChakraProvider> </React.StrictMode>, document.getElementById('root'));
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://chakra-ui.com/docs/getting-started
Chakra UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
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?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 741,
"s": 53,
"text": "Chakra UI is a modern component library for React created by Segun Adebayo to build front-end applications. It provides accessibility, simplicity, and modularity making it a powerful library with over 50 components. Chakra UI comes with concise and scrutable documentation making it easier to build an accessible component and speed up the building process. At the time of writing the Chakra-UI GitHub repository has 19.4k stars and has been forked 1.6k times. If you are a fan of emoticon and styled-system then adopting Chakra is a no-brainer, the library is built using those technologies as the foundation. In this article, we’ll learn how to create a card component using Chakra-UI."
},
{
"code": null,
"e": 894,
"s": 741,
"text": "Approach: Since Chakra UI doesn’t have an existing card component, we will be using their flexible and abstract components to create the complete card. "
},
{
"code": null,
"e": 981,
"s": 894,
"text": "In the App.js file, import Box, Image, Stack, Badge, Flex, Spacer and Text components."
},
{
"code": null,
"e": 1121,
"s": 981,
"text": "Box: It is the most abstract component, it renders a div element by default. Can easily create responsive styles and pass styles via props."
},
{
"code": null,
"e": 1231,
"s": 1121,
"text": "Image: The image component is used for displaying images as well as for styling and adding responsive styles,"
},
{
"code": null,
"e": 1327,
"s": 1231,
"text": "Stack: It is a layout component used to stack elements together and apply a space between them."
},
{
"code": null,
"e": 1469,
"s": 1327,
"text": "Flex and Spacer: Used to create a responsive layout where the child elements occupy 100% of the width keeping the equal spacing between them."
},
{
"code": null,
"e": 1537,
"s": 1469,
"text": "Text: It is used to render text and paragraphs within an interface."
},
{
"code": null,
"e": 1589,
"s": 1539,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 1684,
"s": 1589,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 1748,
"s": 1684,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1780,
"s": 1748,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1893,
"s": 1780,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 1993,
"s": 1893,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 2007,
"s": 1993,
"text": "cd foldername"
},
{
"code": null,
"e": 2193,
"s": 2007,
"text": "Step 3: After creating the ReactJS application, Install Chakra UI modules using the following command:npm i @chakra-ui/react @emotion/react@^11 \n @emotion/styled@^11 framer-motion@^4"
},
{
"code": null,
"e": 2296,
"s": 2193,
"text": "Step 3: After creating the ReactJS application, Install Chakra UI modules using the following command:"
},
{
"code": null,
"e": 2380,
"s": 2296,
"text": "npm i @chakra-ui/react @emotion/react@^11 \n @emotion/styled@^11 framer-motion@^4"
},
{
"code": null,
"e": 2432,
"s": 2380,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2450,
"s": 2432,
"text": "Project Structure"
},
{
"code": null,
"e": 2501,
"s": 2450,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2510,
"s": 2501,
"text": "Example:"
},
{
"code": null,
"e": 2517,
"s": 2510,
"text": "App.js"
},
{
"code": "import React from \"react\";import { Box, Image, Badge, Text, Stack, useColorMode, Button, Flex, Spacer } from \"@chakra-ui/react\"; function App() { // Hook to toggle dark mode const { colorMode, toggleColorMode} = useColorMode(); return ( <div className=\"app\"> <Button onClick={toggleColorMode} mt={5}> Toggle { colorMode === \"light\" ? \"Dark\" : \"Light\"} </Button> <Box w=\"300px\" rounded=\"20px\" overflow=\"hidden\" bg={ colorMode === \"dark\" ? \"gray .700\": \"gray.200\"} mt={10}> <Image src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210727094649/img1.jpg\" alt=\"Card Image\" boxSize=\"300px\"> </Image> <Box p={5}> <Stack align=\"center\"> <Badge variant=\"solid\" colorScheme=\"green\" rounded=\"full\" px={2}> GeeksForGeeks </Badge> </Stack> <Stack align=\"center\"> <Text as=\"h2\" fontWeight=\"normal\" my={2} > A Computer Science Portal for Geeks </Text> <Text fontWeight=\"light\"> A platform for students to study CSE concepts. </Text> </Stack> <Flex> <Spacer /> <Button variant=\"solid\" colorScheme=\"green\" size=\"sm\"> Learn More </Button> </Flex> </Box> </Box> </div> );} export default App;",
"e": 3946,
"s": 2517,
"text": null
},
{
"code": null,
"e": 4040,
"s": 3946,
"text": "For Chakra UI to work, you need to set up the ChakraProvider at the root of your application."
},
{
"code": null,
"e": 4049,
"s": 4040,
"text": "index.js"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom';import App from './App';import { ChakraProvider, ColorModeScript } from \"@chakra-ui/react\"; ReactDOM.render( <React.StrictMode> <ChakraProvider> <ColorModeScript initialColorMode=\"light\"></ColorModeScript> <App /> </ChakraProvider> </React.StrictMode>, document.getElementById('root'));",
"e": 4415,
"s": 4049,
"text": null
},
{
"code": null,
"e": 4528,
"s": 4415,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 4538,
"s": 4528,
"text": "npm start"
},
{
"code": null,
"e": 4637,
"s": 4538,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 4691,
"s": 4637,
"text": "Reference: https://chakra-ui.com/docs/getting-started"
},
{
"code": null,
"e": 4701,
"s": 4691,
"text": "Chakra UI"
},
{
"code": null,
"e": 4717,
"s": 4701,
"text": "React-Questions"
},
{
"code": null,
"e": 4725,
"s": 4717,
"text": "ReactJS"
},
{
"code": null,
"e": 4742,
"s": 4725,
"text": "Web Technologies"
},
{
"code": null,
"e": 4840,
"s": 4742,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4878,
"s": 4840,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 4905,
"s": 4878,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 4944,
"s": 4905,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 4996,
"s": 4944,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 5035,
"s": 4996,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 5068,
"s": 5035,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5130,
"s": 5068,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5191,
"s": 5130,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5241,
"s": 5191,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Find size of largest subset with bitwise AND greater than their bitwise XOR - GeeksforGeeks | 13 Dec, 2021
Given an array arr[] of N integers, the task is to find the size of the largest subset such that the bitwise AND of all elements of the subset is greater than the bitwise XOR of all elements of the subset.
Example:
Input: arr[] = {1, 2, 3, 4, 5}Output: 2Explanation: The subset {2, 3} has the bitwise AND of all elements as 2 while the bitwise XOR of all elements os 1. Hence, bitwise AND > bitwise XOR. Therefore, the required size of the subset is 2 which is the maximum possible. Another example of a valid subset is {4, 5}.
Input: arr[] = {24, 20, 18, 17, 16}Output: 4
Approach: The given problem can be solved by generating all the possible subsets of the given set using a recursive approach and maintaining the value of bitwise AND and bitwise XOR of each and every subset. The required answer will be the maximum size of the subset such that it’s bitwise AND > it’s bitwise XOR.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Recursive function to iterate over all// the subsets of the given array and return// the maximum size of subset such that the// bitwise AND > bitwise OR of all elementsint maxSizeSubset( int* arr, int N, int bitwiseXOR, int bitwiseAND, int i, int len = 0){ // Stores the maximum length of subset int ans = INT_MIN; // Update ans if (bitwiseAND > bitwiseXOR) { ans = len; } // Base Case if (i == N) { return ans; } // Recursive call excluding the // ith element of the given array ans = max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)); // Recursive call including the ith element // of the given array ans = max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)); // Return Answer return ans;} // Driver Codeint main(){ int arr[] = { 24, 20, 18, 17, 16 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxSizeSubset( arr, N, 0, pow(2, 10) - 1, 0); return 0;}
// Java program for the above approachimport java.util.*;class GFG { // Recursive function to iterate over all// the subsets of the given array and return// the maximum size of subset such that the// bitwise AND > bitwise OR of all elementsstatic int maxSizeSubset( int[] arr, int N, int bitwiseXOR, int bitwiseAND, int i, int len){ // Stores the maximum length of subset int ans = Integer.MIN_VALUE; // Update ans if (bitwiseAND > bitwiseXOR) { ans = len; } // Base Case if (i == N) { return ans; } // Recursive call excluding the // ith element of the given array ans = Math.max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)); // Recursive call including the ith element // of the given array ans = Math.max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)); // Return Answer return ans;} // Driver Codepublic static void main (String[] args) { int arr[] = { 24, 20, 18, 17, 16 }; int N = arr.length; System.out.println(maxSizeSubset(arr, N, 0, (int)Math.pow(2, 10) - 1, 0, 0));}} // This code is contributed by target_2.
# Python Program to implement# the above approachimport sys # Recursive function to iterate over all# the subsets of the given array and return# the maximum size of subset such that the# bitwise AND > bitwise OR of all elementsdef maxSizeSubset(arr, N, bitwiseXOR, bitwiseAND, i, len) : # Stores the maximum length of subset ans = -sys.maxsize - 1 # Update ans if (bitwiseAND > bitwiseXOR) : ans = len # Base Case if (i == N) : return ans # Recursive call excluding the # ith element of the given array ans = max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)) # Recursive call including the ith element # of the given array ans = max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)) # Return Answer return ans # Driver Code arr = [ 24, 20, 18, 17, 16 ]N = len(arr) print(maxSizeSubset(arr, N, 0, pow(2, 10) - 1, 0, 0)) # This code is contributed by sanjoy_62.
// C# program for the above approachusing System;class GFG { // Recursive function to iterate over all// the subsets of the given array and return// the maximum size of subset such that the// bitwise AND > bitwise OR of all elementsstatic int maxSizeSubset( int []arr, int N, int bitwiseXOR, int bitwiseAND, int i, int len){ // Stores the maximum length of subset int ans = Int32.MinValue; // Update ans if (bitwiseAND > bitwiseXOR) { ans = len; } // Base Case if (i == N) { return ans; } // Recursive call excluding the // ith element of the given array ans = Math.Max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)); // Recursive call including the ith element // of the given array ans = Math.Max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)); // Return Answer return ans;} // Driver Codepublic static void Main () { int []arr = { 24, 20, 18, 17, 16 }; int N = arr.Length; Console.Write(maxSizeSubset(arr, N, 0, (int)Math.Pow(2, 10) - 1, 0, 0));}} // This code is contributed by Samim Hossain Mondal.
<script> // JavaScript Program to implement // the above approach // Recursive function to iterate over all // the subsets of the given array and return // the maximum size of subset such that the // bitwise AND > bitwise OR of all elements function maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i, len = 0) { // Stores the maximum length of subset let ans = Number.MIN_VALUE; // Update ans if (bitwiseAND > bitwiseXOR) { ans = len; } // Base Case if (i == N) { return ans; } // Recursive call excluding the // ith element of the given array ans = Math.max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)); // Recursive call including the ith element // of the given array ans = Math.max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)); // Return Answer return ans; } // Driver Code let arr = [24, 20, 18, 17, 16]; let N = arr.length; document.write(maxSizeSubset( arr, N, 0, Math.pow(2, 10) - 1, 0)) // This code is contributed by Potta Lokesh </script>
4
Time Complexity: O(2N)Auxiliary Space: O(1)
target_2
lokeshpotta20
samim2000
sanjoy_62
Bitwise-AND
Bitwise-XOR
subset
Arrays
Bit Magic
Arrays
Bit Magic
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division | [
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 25002,
"s": 24796,
"text": "Given an array arr[] of N integers, the task is to find the size of the largest subset such that the bitwise AND of all elements of the subset is greater than the bitwise XOR of all elements of the subset."
},
{
"code": null,
"e": 25011,
"s": 25002,
"text": "Example:"
},
{
"code": null,
"e": 25324,
"s": 25011,
"text": "Input: arr[] = {1, 2, 3, 4, 5}Output: 2Explanation: The subset {2, 3} has the bitwise AND of all elements as 2 while the bitwise XOR of all elements os 1. Hence, bitwise AND > bitwise XOR. Therefore, the required size of the subset is 2 which is the maximum possible. Another example of a valid subset is {4, 5}."
},
{
"code": null,
"e": 25369,
"s": 25324,
"text": "Input: arr[] = {24, 20, 18, 17, 16}Output: 4"
},
{
"code": null,
"e": 25683,
"s": 25369,
"text": "Approach: The given problem can be solved by generating all the possible subsets of the given set using a recursive approach and maintaining the value of bitwise AND and bitwise XOR of each and every subset. The required answer will be the maximum size of the subset such that it’s bitwise AND > it’s bitwise XOR."
},
{
"code": null,
"e": 25734,
"s": 25683,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25738,
"s": 25734,
"text": "C++"
},
{
"code": null,
"e": 25743,
"s": 25738,
"text": "Java"
},
{
"code": null,
"e": 25751,
"s": 25743,
"text": "Python3"
},
{
"code": null,
"e": 25754,
"s": 25751,
"text": "C#"
},
{
"code": null,
"e": 25765,
"s": 25754,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Recursive function to iterate over all// the subsets of the given array and return// the maximum size of subset such that the// bitwise AND > bitwise OR of all elementsint maxSizeSubset( int* arr, int N, int bitwiseXOR, int bitwiseAND, int i, int len = 0){ // Stores the maximum length of subset int ans = INT_MIN; // Update ans if (bitwiseAND > bitwiseXOR) { ans = len; } // Base Case if (i == N) { return ans; } // Recursive call excluding the // ith element of the given array ans = max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)); // Recursive call including the ith element // of the given array ans = max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)); // Return Answer return ans;} // Driver Codeint main(){ int arr[] = { 24, 20, 18, 17, 16 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxSizeSubset( arr, N, 0, pow(2, 10) - 1, 0); return 0;}",
"e": 27001,
"s": 25765,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG { // Recursive function to iterate over all// the subsets of the given array and return// the maximum size of subset such that the// bitwise AND > bitwise OR of all elementsstatic int maxSizeSubset( int[] arr, int N, int bitwiseXOR, int bitwiseAND, int i, int len){ // Stores the maximum length of subset int ans = Integer.MIN_VALUE; // Update ans if (bitwiseAND > bitwiseXOR) { ans = len; } // Base Case if (i == N) { return ans; } // Recursive call excluding the // ith element of the given array ans = Math.max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)); // Recursive call including the ith element // of the given array ans = Math.max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)); // Return Answer return ans;} // Driver Codepublic static void main (String[] args) { int arr[] = { 24, 20, 18, 17, 16 }; int N = arr.length; System.out.println(maxSizeSubset(arr, N, 0, (int)Math.pow(2, 10) - 1, 0, 0));}} // This code is contributed by target_2.",
"e": 28304,
"s": 27001,
"text": null
},
{
"code": "# Python Program to implement# the above approachimport sys # Recursive function to iterate over all# the subsets of the given array and return# the maximum size of subset such that the# bitwise AND > bitwise OR of all elementsdef maxSizeSubset(arr, N, bitwiseXOR, bitwiseAND, i, len) : # Stores the maximum length of subset ans = -sys.maxsize - 1 # Update ans if (bitwiseAND > bitwiseXOR) : ans = len # Base Case if (i == N) : return ans # Recursive call excluding the # ith element of the given array ans = max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)) # Recursive call including the ith element # of the given array ans = max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)) # Return Answer return ans # Driver Code arr = [ 24, 20, 18, 17, 16 ]N = len(arr) print(maxSizeSubset(arr, N, 0, pow(2, 10) - 1, 0, 0)) # This code is contributed by sanjoy_62.",
"e": 29476,
"s": 28304,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG { // Recursive function to iterate over all// the subsets of the given array and return// the maximum size of subset such that the// bitwise AND > bitwise OR of all elementsstatic int maxSizeSubset( int []arr, int N, int bitwiseXOR, int bitwiseAND, int i, int len){ // Stores the maximum length of subset int ans = Int32.MinValue; // Update ans if (bitwiseAND > bitwiseXOR) { ans = len; } // Base Case if (i == N) { return ans; } // Recursive call excluding the // ith element of the given array ans = Math.Max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)); // Recursive call including the ith element // of the given array ans = Math.Max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)); // Return Answer return ans;} // Driver Codepublic static void Main () { int []arr = { 24, 20, 18, 17, 16 }; int N = arr.Length; Console.Write(maxSizeSubset(arr, N, 0, (int)Math.Pow(2, 10) - 1, 0, 0));}} // This code is contributed by Samim Hossain Mondal.",
"e": 30762,
"s": 29476,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach // Recursive function to iterate over all // the subsets of the given array and return // the maximum size of subset such that the // bitwise AND > bitwise OR of all elements function maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i, len = 0) { // Stores the maximum length of subset let ans = Number.MIN_VALUE; // Update ans if (bitwiseAND > bitwiseXOR) { ans = len; } // Base Case if (i == N) { return ans; } // Recursive call excluding the // ith element of the given array ans = Math.max(ans, maxSizeSubset( arr, N, bitwiseXOR, bitwiseAND, i + 1, len)); // Recursive call including the ith element // of the given array ans = Math.max(ans, maxSizeSubset( arr, N, (arr[i] ^ bitwiseXOR), (arr[i] & bitwiseAND), i + 1, len + 1)); // Return Answer return ans; } // Driver Code let arr = [24, 20, 18, 17, 16]; let N = arr.length; document.write(maxSizeSubset( arr, N, 0, Math.pow(2, 10) - 1, 0)) // This code is contributed by Potta Lokesh </script>",
"e": 32210,
"s": 30762,
"text": null
},
{
"code": null,
"e": 32212,
"s": 32210,
"text": "4"
},
{
"code": null,
"e": 32256,
"s": 32212,
"text": "Time Complexity: O(2N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32265,
"s": 32256,
"text": "target_2"
},
{
"code": null,
"e": 32279,
"s": 32265,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 32289,
"s": 32279,
"text": "samim2000"
},
{
"code": null,
"e": 32299,
"s": 32289,
"text": "sanjoy_62"
},
{
"code": null,
"e": 32311,
"s": 32299,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 32323,
"s": 32311,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 32330,
"s": 32323,
"text": "subset"
},
{
"code": null,
"e": 32337,
"s": 32330,
"text": "Arrays"
},
{
"code": null,
"e": 32347,
"s": 32337,
"text": "Bit Magic"
},
{
"code": null,
"e": 32354,
"s": 32347,
"text": "Arrays"
},
{
"code": null,
"e": 32364,
"s": 32354,
"text": "Bit Magic"
},
{
"code": null,
"e": 32371,
"s": 32364,
"text": "subset"
},
{
"code": null,
"e": 32469,
"s": 32371,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32494,
"s": 32469,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32514,
"s": 32494,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 32552,
"s": 32514,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32637,
"s": 32552,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 32686,
"s": 32637,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32713,
"s": 32686,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 32759,
"s": 32713,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 32827,
"s": 32759,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 32856,
"s": 32827,
"text": "Count set bits in an integer"
}
] |
COBOL - Internal Sort | Sorting of data in a file or merging of two or more files is a common necessity in almost all business-oriented applications. Sorting is used for arranging records either in ascending or descending order, so that sequential processing can be performed. There are two techniques which are used for sorting files in COBOL −
External sort is used to sort files by using the SORT utility in JCL. We have discussed this in the JCL chapter. As of now, we will focus on internal sort.
External sort is used to sort files by using the SORT utility in JCL. We have discussed this in the JCL chapter. As of now, we will focus on internal sort.
Internal sort is used to sort files within a COBOL program. SORT verb is used to sort a file.
Internal sort is used to sort files within a COBOL program. SORT verb is used to sort a file.
Three files are used in the sort process in COBOL −
Input file is the file which we have to sort either in ascending or descending order.
Input file is the file which we have to sort either in ascending or descending order.
Work file is used to hold records while the sort process is in progress. Input file records are transferred to the work file for the sorting process. This file should be defined in the File-Section under SD entry.
Work file is used to hold records while the sort process is in progress. Input file records are transferred to the work file for the sorting process. This file should be defined in the File-Section under SD entry.
Output file is the file which we get after the sorting process. It is the final output of the Sort verb.
Output file is the file which we get after the sorting process. It is the final output of the Sort verb.
Following is the syntax to sort a file −
SORT work-file ON ASCENDING KEY rec-key1
[ON DESCENDING KEY rec-key2]
USING input-file GIVING output-file.
SORT performs the following operations −
Opens work-file in I-O mode, input-file in the INPUT mode and output-file in the OUTPUT mode.
Opens work-file in I-O mode, input-file in the INPUT mode and output-file in the OUTPUT mode.
Transfers the records present in the input-file to the work-file.
Transfers the records present in the input-file to the work-file.
Sorts the SORT-FILE in ascending/descending sequence by rec-key.
Sorts the SORT-FILE in ascending/descending sequence by rec-key.
Transfers the sorted records from the work-file to the output-file.
Transfers the sorted records from the work-file to the output-file.
Closes the input-file and the output-file and deletes the work-file.
Closes the input-file and the output-file and deletes the work-file.
Example
In the following example, INPUT is the input file which needs to be sorted in ascending order −
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INPUT ASSIGN TO IN.
SELECT OUTPUT ASSIGN TO OUT.
SELECT WORK ASSIGN TO WRK.
DATA DIVISION.
FILE SECTION.
FD INPUT.
01 INPUT-STUDENT.
05 STUDENT-ID-I PIC 9(5).
05 STUDENT-NAME-I PIC A(25).
FD OUTPUT.
01 OUTPUT-STUDENT.
05 STUDENT-ID-O PIC 9(5).
05 STUDENT-NAME-O PIC A(25).
SD WORK.
01 WORK-STUDENT.
05 STUDENT-ID-W PIC 9(5).
05 STUDENT-NAME-W PIC A(25).
PROCEDURE DIVISION.
SORT WORK ON ASCENDING KEY STUDENT-ID-O
USING INPUT GIVING OUTPUT.
DISPLAY 'Sort Successful'.
STOP RUN.
JCL to execute the above COBOL program −
//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
//STEP1 EXEC PGM = HELLO
//IN DD DSN = INPUT-FILE-NAME,DISP = SHR
//OUT DD DSN = OUTPUT-FILE-NAME,DISP = SHR
//WRK DD DSN = &&TEMP
When you compile and execute the above program, it produces the following result −
Sort Successful
Two or more identically sequenced files are combined using Merge statement. Files used in the merge process −
Input Files − Input-1, Input-2
Work File
Output File
Following is the syntax to merge two or more files −
MERGE work-file ON ASCENDING KEY rec-key1
[ON DESCENDING KEY rec-key2]
USING input-1, input-2 GIVING output-file.
Merge performs the following operations −
Opens the work-file in I-O mode, input-files in the INPUT mode and output-file in the OUTPUT mode.
Opens the work-file in I-O mode, input-files in the INPUT mode and output-file in the OUTPUT mode.
Transfers the records present in the input-files to the work-file.
Transfers the records present in the input-files to the work-file.
Sorts the SORT-FILE in ascending/descending sequence by rec-key.
Sorts the SORT-FILE in ascending/descending sequence by rec-key.
Transfers the sorted records from the work-file to the output-file.
Transfers the sorted records from the work-file to the output-file.
Closes the input-file and the output-file and deletes the work-file.
Closes the input-file and the output-file and deletes the work-file.
Example
In the following example, INPUT1 and INPUT2 are the input files which are to be merged in ascending order −
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INPUT1 ASSIGN TO IN1.
SELECT INPUT2 ASSIGN TO IN2.
SELECT OUTPUT ASSIGN TO OUT.
SELECT WORK ASSIGN TO WRK.
DATA DIVISION.
FILE SECTION.
FD INPUT1.
01 INPUT1-STUDENT.
05 STUDENT-ID-I1 PIC 9(5).
05 STUDENT-NAME-I1 PIC A(25).
FD INPUT2.
01 INPUT2-STUDENT.
05 STUDENT-ID-I2 PIC 9(5).
05 STUDENT-NAME-I2 PIC A(25).
FD OUTPUT.
01 OUTPUT-STUDENT.
05 STUDENT-ID-O PIC 9(5).
05 STUDENT-NAME-O PIC A(25).
SD WORK.
01 WORK-STUDENT.
05 STUDENT-ID-W PIC 9(5).
05 STUDENT-NAME-W PIC A(25).
PROCEDURE DIVISION.
MERGE WORK ON ASCENDING KEY STUDENT-ID-O
USING INPUT1, INPUT2 GIVING OUTPUT.
DISPLAY 'Merge Successful'.
STOP RUN.
JCL to execute the above COBOL program −
//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
//STEP1 EXEC PGM = HELLO
//IN1 DD DSN=INPUT1-FILE-NAME,DISP=SHR
//IN2 DD DSN=INPUT2-FILE-NAME,DISP=SHR
//OUT DD DSN = OUTPUT-FILE-NAME,DISP=SHR
//WRK DD DSN = &&TEMP
When you compile and execute the above program, it produces the following result −
Merge Successful
12 Lectures
2.5 hours
Nishant Malik
33 Lectures
3.5 hours
Craig Kenneth Kaercher
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2344,
"s": 2022,
"text": "Sorting of data in a file or merging of two or more files is a common necessity in almost all business-oriented applications. Sorting is used for arranging records either in ascending or descending order, so that sequential processing can be performed. There are two techniques which are used for sorting files in COBOL −"
},
{
"code": null,
"e": 2500,
"s": 2344,
"text": "External sort is used to sort files by using the SORT utility in JCL. We have discussed this in the JCL chapter. As of now, we will focus on internal sort."
},
{
"code": null,
"e": 2656,
"s": 2500,
"text": "External sort is used to sort files by using the SORT utility in JCL. We have discussed this in the JCL chapter. As of now, we will focus on internal sort."
},
{
"code": null,
"e": 2750,
"s": 2656,
"text": "Internal sort is used to sort files within a COBOL program. SORT verb is used to sort a file."
},
{
"code": null,
"e": 2844,
"s": 2750,
"text": "Internal sort is used to sort files within a COBOL program. SORT verb is used to sort a file."
},
{
"code": null,
"e": 2896,
"s": 2844,
"text": "Three files are used in the sort process in COBOL −"
},
{
"code": null,
"e": 2982,
"s": 2896,
"text": "Input file is the file which we have to sort either in ascending or descending order."
},
{
"code": null,
"e": 3068,
"s": 2982,
"text": "Input file is the file which we have to sort either in ascending or descending order."
},
{
"code": null,
"e": 3282,
"s": 3068,
"text": "Work file is used to hold records while the sort process is in progress. Input file records are transferred to the work file for the sorting process. This file should be defined in the File-Section under SD entry."
},
{
"code": null,
"e": 3496,
"s": 3282,
"text": "Work file is used to hold records while the sort process is in progress. Input file records are transferred to the work file for the sorting process. This file should be defined in the File-Section under SD entry."
},
{
"code": null,
"e": 3601,
"s": 3496,
"text": "Output file is the file which we get after the sorting process. It is the final output of the Sort verb."
},
{
"code": null,
"e": 3706,
"s": 3601,
"text": "Output file is the file which we get after the sorting process. It is the final output of the Sort verb."
},
{
"code": null,
"e": 3747,
"s": 3706,
"text": "Following is the syntax to sort a file −"
},
{
"code": null,
"e": 3858,
"s": 3747,
"text": "SORT work-file ON ASCENDING KEY rec-key1\n [ON DESCENDING KEY rec-key2]\nUSING input-file GIVING output-file.\n"
},
{
"code": null,
"e": 3899,
"s": 3858,
"text": "SORT performs the following operations −"
},
{
"code": null,
"e": 3993,
"s": 3899,
"text": "Opens work-file in I-O mode, input-file in the INPUT mode and output-file in the OUTPUT mode."
},
{
"code": null,
"e": 4087,
"s": 3993,
"text": "Opens work-file in I-O mode, input-file in the INPUT mode and output-file in the OUTPUT mode."
},
{
"code": null,
"e": 4153,
"s": 4087,
"text": "Transfers the records present in the input-file to the work-file."
},
{
"code": null,
"e": 4219,
"s": 4153,
"text": "Transfers the records present in the input-file to the work-file."
},
{
"code": null,
"e": 4284,
"s": 4219,
"text": "Sorts the SORT-FILE in ascending/descending sequence by rec-key."
},
{
"code": null,
"e": 4349,
"s": 4284,
"text": "Sorts the SORT-FILE in ascending/descending sequence by rec-key."
},
{
"code": null,
"e": 4417,
"s": 4349,
"text": "Transfers the sorted records from the work-file to the output-file."
},
{
"code": null,
"e": 4485,
"s": 4417,
"text": "Transfers the sorted records from the work-file to the output-file."
},
{
"code": null,
"e": 4554,
"s": 4485,
"text": "Closes the input-file and the output-file and deletes the work-file."
},
{
"code": null,
"e": 4623,
"s": 4554,
"text": "Closes the input-file and the output-file and deletes the work-file."
},
{
"code": null,
"e": 4631,
"s": 4623,
"text": "Example"
},
{
"code": null,
"e": 4727,
"s": 4631,
"text": "In the following example, INPUT is the input file which needs to be sorted in ascending order −"
},
{
"code": null,
"e": 5434,
"s": 4727,
"text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nENVIRONMENT DIVISION.\n INPUT-OUTPUT SECTION.\n FILE-CONTROL.\n SELECT INPUT ASSIGN TO IN.\n SELECT OUTPUT ASSIGN TO OUT.\n SELECT WORK ASSIGN TO WRK.\n\nDATA DIVISION.\n FILE SECTION.\n FD INPUT.\n 01 INPUT-STUDENT.\n 05 STUDENT-ID-I PIC 9(5).\n 05 STUDENT-NAME-I PIC A(25).\n FD OUTPUT.\n 01 OUTPUT-STUDENT.\n 05 STUDENT-ID-O PIC 9(5).\n 05 STUDENT-NAME-O PIC A(25).\n SD WORK.\n 01 WORK-STUDENT.\n 05 STUDENT-ID-W PIC 9(5).\n 05 STUDENT-NAME-W PIC A(25).\n\nPROCEDURE DIVISION.\n SORT WORK ON ASCENDING KEY STUDENT-ID-O\n USING INPUT GIVING OUTPUT.\n DISPLAY 'Sort Successful'.\nSTOP RUN."
},
{
"code": null,
"e": 5475,
"s": 5434,
"text": "JCL to execute the above COBOL program −"
},
{
"code": null,
"e": 5658,
"s": 5475,
"text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO\n//IN DD DSN = INPUT-FILE-NAME,DISP = SHR\n//OUT DD DSN = OUTPUT-FILE-NAME,DISP = SHR\n//WRK DD DSN = &&TEMP"
},
{
"code": null,
"e": 5741,
"s": 5658,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 5758,
"s": 5741,
"text": "Sort Successful\n"
},
{
"code": null,
"e": 5868,
"s": 5758,
"text": "Two or more identically sequenced files are combined using Merge statement. Files used in the merge process −"
},
{
"code": null,
"e": 5899,
"s": 5868,
"text": "Input Files − Input-1, Input-2"
},
{
"code": null,
"e": 5909,
"s": 5899,
"text": "Work File"
},
{
"code": null,
"e": 5921,
"s": 5909,
"text": "Output File"
},
{
"code": null,
"e": 5974,
"s": 5921,
"text": "Following is the syntax to merge two or more files −"
},
{
"code": null,
"e": 6092,
"s": 5974,
"text": "MERGE work-file ON ASCENDING KEY rec-key1\n [ON DESCENDING KEY rec-key2]\n\nUSING input-1, input-2 GIVING output-file."
},
{
"code": null,
"e": 6134,
"s": 6092,
"text": "Merge performs the following operations −"
},
{
"code": null,
"e": 6233,
"s": 6134,
"text": "Opens the work-file in I-O mode, input-files in the INPUT mode and output-file in the OUTPUT mode."
},
{
"code": null,
"e": 6332,
"s": 6233,
"text": "Opens the work-file in I-O mode, input-files in the INPUT mode and output-file in the OUTPUT mode."
},
{
"code": null,
"e": 6399,
"s": 6332,
"text": "Transfers the records present in the input-files to the work-file."
},
{
"code": null,
"e": 6466,
"s": 6399,
"text": "Transfers the records present in the input-files to the work-file."
},
{
"code": null,
"e": 6531,
"s": 6466,
"text": "Sorts the SORT-FILE in ascending/descending sequence by rec-key."
},
{
"code": null,
"e": 6596,
"s": 6531,
"text": "Sorts the SORT-FILE in ascending/descending sequence by rec-key."
},
{
"code": null,
"e": 6664,
"s": 6596,
"text": "Transfers the sorted records from the work-file to the output-file."
},
{
"code": null,
"e": 6732,
"s": 6664,
"text": "Transfers the sorted records from the work-file to the output-file."
},
{
"code": null,
"e": 6801,
"s": 6732,
"text": "Closes the input-file and the output-file and deletes the work-file."
},
{
"code": null,
"e": 6870,
"s": 6801,
"text": "Closes the input-file and the output-file and deletes the work-file."
},
{
"code": null,
"e": 6878,
"s": 6870,
"text": "Example"
},
{
"code": null,
"e": 6986,
"s": 6878,
"text": "In the following example, INPUT1 and INPUT2 are the input files which are to be merged in ascending order −"
},
{
"code": null,
"e": 7859,
"s": 6986,
"text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nENVIRONMENT DIVISION.\n INPUT-OUTPUT SECTION.\n FILE-CONTROL.\n SELECT INPUT1 ASSIGN TO IN1.\n SELECT INPUT2 ASSIGN TO IN2.\n SELECT OUTPUT ASSIGN TO OUT.\n SELECT WORK ASSIGN TO WRK.\n\nDATA DIVISION.\n FILE SECTION.\n FD INPUT1.\n 01 INPUT1-STUDENT.\n 05 STUDENT-ID-I1 PIC 9(5).\n 05 STUDENT-NAME-I1 PIC A(25).\n FD INPUT2.\n 01 INPUT2-STUDENT.\n 05 STUDENT-ID-I2 PIC 9(5).\n 05 STUDENT-NAME-I2 PIC A(25).\n FD OUTPUT.\n 01 OUTPUT-STUDENT.\n 05 STUDENT-ID-O PIC 9(5).\n 05 STUDENT-NAME-O PIC A(25).\n SD WORK.\n 01 WORK-STUDENT.\n 05 STUDENT-ID-W PIC 9(5).\n 05 STUDENT-NAME-W PIC A(25).\n\nPROCEDURE DIVISION.\n MERGE WORK ON ASCENDING KEY STUDENT-ID-O\n USING INPUT1, INPUT2 GIVING OUTPUT.\n DISPLAY 'Merge Successful'.\nSTOP RUN."
},
{
"code": null,
"e": 7900,
"s": 7859,
"text": "JCL to execute the above COBOL program −"
},
{
"code": null,
"e": 8118,
"s": 7900,
"text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO\n//IN1 DD DSN=INPUT1-FILE-NAME,DISP=SHR\n//IN2 DD DSN=INPUT2-FILE-NAME,DISP=SHR\n//OUT DD DSN = OUTPUT-FILE-NAME,DISP=SHR\n//WRK DD DSN = &&TEMP"
},
{
"code": null,
"e": 8201,
"s": 8118,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 8219,
"s": 8201,
"text": "Merge Successful\n"
},
{
"code": null,
"e": 8254,
"s": 8219,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8269,
"s": 8254,
"text": " Nishant Malik"
},
{
"code": null,
"e": 8304,
"s": 8269,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8328,
"s": 8304,
"text": " Craig Kenneth Kaercher"
},
{
"code": null,
"e": 8335,
"s": 8328,
"text": " Print"
},
{
"code": null,
"e": 8346,
"s": 8335,
"text": " Add Notes"
}
] |
PyQt5 QListWidget – Getting Auto Scroll Margin | 06 Aug, 2020
In this article we will see how we can get auto scroll margin of the QListWidget. 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. This property holds the size of the area when auto scrolling is triggered. This property controls the size of the area at the edge of the viewport that triggers autoscrolling. The default value is 16 pixels although it can be changed with the help of setAutoScrollMargin method.
In order to do this we will use autoScrollMargin method with the list widget object.
Syntax : list_widget.autoScrollMargin()
Argument : It takes no argument
Return : It returns integer
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 80) # list widget items item1 = QListWidgetItem("PyQt5 Geeks for Geeks") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") item4 = QListWidgetItem("D") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) list_widget.addItem(item4) # setting drag and drop property list_widget.setDragDropMode(3) # setting auto scroll property list_widget.setAutoScroll(True) # setting auto scroll margin list_widget.setAutoScrollMargin(20) # setting word wrap property list_widget.setWordWrap(True) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting auto scroll margin value = list_widget.autoScrollMargin() # setting text to the label label.setText("Auto Scroll Margin : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
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
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 596,
"s": 28,
"text": "In this article we will see how we can get auto scroll margin of the QListWidget. 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. This property holds the size of the area when auto scrolling is triggered. This property controls the size of the area at the edge of the viewport that triggers autoscrolling. The default value is 16 pixels although it can be changed with the help of setAutoScrollMargin method."
},
{
"code": null,
"e": 681,
"s": 596,
"text": "In order to do this we will use autoScrollMargin method with the list widget object."
},
{
"code": null,
"e": 721,
"s": 681,
"text": "Syntax : list_widget.autoScrollMargin()"
},
{
"code": null,
"e": 753,
"s": 721,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 781,
"s": 753,
"text": "Return : It returns integer"
},
{
"code": null,
"e": 809,
"s": 781,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 80) # list widget items item1 = QListWidgetItem(\"PyQt5 Geeks for Geeks\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") item4 = QListWidgetItem(\"D\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) list_widget.addItem(item4) # setting drag and drop property list_widget.setDragDropMode(3) # setting auto scroll property list_widget.setAutoScroll(True) # setting auto scroll margin list_widget.setAutoScrollMargin(20) # setting word wrap property list_widget.setWordWrap(True) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting auto scroll margin value = list_widget.autoScrollMargin() # setting text to the label label.setText(\"Auto Scroll Margin : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2727,
"s": 809,
"text": null
},
{
"code": null,
"e": 2736,
"s": 2727,
"text": "Output :"
},
{
"code": null,
"e": 2760,
"s": 2736,
"text": "Python PyQt-QListWidget"
},
{
"code": null,
"e": 2771,
"s": 2760,
"text": "Python-gui"
},
{
"code": null,
"e": 2783,
"s": 2771,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2790,
"s": 2783,
"text": "Python"
},
{
"code": null,
"e": 2888,
"s": 2790,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2906,
"s": 2888,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2948,
"s": 2906,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2983,
"s": 2948,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3015,
"s": 2983,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3041,
"s": 3015,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3070,
"s": 3041,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3097,
"s": 3070,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3118,
"s": 3097,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3141,
"s": 3118,
"text": "Introduction To PYTHON"
}
] |
Scanner nextFloat() method in Java with Examples | 12 Oct, 2018
The nextFloat() method of java.util.Scanner class scans the next token of the input as a Float(). If the translation is successful, the scanner advances past the input that matched.
Syntax:
public float nextFloat()
Parameters: The function does not accepts any parameter.
Return Value: This function returns the Float scanned from the input.
Exceptions: The function throws three exceptions as described below:
InputMismatchException: if the next token does not matches the Float regular expression, or is out of range
NoSuchElementException: if input is exhausted
IllegalStateException: if this scanner is closed
Below programs illustrate the above function:
Program 1:
// Java program to illustrate the// nextFloat() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Float, // print found and the Float if (scanner.hasNextFloat()) { System.out.println("Found Float value :" + scanner.nextFloat()); } // if no float is found, // print "Not Found:" and the token else { System.out.println("Not found Float() value :" + scanner.next()); } } scanner.close(); }}
Not found Float() value :Gfg
Found Float value :9.0
Not found Float() value :+
Found Float value :6.0
Not found Float() value :=
Found Float value :12.0
Program 2: To demonstrate InputMismatchException
// Java program to illustrate the// nextFloat() method of Scanner class in Java// InputMismatchException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Float // print found and the Float // since the value 60 is out of range // it throws an exception System.out.println("Next Float value :" + scanner.nextFloat()); } scanner.close(); } catch (Exception e) { System.out.println("Exception thrown: " + e); } }}
Exception thrown: java.util.InputMismatchException
Program 3: To demonstrate NoSuchElementException
// Java program to illustrate the// nextFloat() method of Scanner class in Java// NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // Trying to get the next Float value // more times than the scanner // Hence it will throw exception for (int i = 0; i < 5; i++) { // if the next is a Float, // print found and the Float if (scanner.hasNextFloat()) { System.out.println("Found Float value :" + scanner.nextFloat()); } // if no Float is found, // print "Not Found:" and the token else { System.out.println("Not found Float value :" + scanner.next()); } } scanner.close(); } catch (Exception e) { System.out.println("Exception thrown: " + e); } }}
Not found Float value :Gfg
Exception thrown: java.util.NoSuchElementException
Program 4: To demonstrate IllegalStateException
// Java program to illustrate the// nextFloat() method of Scanner class in Java// IllegalStateException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); System.out.println("Scanner Closed"); System.out.println("Trying to get " + "next Float value"); while (scanner.hasNext()) { // if the next is a Float, // print found and the Float if (scanner.hasNextFloat()) { System.out.println("Found Float value :" + scanner.nextFloat()); } // if no Float is found, // print "Not Found:" and the token else { System.out.println("Not found Float value :" + scanner.next()); } } } catch (Exception e) { System.out.println("Exception thrown: " + e); } }}
Scanner Closed
Trying to get next Float value
Exception thrown: java.lang.IllegalStateException: Scanner closed
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextFloat()
Java - util package
Java-Functions
Java-Library
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Oct, 2018"
},
{
"code": null,
"e": 235,
"s": 53,
"text": "The nextFloat() method of java.util.Scanner class scans the next token of the input as a Float(). If the translation is successful, the scanner advances past the input that matched."
},
{
"code": null,
"e": 243,
"s": 235,
"text": "Syntax:"
},
{
"code": null,
"e": 268,
"s": 243,
"text": "public float nextFloat()"
},
{
"code": null,
"e": 325,
"s": 268,
"text": "Parameters: The function does not accepts any parameter."
},
{
"code": null,
"e": 395,
"s": 325,
"text": "Return Value: This function returns the Float scanned from the input."
},
{
"code": null,
"e": 464,
"s": 395,
"text": "Exceptions: The function throws three exceptions as described below:"
},
{
"code": null,
"e": 572,
"s": 464,
"text": "InputMismatchException: if the next token does not matches the Float regular expression, or is out of range"
},
{
"code": null,
"e": 618,
"s": 572,
"text": "NoSuchElementException: if input is exhausted"
},
{
"code": null,
"e": 667,
"s": 618,
"text": "IllegalStateException: if this scanner is closed"
},
{
"code": null,
"e": 713,
"s": 667,
"text": "Below programs illustrate the above function:"
},
{
"code": null,
"e": 724,
"s": 713,
"text": "Program 1:"
},
{
"code": "// Java program to illustrate the// nextFloat() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"Gfg 9 + 6 = 12.0\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Float, // print found and the Float if (scanner.hasNextFloat()) { System.out.println(\"Found Float value :\" + scanner.nextFloat()); } // if no float is found, // print \"Not Found:\" and the token else { System.out.println(\"Not found Float() value :\" + scanner.next()); } } scanner.close(); }}",
"e": 1649,
"s": 724,
"text": null
},
{
"code": null,
"e": 1803,
"s": 1649,
"text": "Not found Float() value :Gfg\nFound Float value :9.0\nNot found Float() value :+\nFound Float value :6.0\nNot found Float() value :=\nFound Float value :12.0\n"
},
{
"code": null,
"e": 1852,
"s": 1803,
"text": "Program 2: To demonstrate InputMismatchException"
},
{
"code": "// Java program to illustrate the// nextFloat() method of Scanner class in Java// InputMismatchException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg 9 + 6 = 12.0\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Float // print found and the Float // since the value 60 is out of range // it throws an exception System.out.println(\"Next Float value :\" + scanner.nextFloat()); } scanner.close(); } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}",
"e": 2746,
"s": 1852,
"text": null
},
{
"code": null,
"e": 2798,
"s": 2746,
"text": "Exception thrown: java.util.InputMismatchException\n"
},
{
"code": null,
"e": 2847,
"s": 2798,
"text": "Program 3: To demonstrate NoSuchElementException"
},
{
"code": "// Java program to illustrate the// nextFloat() method of Scanner class in Java// NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // Trying to get the next Float value // more times than the scanner // Hence it will throw exception for (int i = 0; i < 5; i++) { // if the next is a Float, // print found and the Float if (scanner.hasNextFloat()) { System.out.println(\"Found Float value :\" + scanner.nextFloat()); } // if no Float is found, // print \"Not Found:\" and the token else { System.out.println(\"Not found Float value :\" + scanner.next()); } } scanner.close(); } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}",
"e": 4094,
"s": 2847,
"text": null
},
{
"code": null,
"e": 4173,
"s": 4094,
"text": "Not found Float value :Gfg\nException thrown: java.util.NoSuchElementException\n"
},
{
"code": null,
"e": 4221,
"s": 4173,
"text": "Program 4: To demonstrate IllegalStateException"
},
{
"code": "// Java program to illustrate the// nextFloat() method of Scanner class in Java// IllegalStateException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg 9 + 6 = 12.0\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); System.out.println(\"Scanner Closed\"); System.out.println(\"Trying to get \" + \"next Float value\"); while (scanner.hasNext()) { // if the next is a Float, // print found and the Float if (scanner.hasNextFloat()) { System.out.println(\"Found Float value :\" + scanner.nextFloat()); } // if no Float is found, // print \"Not Found:\" and the token else { System.out.println(\"Not found Float value :\" + scanner.next()); } } } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}",
"e": 5528,
"s": 4221,
"text": null
},
{
"code": null,
"e": 5641,
"s": 5528,
"text": "Scanner Closed\nTrying to get next Float value\nException thrown: java.lang.IllegalStateException: Scanner closed\n"
},
{
"code": null,
"e": 5729,
"s": 5641,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextFloat()"
},
{
"code": null,
"e": 5749,
"s": 5729,
"text": "Java - util package"
},
{
"code": null,
"e": 5764,
"s": 5749,
"text": "Java-Functions"
},
{
"code": null,
"e": 5777,
"s": 5764,
"text": "Java-Library"
},
{
"code": null,
"e": 5782,
"s": 5777,
"text": "Java"
},
{
"code": null,
"e": 5787,
"s": 5782,
"text": "Java"
}
] |
Sum of degrees of all nodes of a undirected graph | 07 May, 2021
Given an edge list of a graph we have to find the sum of degree of all nodes of a undirected graph. Example
Examples:
Input : edge list : (1, 2), (2, 3), (1, 4), (2, 4)
Output : sum= 8
Brute force approach We will add the degree of each node of the graph and print the sum.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // returns the sum of degree of all// the nodes in a undirected graphint count(int edges[][2], int len, int n){ int degree[n + 1] = { 0 }; // compute the degree of each node for (int i = 0; i < len; i++) { // increase the degree of the // nodes degree[edges[i][0]]++; degree[edges[i][1]]++; } // calculate the sum of degree int sum = 0; for (int i = 1; i <= n; i++) sum += degree[i]; return sum;} // main functionint main(){ // the edge list int edges[][2] = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = sizeof(edges) / (sizeof(int) * 2), n = 4; // display the result cout << "sum = " << count(edges, len, n) << endl; return 0;}
// Java implementation of the approachclass GFG { // returns the sum of degree of all // the nodes in a undirected graph static int count(int edges[][], int len, int n) { int degree[] = new int[n + 1]; // compute the degree of each node for (int i = 0; i < len; i++) { // increase the degree of the // nodes degree[edges[i][0]]++; degree[edges[i][1]]++; } // calculate the sum of degree int sum = 0; for (int i = 1; i <= n; i++) sum += degree[i]; return sum; } // Driver code public static void main(String[] args) { // the edge list int edges[][] = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = edges.length, n = 4; // display the result System.out.println("sum = " + count(edges, len, n)); }} // This code has been contributed by 29AjayKumar
# Python 3 implementation of above approach # returns the sum of degree of all# the nodes in a undirected graphdef count(edges, len1, n): degree = [0 for i in range(n + 1)] # compute the degree of each node for i in range(len1): # increase the degree of the # nodes degree[edges[i][0]] += 1 degree[edges[i][1]] += 1 # calculate the sum of degree sum = 0 for i in range(1, n + 1, 1): sum += degree[i] return sum # main functionif __name__ == '__main__': # the edge list edges = [[1, 2], [2, 3], [1, 4], [2, 4]] len1 = len(edges) n = 4 # display the result print("sum =", count(edges, len1, n)) # This code is contributed by# Surendra_Gangwar
// C# implementation of the approachusing System; class GFG { // returns the sum of degree of all // the nodes in a undirected graph static int count(int[][] edges, int len, int n) { int[] degree = new int[n + 1]; // compute the degree of each node for (int i = 0; i < len; i++) { // increase the degree of the // nodes degree[edges[i][0]]++; degree[edges[i][1]]++; } // calculate the sum of degree int sum = 0; for (int i = 1; i <= n; i++) sum += degree[i]; return sum; } // Driver code public static void Main() { // the edge list int[][] edges = new int[][] { new int[] { 1, 2 }, new int[] { 2, 3 }, new int[] { 1, 4 }, new int[] { 2, 4 } }; int len = edges.Length, n = 4; // display the result Console.WriteLine("sum = " + count(edges, len, n)); }} // This code has been contributed by Code_Mech.
<?php// PHP implementation of above approach // Returns the sum of degree of all// the nodes in a undirected graphfunction count1($edges, $len, $n){ $degree = array_fill(0, $n + 1, 0); // compute the degree of each node for ($i = 0; $i < $len; $i++) { // increase the degree of the // nodes $degree[$edges[$i][0]]++; $degree[$edges[$i][1]]++; } // calculate the sum of degree $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += $degree[$i]; return $sum;} // Driver Code // the edge list$edges = array(array(1, 2), array(2, 3), array(1, 4), array(2, 4));$len = count($edges);$n = 4; // display the resultecho "sum = " . count1($edges, $len, $n) . "\n"; // This code is contributed by mits?>
<script> // Javascript implementation of above approach // returns the sum of degree of all// the nodes in a undirected graphfunction count(edges, len, n){ var degree = Array(n+1).fill(0); // compute the degree of each node for (var i = 0; i < len; i++) { // increase the degree of the // nodes degree[edges[i][0]]++; degree[edges[i][1]]++; } // calculate the sum of degree var sum = 0; for (var i = 1; i <= n; i++) sum += degree[i]; return sum;} // main function// the edge listvar edges = [ [ 1, 2 ], [ 2, 3 ], [ 1, 4 ], [ 2, 4 ] ];var len = edges.length, n = 4; // display the resultdocument.write( "sum = " + count(edges, len, n)); // This code is contributed by rutvik_56.</script>
Output:
sum = 8
Efficient approach If we get the number of the edges in a directed graph then we can find the sum of degree of the graph. Let us consider an graph with no edges. If we add a edge we are increasing the degree of two nodes of graph by 1, so after adding each edge the sum of degree of nodes increases by 2, hence the sum of degree is 2*e.
C++
Java
Python 3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // returns the sum of degree of all// the nodes in a undirected graphint count(int edges[][2], int len){ return 2 * len;} // main functionint main(){ // the edge list int edges[][2] = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = sizeof(edges) / (sizeof(int) * 2); // display the result cout << "sum = " << count(edges, len) << endl; return 0;}
// Java implementation for above approachclass GFG { // returns the sum of degree of all // the nodes in a undirected graph static int count(int edges[][], int len) { return 2 * len; } // Driver code public static void main(String[] args) { // the edge list int edges[][] = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = edges.length; // display the result System.out.println("sum = " + count(edges, len)); }} // This code contributed by Rajput-Ji
# Python3 implementation of above approach # returns the sum of degree of all# the nodes in a undirected graphdef count(edges, length) : return 2 * length; # Driver Codeif __name__ == "__main__" : # the edge list edges = [[ 1, 2 ], [ 2, 3 ], [ 1, 4 ], [ 2, 4 ]]; length = len(edges); # display the result print("sum = ", count(edges, length)); # This code is contributed by Ryuga
// C# implementation for above approachusing System; class GFG { // returns the sum of degree of all // the nodes in a undirected graph static int count(int[, ] edges, int len) { return 2 * len; } // Driver code public static void Main(String[] args) { // the edge list int[, ] edges = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = edges.GetLength(0); // display the result Console.WriteLine("sum = " + count(edges, len)); }} /* This code contributed by PrinciRaj1992 */
<?php// PHP implementation of above approach // returns the sum of degree of all// the nodes in a undirected graphfunction count1($edges, $len){ return 2 * $len;} // Driver Code // the edge list$edges = array(array(1, 2), array(2, 3), array(1, 4), array(2, 4));$len = sizeof($edges); // display the resultecho "sum = " . count1($edges, $len) . "\n"; // This code is contributed// by Akanksha Rai?>
<script> // Javascript implementation of above approach // returns the sum of degree of all// the nodes in a undirected graphfunction count(edges, len){ return 2 * len;} // main function// the edge listvar edges = [ [ 1, 2 ], [ 2, 3 ], [ 1, 4 ], [ 2, 4 ] ];var len = edges.length;// display the resultdocument.write( "sum = " + count(edges, len)); </script>
Output:
sum = 8
ankthon
Rajput-Ji
princiraj1992
29AjayKumar
Akanksha_Rai
Code_Mech
SURENDRA_GANGWAR
Mithun Kumar
noob2000
rutvik_56
graph-connectivity
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 164,
"s": 54,
"text": "Given an edge list of a graph we have to find the sum of degree of all nodes of a undirected graph. Example "
},
{
"code": null,
"e": 176,
"s": 164,
"text": "Examples: "
},
{
"code": null,
"e": 245,
"s": 176,
"text": "Input : edge list : (1, 2), (2, 3), (1, 4), (2, 4) \nOutput : sum= 8"
},
{
"code": null,
"e": 336,
"s": 245,
"text": "Brute force approach We will add the degree of each node of the graph and print the sum. "
},
{
"code": null,
"e": 340,
"s": 336,
"text": "C++"
},
{
"code": null,
"e": 345,
"s": 340,
"text": "Java"
},
{
"code": null,
"e": 353,
"s": 345,
"text": "Python3"
},
{
"code": null,
"e": 356,
"s": 353,
"text": "C#"
},
{
"code": null,
"e": 360,
"s": 356,
"text": "PHP"
},
{
"code": null,
"e": 371,
"s": 360,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // returns the sum of degree of all// the nodes in a undirected graphint count(int edges[][2], int len, int n){ int degree[n + 1] = { 0 }; // compute the degree of each node for (int i = 0; i < len; i++) { // increase the degree of the // nodes degree[edges[i][0]]++; degree[edges[i][1]]++; } // calculate the sum of degree int sum = 0; for (int i = 1; i <= n; i++) sum += degree[i]; return sum;} // main functionint main(){ // the edge list int edges[][2] = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = sizeof(edges) / (sizeof(int) * 2), n = 4; // display the result cout << \"sum = \" << count(edges, len, n) << endl; return 0;}",
"e": 1241,
"s": 371,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // returns the sum of degree of all // the nodes in a undirected graph static int count(int edges[][], int len, int n) { int degree[] = new int[n + 1]; // compute the degree of each node for (int i = 0; i < len; i++) { // increase the degree of the // nodes degree[edges[i][0]]++; degree[edges[i][1]]++; } // calculate the sum of degree int sum = 0; for (int i = 1; i <= n; i++) sum += degree[i]; return sum; } // Driver code public static void main(String[] args) { // the edge list int edges[][] = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = edges.length, n = 4; // display the result System.out.println(\"sum = \" + count(edges, len, n)); }} // This code has been contributed by 29AjayKumar",
"e": 2248,
"s": 1241,
"text": null
},
{
"code": "# Python 3 implementation of above approach # returns the sum of degree of all# the nodes in a undirected graphdef count(edges, len1, n): degree = [0 for i in range(n + 1)] # compute the degree of each node for i in range(len1): # increase the degree of the # nodes degree[edges[i][0]] += 1 degree[edges[i][1]] += 1 # calculate the sum of degree sum = 0 for i in range(1, n + 1, 1): sum += degree[i] return sum # main functionif __name__ == '__main__': # the edge list edges = [[1, 2], [2, 3], [1, 4], [2, 4]] len1 = len(edges) n = 4 # display the result print(\"sum =\", count(edges, len1, n)) # This code is contributed by# Surendra_Gangwar",
"e": 2971,
"s": 2248,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { // returns the sum of degree of all // the nodes in a undirected graph static int count(int[][] edges, int len, int n) { int[] degree = new int[n + 1]; // compute the degree of each node for (int i = 0; i < len; i++) { // increase the degree of the // nodes degree[edges[i][0]]++; degree[edges[i][1]]++; } // calculate the sum of degree int sum = 0; for (int i = 1; i <= n; i++) sum += degree[i]; return sum; } // Driver code public static void Main() { // the edge list int[][] edges = new int[][] { new int[] { 1, 2 }, new int[] { 2, 3 }, new int[] { 1, 4 }, new int[] { 2, 4 } }; int len = edges.Length, n = 4; // display the result Console.WriteLine(\"sum = \" + count(edges, len, n)); }} // This code has been contributed by Code_Mech.",
"e": 4063,
"s": 2971,
"text": null
},
{
"code": "<?php// PHP implementation of above approach // Returns the sum of degree of all// the nodes in a undirected graphfunction count1($edges, $len, $n){ $degree = array_fill(0, $n + 1, 0); // compute the degree of each node for ($i = 0; $i < $len; $i++) { // increase the degree of the // nodes $degree[$edges[$i][0]]++; $degree[$edges[$i][1]]++; } // calculate the sum of degree $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += $degree[$i]; return $sum;} // Driver Code // the edge list$edges = array(array(1, 2), array(2, 3), array(1, 4), array(2, 4));$len = count($edges);$n = 4; // display the resultecho \"sum = \" . count1($edges, $len, $n) . \"\\n\"; // This code is contributed by mits?>",
"e": 4856,
"s": 4063,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach // returns the sum of degree of all// the nodes in a undirected graphfunction count(edges, len, n){ var degree = Array(n+1).fill(0); // compute the degree of each node for (var i = 0; i < len; i++) { // increase the degree of the // nodes degree[edges[i][0]]++; degree[edges[i][1]]++; } // calculate the sum of degree var sum = 0; for (var i = 1; i <= n; i++) sum += degree[i]; return sum;} // main function// the edge listvar edges = [ [ 1, 2 ], [ 2, 3 ], [ 1, 4 ], [ 2, 4 ] ];var len = edges.length, n = 4; // display the resultdocument.write( \"sum = \" + count(edges, len, n)); // This code is contributed by rutvik_56.</script>",
"e": 5660,
"s": 4856,
"text": null
},
{
"code": null,
"e": 5670,
"s": 5660,
"text": "Output: "
},
{
"code": null,
"e": 5678,
"s": 5670,
"text": "sum = 8"
},
{
"code": null,
"e": 6017,
"s": 5678,
"text": "Efficient approach If we get the number of the edges in a directed graph then we can find the sum of degree of the graph. Let us consider an graph with no edges. If we add a edge we are increasing the degree of two nodes of graph by 1, so after adding each edge the sum of degree of nodes increases by 2, hence the sum of degree is 2*e. "
},
{
"code": null,
"e": 6021,
"s": 6017,
"text": "C++"
},
{
"code": null,
"e": 6026,
"s": 6021,
"text": "Java"
},
{
"code": null,
"e": 6035,
"s": 6026,
"text": "Python 3"
},
{
"code": null,
"e": 6038,
"s": 6035,
"text": "C#"
},
{
"code": null,
"e": 6042,
"s": 6038,
"text": "PHP"
},
{
"code": null,
"e": 6053,
"s": 6042,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // returns the sum of degree of all// the nodes in a undirected graphint count(int edges[][2], int len){ return 2 * len;} // main functionint main(){ // the edge list int edges[][2] = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = sizeof(edges) / (sizeof(int) * 2); // display the result cout << \"sum = \" << count(edges, len) << endl; return 0;}",
"e": 6578,
"s": 6053,
"text": null
},
{
"code": "// Java implementation for above approachclass GFG { // returns the sum of degree of all // the nodes in a undirected graph static int count(int edges[][], int len) { return 2 * len; } // Driver code public static void main(String[] args) { // the edge list int edges[][] = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = edges.length; // display the result System.out.println(\"sum = \" + count(edges, len)); }} // This code contributed by Rajput-Ji",
"e": 7180,
"s": 6578,
"text": null
},
{
"code": "# Python3 implementation of above approach # returns the sum of degree of all# the nodes in a undirected graphdef count(edges, length) : return 2 * length; # Driver Codeif __name__ == \"__main__\" : # the edge list edges = [[ 1, 2 ], [ 2, 3 ], [ 1, 4 ], [ 2, 4 ]]; length = len(edges); # display the result print(\"sum = \", count(edges, length)); # This code is contributed by Ryuga",
"e": 7621,
"s": 7180,
"text": null
},
{
"code": "// C# implementation for above approachusing System; class GFG { // returns the sum of degree of all // the nodes in a undirected graph static int count(int[, ] edges, int len) { return 2 * len; } // Driver code public static void Main(String[] args) { // the edge list int[, ] edges = { { 1, 2 }, { 2, 3 }, { 1, 4 }, { 2, 4 } }; int len = edges.GetLength(0); // display the result Console.WriteLine(\"sum = \" + count(edges, len)); }} /* This code contributed by PrinciRaj1992 */",
"e": 8247,
"s": 7621,
"text": null
},
{
"code": "<?php// PHP implementation of above approach // returns the sum of degree of all// the nodes in a undirected graphfunction count1($edges, $len){ return 2 * $len;} // Driver Code // the edge list$edges = array(array(1, 2), array(2, 3), array(1, 4), array(2, 4));$len = sizeof($edges); // display the resultecho \"sum = \" . count1($edges, $len) . \"\\n\"; // This code is contributed// by Akanksha Rai?>",
"e": 8690,
"s": 8247,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach // returns the sum of degree of all// the nodes in a undirected graphfunction count(edges, len){ return 2 * len;} // main function// the edge listvar edges = [ [ 1, 2 ], [ 2, 3 ], [ 1, 4 ], [ 2, 4 ] ];var len = edges.length;// display the resultdocument.write( \"sum = \" + count(edges, len)); </script> ",
"e": 9108,
"s": 8690,
"text": null
},
{
"code": null,
"e": 9118,
"s": 9108,
"text": "Output: "
},
{
"code": null,
"e": 9126,
"s": 9118,
"text": "sum = 8"
},
{
"code": null,
"e": 9136,
"s": 9128,
"text": "ankthon"
},
{
"code": null,
"e": 9146,
"s": 9136,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9160,
"s": 9146,
"text": "princiraj1992"
},
{
"code": null,
"e": 9172,
"s": 9160,
"text": "29AjayKumar"
},
{
"code": null,
"e": 9185,
"s": 9172,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9195,
"s": 9185,
"text": "Code_Mech"
},
{
"code": null,
"e": 9212,
"s": 9195,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 9225,
"s": 9212,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 9234,
"s": 9225,
"text": "noob2000"
},
{
"code": null,
"e": 9244,
"s": 9234,
"text": "rutvik_56"
},
{
"code": null,
"e": 9263,
"s": 9244,
"text": "graph-connectivity"
},
{
"code": null,
"e": 9269,
"s": 9263,
"text": "Graph"
},
{
"code": null,
"e": 9275,
"s": 9269,
"text": "Graph"
}
] |
LinkedList size() Method in Java | 10 Dec, 2018
The Java.util.LinkedList.size() method is used to get the size of the Linked list or the number of elements present in the linked list.
Syntax:
LinkedList.size()
Parameters: This method does not take any parameter.
Return Value: This method returns the size or the number of elements present in the LinkedList.
Below program illustrate the Java.util.LinkedList.size() method:
// Java code to illustrate size()import java.io.*;import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Displaying the linkedlist System.out.println("LinkedList:" + list); // Displaying the size of the list System.out.println("The size of the linked list is: " + list.size()); }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The size of the linked list is: 5
Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 189,
"s": 53,
"text": "The Java.util.LinkedList.size() method is used to get the size of the Linked list or the number of elements present in the linked list."
},
{
"code": null,
"e": 197,
"s": 189,
"text": "Syntax:"
},
{
"code": null,
"e": 216,
"s": 197,
"text": "LinkedList.size()\n"
},
{
"code": null,
"e": 269,
"s": 216,
"text": "Parameters: This method does not take any parameter."
},
{
"code": null,
"e": 365,
"s": 269,
"text": "Return Value: This method returns the size or the number of elements present in the LinkedList."
},
{
"code": null,
"e": 430,
"s": 365,
"text": "Below program illustrate the Java.util.LinkedList.size() method:"
},
{
"code": "// Java code to illustrate size()import java.io.*;import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Displaying the linkedlist System.out.println(\"LinkedList:\" + list); // Displaying the size of the list System.out.println(\"The size of the linked list is: \" + list.size()); }}",
"e": 1138,
"s": 430,
"text": null
},
{
"code": null,
"e": 1212,
"s": 1138,
"text": "LinkedList:[Geeks, for, Geeks, 10, 20]\nThe size of the linked list is: 5\n"
},
{
"code": null,
"e": 1232,
"s": 1212,
"text": "Java - util package"
},
{
"code": null,
"e": 1249,
"s": 1232,
"text": "Java-Collections"
},
{
"code": null,
"e": 1264,
"s": 1249,
"text": "Java-Functions"
},
{
"code": null,
"e": 1280,
"s": 1264,
"text": "java-LinkedList"
},
{
"code": null,
"e": 1285,
"s": 1280,
"text": "Java"
},
{
"code": null,
"e": 1290,
"s": 1285,
"text": "Java"
},
{
"code": null,
"e": 1307,
"s": 1290,
"text": "Java-Collections"
}
] |
The most occurring number in a string using Regex in python | 29 Dec, 2020
Given a string str, the task is to extract all the numbers from a string and find out the most occurring element of them using Regex Python.
It is guaranteed that no two element have the same frequency
Input :geek55of55geeks4abc3dr2
Output :55
Input :abcd1def2high2bnasvd3vjhd44
Output :2
Approach:Extract all the numbers from a string str using re.findall() function from regex library in python, and with the use of Counter function from collection library we can get the most occurred element.
Below is the Python implementation of above approach
# your code goes here# Python program to # find the most occurring element import re from collections import Counter def most_occr_element(word): # re.findall will extract all the elements # from the string and make a list arr = re.findall(r'[0-9]+', word) # to store maxm frequency maxm = 0 # to store maxm element of most frequency max_elem = 0 # counter will store all the number with # their frequencies # c = counter((55, 2), (2, 1), (3, 1), (4, 1)) c = Counter(arr) # Store all the keys of counter in a list in # which first would we our required element for x in list(c.keys()): if c[x]>= maxm: maxm = c[x] max_elem = int(x) return max_elem # Driver program if __name__ == "__main__": word = 'geek55of55gee4ksabc3dr2x' print(most_occr_element(word))
55
Python Regex-programs
Python string-programs
python-regex
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "Given a string str, the task is to extract all the numbers from a string and find out the most occurring element of them using Regex Python."
},
{
"code": null,
"e": 230,
"s": 169,
"text": "It is guaranteed that no two element have the same frequency"
},
{
"code": null,
"e": 320,
"s": 230,
"text": "Input :geek55of55geeks4abc3dr2 \nOutput :55\n\nInput :abcd1def2high2bnasvd3vjhd44\nOutput :2\n"
},
{
"code": null,
"e": 528,
"s": 320,
"text": "Approach:Extract all the numbers from a string str using re.findall() function from regex library in python, and with the use of Counter function from collection library we can get the most occurred element."
},
{
"code": null,
"e": 581,
"s": 528,
"text": "Below is the Python implementation of above approach"
},
{
"code": "# your code goes here# Python program to # find the most occurring element import re from collections import Counter def most_occr_element(word): # re.findall will extract all the elements # from the string and make a list arr = re.findall(r'[0-9]+', word) # to store maxm frequency maxm = 0 # to store maxm element of most frequency max_elem = 0 # counter will store all the number with # their frequencies # c = counter((55, 2), (2, 1), (3, 1), (4, 1)) c = Counter(arr) # Store all the keys of counter in a list in # which first would we our required element for x in list(c.keys()): if c[x]>= maxm: maxm = c[x] max_elem = int(x) return max_elem # Driver program if __name__ == \"__main__\": word = 'geek55of55gee4ksabc3dr2x' print(most_occr_element(word))",
"e": 1482,
"s": 581,
"text": null
},
{
"code": null,
"e": 1486,
"s": 1482,
"text": "55\n"
},
{
"code": null,
"e": 1508,
"s": 1486,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 1531,
"s": 1508,
"text": "Python string-programs"
},
{
"code": null,
"e": 1544,
"s": 1531,
"text": "python-regex"
},
{
"code": null,
"e": 1558,
"s": 1544,
"text": "python-string"
},
{
"code": null,
"e": 1565,
"s": 1558,
"text": "Python"
}
] |
Initialize a static Map using Java 9 Map.of() | 14 Jul, 2022
In this article, a static map is created and initialised in Java using Java 9.
Static Map in JavaA static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class.
Java 9 feature – Map.of() methodIn Java 9, Map.of() was introduced which is a convenient way to create instances of Map interface. It can hold up to 10 key-value pairs.
Approach:
Pass the map values as Key and Value pair in the Map.of() method.
A static factory Map instance is returned.
Store it in Map and use.
Below is the implementation of the above approach:
Example 1:
// Java program to create a static map using Java 9 import java.util.*; class GFG { // Declaring and instantiating the static map private static Map<String, String> map = Map.of("1", "GFG", "2", "Geek", "3", "GeeksForGeeks"); // Driver code public static void main(String[] args) { System.out.println(map); }}
Output:
{3=GeeksForGeeks, 2=Geek, 1=GFG}
Example 2: To show the error when 10 key-value pairs are given
// Java program to create a static map using Java 9 import java.util.*; class GFG { // Declaring and instantiating the static map private static Map<String, String> map = Map.of("1", "GFG", "2", "Geek", "3", "GeeksForGeeks", "4", "G", "5", "e", "6", "e", "7", "k", "8", "s", "9", "f", "10", "o"); // Driver code public static void main(String[] args) { System.out.println(map); }}
Output:
{10=o, 9=f, 8=s, 7=k, 6=e, 5=e, 4=G, 3=GeeksForGeeks, 2=Geek, 1=GFG}
Example 3: To show the error when more than 10 key-value pairs are given
// Java program to create a static map using Java 9 import java.util.*; class GFG { // Declaring and instantiating the static map private static Map<String, String> map = Map.of("1", "GFG", "2", "Geek", "3", "GeeksForGeeks", "4", "G", "5", "e", "6", "e", "7", "k", "8", "s", "9", "f", "10", "o", "11", "r"); // Driver code public static void main(String[] args) { System.out.println(map); }}
Compilation Error:
Main.java:12: error: no suitable method found for
of(String, String,
String, String,
String, String,
String, String,
String, String,
String, String,
String, String,
String, String,
String, String,
String, String,
String, String)
1 error
Related Articles:
Initialize a static map in Java with Examples
Initialize a static Map using Stream in Java
java-map
Static Keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2022"
},
{
"code": null,
"e": 107,
"s": 28,
"text": "In this article, a static map is created and initialised in Java using Java 9."
},
{
"code": null,
"e": 256,
"s": 107,
"text": "Static Map in JavaA static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class."
},
{
"code": null,
"e": 425,
"s": 256,
"text": "Java 9 feature – Map.of() methodIn Java 9, Map.of() was introduced which is a convenient way to create instances of Map interface. It can hold up to 10 key-value pairs."
},
{
"code": null,
"e": 435,
"s": 425,
"text": "Approach:"
},
{
"code": null,
"e": 501,
"s": 435,
"text": "Pass the map values as Key and Value pair in the Map.of() method."
},
{
"code": null,
"e": 544,
"s": 501,
"text": "A static factory Map instance is returned."
},
{
"code": null,
"e": 569,
"s": 544,
"text": "Store it in Map and use."
},
{
"code": null,
"e": 620,
"s": 569,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 631,
"s": 620,
"text": "Example 1:"
},
{
"code": "// Java program to create a static map using Java 9 import java.util.*; class GFG { // Declaring and instantiating the static map private static Map<String, String> map = Map.of(\"1\", \"GFG\", \"2\", \"Geek\", \"3\", \"GeeksForGeeks\"); // Driver code public static void main(String[] args) { System.out.println(map); }}",
"e": 1011,
"s": 631,
"text": null
},
{
"code": null,
"e": 1019,
"s": 1011,
"text": "Output:"
},
{
"code": null,
"e": 1053,
"s": 1019,
"text": "{3=GeeksForGeeks, 2=Geek, 1=GFG}\n"
},
{
"code": null,
"e": 1116,
"s": 1053,
"text": "Example 2: To show the error when 10 key-value pairs are given"
},
{
"code": "// Java program to create a static map using Java 9 import java.util.*; class GFG { // Declaring and instantiating the static map private static Map<String, String> map = Map.of(\"1\", \"GFG\", \"2\", \"Geek\", \"3\", \"GeeksForGeeks\", \"4\", \"G\", \"5\", \"e\", \"6\", \"e\", \"7\", \"k\", \"8\", \"s\", \"9\", \"f\", \"10\", \"o\"); // Driver code public static void main(String[] args) { System.out.println(map); }}",
"e": 1679,
"s": 1116,
"text": null
},
{
"code": null,
"e": 1687,
"s": 1679,
"text": "Output:"
},
{
"code": null,
"e": 1757,
"s": 1687,
"text": "{10=o, 9=f, 8=s, 7=k, 6=e, 5=e, 4=G, 3=GeeksForGeeks, 2=Geek, 1=GFG}\n"
},
{
"code": null,
"e": 1830,
"s": 1757,
"text": "Example 3: To show the error when more than 10 key-value pairs are given"
},
{
"code": "// Java program to create a static map using Java 9 import java.util.*; class GFG { // Declaring and instantiating the static map private static Map<String, String> map = Map.of(\"1\", \"GFG\", \"2\", \"Geek\", \"3\", \"GeeksForGeeks\", \"4\", \"G\", \"5\", \"e\", \"6\", \"e\", \"7\", \"k\", \"8\", \"s\", \"9\", \"f\", \"10\", \"o\", \"11\", \"r\"); // Driver code public static void main(String[] args) { System.out.println(map); }}",
"e": 2420,
"s": 1830,
"text": null
},
{
"code": null,
"e": 2439,
"s": 2420,
"text": "Compilation Error:"
},
{
"code": null,
"e": 2727,
"s": 2439,
"text": "Main.java:12: error: no suitable method found for\n of(String, String,\n String, String,\n String, String,\n String, String,\n String, String,\n String, String,\n String, String,\n String, String,\n String, String,\n String, String,\n String, String)\n \n1 error\n"
},
{
"code": null,
"e": 2745,
"s": 2727,
"text": "Related Articles:"
},
{
"code": null,
"e": 2791,
"s": 2745,
"text": "Initialize a static map in Java with Examples"
},
{
"code": null,
"e": 2836,
"s": 2791,
"text": "Initialize a static Map using Stream in Java"
},
{
"code": null,
"e": 2845,
"s": 2836,
"text": "java-map"
},
{
"code": null,
"e": 2860,
"s": 2845,
"text": "Static Keyword"
},
{
"code": null,
"e": 2865,
"s": 2860,
"text": "Java"
},
{
"code": null,
"e": 2870,
"s": 2865,
"text": "Java"
}
] |
Angular7 - Materials/CDK-Virtual Scrolling | This is one of the new features added to Angular 7 called as Virtual Scrolling. This feature is added to CDK (Component Development Kit). Virtual scrolling shows up the visible dom elements to the user, as the user scrolls, the next list is displayed. This gives faster experience as the full list is not loaded at one go and only loaded as per the visibility on the screen.
Consider you have a UI which has a big list where loading all the data together can have performance issues. The new feature of Angular 7 Virtual Scrolling takes care of loading the elements which are visible to the user. As the user scrolls, the next list of dom elements visible to user is displayed. This gives faster experience and the scrolling is also very smooth.
Let us add the dependency to our project −
npm install @angular/cdk –save
We are done with installing the dependency for virtual scrolling module.
We will work on an example to get a better understanding on how we can use virtual scrolling module in our project.
We will first add the virtual scrolling module inside app.module.ts as follows −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule , RoutingComponent} from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
import { MyserviceService } from './myservice.service';
import { HttpClientModule } from '@angular/common/http';
import { ScrollDispatchModule } from '@angular/cdk/scrolling';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective,
RoutingComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ScrollDispatchModule
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
In app.module.ts, we have imported the ScrollDispatchModule and the same is added to imports array as shown in the code above.
Next step is to get data to be displayed on the screen. We will continue to use the service we created in the last chapter.
We will fetch data from the url, https://jsonplaceholder.typicode.com/photos which has data for around 5000 images. We will get the data from it and display to the user using virtual scrolling module.
The details in the url, https://jsonplaceholder.typicode.com/photos are as follows −
It is json data that has image url and thumbnail url. We will show the thumbnail url to the users.
Following is the service which will fetch data −
myservice.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class MyserviceService {
private finaldata = [];
private apiurl = "https://jsonplaceholder.typicode.com/photos";
constructor(private http: HttpClient) { }
getData() {
return this.http.get(this.apiurl);
}
}
We will call the service from app.component.ts as follows −
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7 Project!';
public albumdetails = [];
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.myservice.getData().subscribe((data) => {
this.albumdetails = Array.from(Object.keys(data), k=>data[k]);
console.log(this.albumdetails);
});
}
}
Now the variable albumdetails has all the data from the api and the total count is 5000.
Now that we have the data ready to be displayed, let us work inside app.component.html to display the data.
We need to add the tag, <cdk-virtual-scroll-viewport></cdk-virtual-scroll-viewport> to work with virtual scroll module. The tag needs to be added to .html file where we want the data to be displayed.
Here is the working of <cdk-virtual-scroll-viewport> in app.component.html.
<h3>Angular 7 - Virtual Scrolling</h3>
<cdk-virtual-scroll-viewport [itemSize] = "20">
<table>
<thead>
<tr>
<td>ID</td>
<td>ThumbNail</td>
</tr>
</thead>
<tbody>
<tr *cdkVirtualFor = "let album of albumdetails">
<td>{{album.id}}</td>
<td>
<img src = "{{album.thumbnailUrl}}" width = "100" height = "100"/>
</td>
</tr>
</tbody>
</table>
</cdk-virtual-scroll-viewport>
We are displaying the id and thumbnail url to the user on the screen. We have mostly used *ngFor so far, but inside <cdk-virtual-scroll-viewport>, we have to use *cdkVirtualFor to loop through the data.
We are looping through albumdetails variable which is populated inside app.component.html. There is a size assigned to the virtual tag [itemSize]="20" which will display the number of items based on the height of the virtual scroll module.
The css related to the virtual scroll module is as follows −
table {
width: 100%;
}
cdk-virtual-scroll-viewport {
height: 500px;
}
The height given to the virtual scroll is 500px. The images that fit within that height will be displayed to the user. We are done with adding the necessary code to get our virtual scroll module to be viewed.
The output of Virtual Scroll Module in the browser is as follows −
We can see the first 4 images are displayed to the user. We have specified the height of 500px. There is scroll displayed for the table, as the user scrolls, the images which will fit in that height will be displayed as shown below −
The required images are loaded as the user scrolls. This feature is very useful in terms of performance. At first go, it does not load all the 5000 images, instead as the user scrolls, the urls are called and displayed.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2436,
"s": 2061,
"text": "This is one of the new features added to Angular 7 called as Virtual Scrolling. This feature is added to CDK (Component Development Kit). Virtual scrolling shows up the visible dom elements to the user, as the user scrolls, the next list is displayed. This gives faster experience as the full list is not loaded at one go and only loaded as per the visibility on the screen."
},
{
"code": null,
"e": 2807,
"s": 2436,
"text": "Consider you have a UI which has a big list where loading all the data together can have performance issues. The new feature of Angular 7 Virtual Scrolling takes care of loading the elements which are visible to the user. As the user scrolls, the next list of dom elements visible to user is displayed. This gives faster experience and the scrolling is also very smooth."
},
{
"code": null,
"e": 2850,
"s": 2807,
"text": "Let us add the dependency to our project −"
},
{
"code": null,
"e": 2882,
"s": 2850,
"text": "npm install @angular/cdk –save\n"
},
{
"code": null,
"e": 2955,
"s": 2882,
"text": "We are done with installing the dependency for virtual scrolling module."
},
{
"code": null,
"e": 3071,
"s": 2955,
"text": "We will work on an example to get a better understanding on how we can use virtual scrolling module in our project."
},
{
"code": null,
"e": 3152,
"s": 3071,
"text": "We will first add the virtual scrolling module inside app.module.ts as follows −"
},
{
"code": null,
"e": 4073,
"s": 3152,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule , RoutingComponent} from './app-routing.module';\nimport { AppComponent } from './app.component';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\nimport { MyserviceService } from './myservice.service';\nimport { HttpClientModule } from '@angular/common/http';\nimport { ScrollDispatchModule } from '@angular/cdk/scrolling';\n\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective,\n RoutingComponent\n ],\n imports: [\n BrowserModule,\n AppRoutingModule,\n HttpClientModule,\n ScrollDispatchModule\n ],\n providers: [MyserviceService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 4200,
"s": 4073,
"text": "In app.module.ts, we have imported the ScrollDispatchModule and the same is added to imports array as shown in the code above."
},
{
"code": null,
"e": 4324,
"s": 4200,
"text": "Next step is to get data to be displayed on the screen. We will continue to use the service we created in the last chapter."
},
{
"code": null,
"e": 4525,
"s": 4324,
"text": "We will fetch data from the url, https://jsonplaceholder.typicode.com/photos which has data for around 5000 images. We will get the data from it and display to the user using virtual scrolling module."
},
{
"code": null,
"e": 4611,
"s": 4525,
"text": "The details in the url, https://jsonplaceholder.typicode.com/photos are as follows −"
},
{
"code": null,
"e": 4710,
"s": 4611,
"text": "It is json data that has image url and thumbnail url. We will show the thumbnail url to the users."
},
{
"code": null,
"e": 4759,
"s": 4710,
"text": "Following is the service which will fetch data −"
},
{
"code": null,
"e": 4780,
"s": 4759,
"text": "myservice.service.ts"
},
{
"code": null,
"e": 5149,
"s": 4780,
"text": "import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class MyserviceService {\n private finaldata = [];\n private apiurl = \"https://jsonplaceholder.typicode.com/photos\";\n constructor(private http: HttpClient) { }\n getData() {\n return this.http.get(this.apiurl);\n }\n}"
},
{
"code": null,
"e": 5209,
"s": 5149,
"text": "We will call the service from app.component.ts as follows −"
},
{
"code": null,
"e": 5772,
"s": 5209,
"text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 7 Project!';\n public albumdetails = [];\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.myservice.getData().subscribe((data) => {\n this.albumdetails = Array.from(Object.keys(data), k=>data[k]);\n console.log(this.albumdetails);\n });\n }\n}"
},
{
"code": null,
"e": 5861,
"s": 5772,
"text": "Now the variable albumdetails has all the data from the api and the total count is 5000."
},
{
"code": null,
"e": 5969,
"s": 5861,
"text": "Now that we have the data ready to be displayed, let us work inside app.component.html to display the data."
},
{
"code": null,
"e": 6169,
"s": 5969,
"text": "We need to add the tag, <cdk-virtual-scroll-viewport></cdk-virtual-scroll-viewport> to work with virtual scroll module. The tag needs to be added to .html file where we want the data to be displayed."
},
{
"code": null,
"e": 6245,
"s": 6169,
"text": "Here is the working of <cdk-virtual-scroll-viewport> in app.component.html."
},
{
"code": null,
"e": 6753,
"s": 6245,
"text": "<h3>Angular 7 - Virtual Scrolling</h3>\n<cdk-virtual-scroll-viewport [itemSize] = \"20\">\n <table>\n <thead>\n <tr>\n <td>ID</td>\n <td>ThumbNail</td>\n </tr>\n </thead>\n <tbody>\n <tr *cdkVirtualFor = \"let album of albumdetails\">\n <td>{{album.id}}</td>\n <td>\n <img src = \"{{album.thumbnailUrl}}\" width = \"100\" height = \"100\"/>\n </td>\n </tr>\n </tbody>\n </table>\n</cdk-virtual-scroll-viewport>"
},
{
"code": null,
"e": 6956,
"s": 6753,
"text": "We are displaying the id and thumbnail url to the user on the screen. We have mostly used *ngFor so far, but inside <cdk-virtual-scroll-viewport>, we have to use *cdkVirtualFor to loop through the data."
},
{
"code": null,
"e": 7196,
"s": 6956,
"text": "We are looping through albumdetails variable which is populated inside app.component.html. There is a size assigned to the virtual tag [itemSize]=\"20\" which will display the number of items based on the height of the virtual scroll module."
},
{
"code": null,
"e": 7257,
"s": 7196,
"text": "The css related to the virtual scroll module is as follows −"
},
{
"code": null,
"e": 7334,
"s": 7257,
"text": "table {\n width: 100%;\n}\ncdk-virtual-scroll-viewport {\n height: 500px;\n}\n"
},
{
"code": null,
"e": 7543,
"s": 7334,
"text": "The height given to the virtual scroll is 500px. The images that fit within that height will be displayed to the user. We are done with adding the necessary code to get our virtual scroll module to be viewed."
},
{
"code": null,
"e": 7610,
"s": 7543,
"text": "The output of Virtual Scroll Module in the browser is as follows −"
},
{
"code": null,
"e": 7844,
"s": 7610,
"text": "We can see the first 4 images are displayed to the user. We have specified the height of 500px. There is scroll displayed for the table, as the user scrolls, the images which will fit in that height will be displayed as shown below −"
},
{
"code": null,
"e": 8064,
"s": 7844,
"text": "The required images are loaded as the user scrolls. This feature is very useful in terms of performance. At first go, it does not load all the 5000 images, instead as the user scrolls, the urls are called and displayed."
},
{
"code": null,
"e": 8099,
"s": 8064,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8113,
"s": 8099,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8148,
"s": 8113,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8162,
"s": 8148,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8197,
"s": 8162,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 8217,
"s": 8197,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 8252,
"s": 8217,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8269,
"s": 8252,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8302,
"s": 8269,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8314,
"s": 8302,
"text": " Senol Atac"
},
{
"code": null,
"e": 8349,
"s": 8314,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8361,
"s": 8349,
"text": " Senol Atac"
},
{
"code": null,
"e": 8368,
"s": 8361,
"text": " Print"
},
{
"code": null,
"e": 8379,
"s": 8368,
"text": " Add Notes"
}
] |
Difference between Arrays and Collection in Java - GeeksforGeeks | 29 Dec, 2021
An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. On the other hand, any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface in it.
The most essential thing while dealing Collection is to have super strong grasp of Collection framework which in one go is depicted via below image as follows:
Example
Java
// Java Program to Illustrate Difference// Between Arrays and Collection // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Arrays String[] gfg = new String[] { "G", "E", "E", "K", "S" }; // Trying printing the above array System.out.print(gfg); // New Line System.out.println(); // Collection // Let us arbitarly create an empty ArrayList // of string type ArrayList<String> al = new ArrayList<String>(); // Adding elements to above List // using add() method al.add("g"); al.add("e"); al.add("e"); al.add("k"); al.add("s"); // Printing all elements of Collection (ArrayList) System.out.println(al); }}
[Ljava.lang.String;@3d075dc0
[g, e, e, k, s]
Now after having understanding of Arrays and Collection, let us now tabulate differences between them which is as follows:
mohddanishsajid
nitinagrawalup
sagartomar9927
sumitgumber28
rkbhola5
Java-Arrays
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java | [
{
"code": null,
"e": 23893,
"s": 23865,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 24369,
"s": 23893,
"text": "An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. On the other hand, any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface in it."
},
{
"code": null,
"e": 24529,
"s": 24369,
"text": "The most essential thing while dealing Collection is to have super strong grasp of Collection framework which in one go is depicted via below image as follows:"
},
{
"code": null,
"e": 24537,
"s": 24529,
"text": "Example"
},
{
"code": null,
"e": 24542,
"s": 24537,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Difference// Between Arrays and Collection // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Arrays String[] gfg = new String[] { \"G\", \"E\", \"E\", \"K\", \"S\" }; // Trying printing the above array System.out.print(gfg); // New Line System.out.println(); // Collection // Let us arbitarly create an empty ArrayList // of string type ArrayList<String> al = new ArrayList<String>(); // Adding elements to above List // using add() method al.add(\"g\"); al.add(\"e\"); al.add(\"e\"); al.add(\"k\"); al.add(\"s\"); // Printing all elements of Collection (ArrayList) System.out.println(al); }}",
"e": 25398,
"s": 24542,
"text": null
},
{
"code": null,
"e": 25443,
"s": 25398,
"text": "[Ljava.lang.String;@3d075dc0\n[g, e, e, k, s]"
},
{
"code": null,
"e": 25566,
"s": 25443,
"text": "Now after having understanding of Arrays and Collection, let us now tabulate differences between them which is as follows:"
},
{
"code": null,
"e": 25582,
"s": 25566,
"text": "mohddanishsajid"
},
{
"code": null,
"e": 25597,
"s": 25582,
"text": "nitinagrawalup"
},
{
"code": null,
"e": 25612,
"s": 25597,
"text": "sagartomar9927"
},
{
"code": null,
"e": 25626,
"s": 25612,
"text": "sumitgumber28"
},
{
"code": null,
"e": 25635,
"s": 25626,
"text": "rkbhola5"
},
{
"code": null,
"e": 25647,
"s": 25635,
"text": "Java-Arrays"
},
{
"code": null,
"e": 25664,
"s": 25647,
"text": "Java-Collections"
},
{
"code": null,
"e": 25669,
"s": 25664,
"text": "Java"
},
{
"code": null,
"e": 25674,
"s": 25669,
"text": "Java"
},
{
"code": null,
"e": 25691,
"s": 25674,
"text": "Java-Collections"
},
{
"code": null,
"e": 25789,
"s": 25691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25798,
"s": 25789,
"text": "Comments"
},
{
"code": null,
"e": 25811,
"s": 25798,
"text": "Old Comments"
},
{
"code": null,
"e": 25857,
"s": 25811,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25878,
"s": 25857,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25893,
"s": 25878,
"text": "Stream In Java"
},
{
"code": null,
"e": 25912,
"s": 25893,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25929,
"s": 25912,
"text": "Generics in Java"
},
{
"code": null,
"e": 25972,
"s": 25929,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26014,
"s": 25972,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 26043,
"s": 26014,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26073,
"s": 26043,
"text": "Functional Interfaces in Java"
}
] |
How to Render Interactive Weather Models Entirely in the Browser | by Thomas Horner | Towards Data Science | Weather enthusiasts, meteorologists, and storm chasers are aware of the myriad of weather model visualization websites out on the web. These platforms allow you to view various parameters, levels, and forecast hours of dozens of different weather models. For example, when preparing for a day of storm chasing, a chaser may look at a few parameters for a certain area — the dewpoint in the morning, the CAPE later in the day, and the HRRR’s simulated reflectivity in the afternoon. Menus, buttons, and sliders are usually provided to switch forecast hours, models, and parameters.
Typically, all of these weather model viewers are simply ways for the user to access pre-rendered, nonspatial weather models, despite the original data being geospatial in nature. Though interfaces differ, many things are consistent in weather model viewers:
Geographic regions are fixed. You can only view preset areas, such as from a list of cities, states, or regions. The output images are fixed in size as well. A few viewers let you zoom in to certain areas and wait for a new render.
Geographic layers and information are scarce or non-existent. You may only have roads or counties visible on top of the weather model image, which can make specific areas difficult to pinpoint.
Many providers have viewers that are generally non-queryable, which means to get the actual value for any given point you need to compare the color of the data against the legend.
Model layer combinations and color schemes are static. You cannot overlay, for instance, wind streamlines at a certain height over another variable, unless the provider has made that combination available.
Though many of the providers have put serious care and thought into the presentation of the data, the aforementioned shortcomings can be significant and aggravating in certain circumstances. For instance, evaluating forecasted snowfall totals in mountainous terrain can be incredibly challenging if you just have county boundaries to orient yourself with, considering that snowfall totals may vary by tens of inches over just a few miles.
Consider the below image:
Even as a forecaster with a geography degree I struggle with getting useful data out of this graphic. Looking at the state of Colorado:
Where is Steamboat in relation to that yellow isoband in north Colorado? Is it in the blue or in the green? (this would be the difference between 2" and 6" of snow).On I-70, how does snowfall distribution change from the east of Vail Pass to west of it?How much snow is the Gore Range getting compared to the Tenmile Range to its immediate south?
Where is Steamboat in relation to that yellow isoband in north Colorado? Is it in the blue or in the green? (this would be the difference between 2" and 6" of snow).
On I-70, how does snowfall distribution change from the east of Vail Pass to west of it?
How much snow is the Gore Range getting compared to the Tenmile Range to its immediate south?
If you do enough forecasting in Colorado, you’ll eventually have the county outlines vs. mountain range relationship memorized down to the mile, because that’s usually all you have to work with when looking at the distribution of weather across the state on many model viewers.
That said, it is important to mention the benefits of these platforms — the most obvious being the use of pre-rendered static images. These are fast and it is easy to load all forecast hours of a model in just a few seconds, and you can often easily have the server generate an animated GIF of the data. The fixed regions prevent ‘misuse’ of the data — such as zooming in to a resolution beyond what the weather model is suited for. These two factors allow for consistent weather model visualization, which is helpful if you are downloading the images and archiving them for comparison or redistribution.
In a previous article, I discussed how you can build and automate your own weather model visualizer. This technique had an interesting twist in that, though the server is still rendering the data, it is serving it as a geospatial layer (OGC WMS) that can be added to interactive web maps. This strikes an nice balance between the performance of pre-rendered static images and the interactivity of fully geospatial data. I will show you how to take this one step farther and do the rendering entirely in the browser, no server needed! Per my link above, this article will assume you have the weather models available in GeoTIFF format and projected to EPSG:4326. You can convert raw weather model data (in GRIB2 format) to GeoTIFF with just one GDAL command.
The disadvantages of rendering weather model data on the client, using a web browser, are plentiful — but there are some potential use cases for the technology. Web development in the year 2020 seems to be just mature and powerful enough to make this an actually viable proposition for certain purposes. Here are the main issues we’ll encounter:
Slowness. JavaScript is not an ideal language to turn raw multidimensional rasters into RGB images or vector isobands.
Data use. The raw weather model data is not as compact as a simple JPEG.
Compatibility. The final code we write wont work in Internet Explorer, and it will perform miserably on older hardware.
In contrast, here are some benefits we will enjoy:
The ability to present the data on a fully interactive web map, which means we can add as many layers of geographic data (or other model parameters) as we want, and style it however we want, in real-time.
The data can be accessed directly, such as to query points or areas for the raw model data. This goes beyond just clicking on a map and getting the data at a point — a use case may be the ability to define a list of locations or set of points that present the data in a tabular format or overlaid on the map.
The ability to render weather model data, or combinations of the data, in any way we choose — as a raster, as isobands, as isolines (isopleths/contours), as streamlines, etc. The rendering, styling (for instance, width of the contours), and color bands can all be modified by the user (if desired) and update the visualization instantaneously. Various models can even be combined mathematically to produce specific visualizations, instead of having to set up the automated processing scripts to do so ahead of time.
We also have a few strategies to alleviate some of the pain points:
Use web workers to process and render the GeoTIFFs. This will spread the intensive calculations across the various cores of the user’s CPU.
Use cloud-optimized GeoTIFFs (COGs) or the WCS standard to stream the raw data to the user only for the region and scale they are interested in. In addition, applying appropriate compression to the GeoTIFFs can bring them down to reasonable sizes.
With those points in mind, can you think of some use cases where you might enjoy the benefits of client-side rendering? For me, the quality of the visualizations comes immediately to mind. I used to have custom QGIS projects to export nice-looking maps with weather model data, but there was still manual labor involved. With a well-presented web browser visualization platform, I can do the analysis across multiple models, parameters, and forecast hours quickly while being able to export the weather model graphic and map for redistribution with just a click.
There were also some specific issues I encountered in my previously-mentioned article about using MapServer to distribute the weather model data. These issues were all related to visualization products where the graphics are heavily removed from the data itself, requiring various rasters to be rendered into a final RGB image (for example, streamlines or wind barbs on top of a wind speed raster) — which is incompatible with the scale and styling agnostic model data distribution strategy model I intended to employ with MapServer. These issues were fairly trivial to tackle when handled in the web browser, however:
Weather model combination calculations. Several popular weather model visualizations are not possible simply by distributing the converted data without rendering an RGB image. The best example is Composite Reflectivity + Precipitation Type, which shows the simulated radar as you might expect — rain shows up with the typical color scale of green-yellow-red, while snow displays as shades of blue. This actually requires a combination of at least three different weather model parameter rasters, or five if you want to handle all precipitation types (ice pellets and frozen rain). There’s no way that I know of to do this on-the-fly in MapServer, as different color scales need to be used based on the precipitation type and combined into the final image. A more simple example is that wind direction in most models is not a single parameter, but instead two rasters (a horizontal and vertical vector component) that need to be combined with trigonometry to calculate the actual direction and speed.
Wind streamlines. MapServer is capable of producing contours from rasters, or even directional arrows across a raster field, but streamlines are not possible. Yet many popular products rely on streamlines to show things like mid-atmospheric winds.
One thing you may have noticed in the above examples is that, while serviceable, the visualizations don’t look that great. The images are small and the data is cramped, which doesn’t make things easy for forecasters. They’re even more troublesome when redistributed to weather forecast readers, who are likely not data geeks and just want to know where they should ski next weekend. I suppose one could concede that the pixelated, late-90s aesthetic of them does give a sense of pure data authority, and they certainly don’t waste any time on doing anything besides conveying the raw data.
Let’s take a look at what weather models may look like when rendered entirely in the web browser. These were taken from my website and are used in my forecasts. First off, here’s the interface I built for it in Angular:
Some example output images:
Now, let’s zoom in on the interactive map and enable some other layers. When I say adjustable, I mean this can be done in real-time, by the user, on the webpage:
How about a layer with streamlines?
We even have the dreaded Composite Reflectivity + Type layer working properly. You can see the snow as dark blues over the Rockies, with very light rain as greys (and, well, sorry about the slightly misleading light blue color) in Nebraska. This was all calculated in the browser.
Here are the main steps needed to accomplish client-side weather model rendering, once you have your web map in place. I used Leaflet, but ended up needing to extend it so much that OpenLayers may likely be more suitable if you’re starting from scratch.
Fetch the GeoTIFF data for the appropriate model, timestamp, parameter, level, and forecast hour, and read the stream as an ArrayBuffer.Parse the ArrayBuffer to get the geographic information and a nested array of raw data. Geotiff.js is the go-to library for this, although it does not play nicely with Angular unless you import the minified version. You’ll want to cache this data in case you want to make queries against it or re-render the visualizations.Pull out the appropriate band’s data (for multidimensional data, such as multiple forecast hours in one TIFF or multiple parameters in one) and use web workers to run a marching squares algorithm on the nested data array which you can use to produce isobands (polygons) or isolines (polylines), depending on if you want filled/colorized data or contours. You can use a library like raster-marching-squares. For streamlines, you can use the raster-streamlines library. This is the most computationally-expensive step. You’re going to want to cache all this data once it is calculated.Apply the necessary geographic transform to the isobands and isolines as you create them, and then supply them to your web map. For instance, in Leaflet, I make this data available as an L.GeoJSON layer. Make sure to supply the value of the data to each band or line so that it can be styled appropriately. Add it to the map.Add other functionality, such as point querying and visualization download (“Save as JPEG”).
Fetch the GeoTIFF data for the appropriate model, timestamp, parameter, level, and forecast hour, and read the stream as an ArrayBuffer.
Parse the ArrayBuffer to get the geographic information and a nested array of raw data. Geotiff.js is the go-to library for this, although it does not play nicely with Angular unless you import the minified version. You’ll want to cache this data in case you want to make queries against it or re-render the visualizations.
Pull out the appropriate band’s data (for multidimensional data, such as multiple forecast hours in one TIFF or multiple parameters in one) and use web workers to run a marching squares algorithm on the nested data array which you can use to produce isobands (polygons) or isolines (polylines), depending on if you want filled/colorized data or contours. You can use a library like raster-marching-squares. For streamlines, you can use the raster-streamlines library. This is the most computationally-expensive step. You’re going to want to cache all this data once it is calculated.
Apply the necessary geographic transform to the isobands and isolines as you create them, and then supply them to your web map. For instance, in Leaflet, I make this data available as an L.GeoJSON layer. Make sure to supply the value of the data to each band or line so that it can be styled appropriately. Add it to the map.
Add other functionality, such as point querying and visualization download (“Save as JPEG”).
Let’s dig in and go over specifics! I will be using TypeScript and ES6 syntax direct from my codebase, which uses the Angular framework.
This is the easiest part. Some strategies might be:
Simply have the files downloadable from a web server.
Create an API that retrieves the appropriate file for the model, parameter, forecast hour, geographic region, etc.
✔️ Use Cloud-Optimized GeoTIFFs
Use MapServer or another geographic data server to handle WCS requests and return data as a GeoTIFF.
Think about how you want your GeoTIFFs to be structured. To save on data, you likely want one TIFF returned per model, parameter, level, forecast hour, etc. However, you could store multiple forecast hours as several bands in one TIFF if the client wants to preload everything (for instance, to use a slider to view all the forecast hours). This will create an initial, longer download time but speed up overall parsing time slightly.
Don’t forget about compression. Though you can use JPEG compression on TIFFs to get their filesize down to, well, something comparable a JPEG’s — this isn’t responsible use of the data. These are not images, but instead arrays of raw data, the integrity of which should be respected before they are rendered. Also, I don’t think the geotiff.js library can handle that method of compression. I have found that a high level (zlevel = 9) of deflate reduced sizes by up to 50% without impacting parsing performance too badly.
You’ll likely retrieve the GeoTIFF with fetch or using the built-in functions of geotiff.js. The library can natively read cloud-optimized GeoTIFFs! If using a regular GeoTIFF, you’ll need to read the fetch request stream (if you made one) as an ArrayBuffer :
const response = await fetch( <the url of your tiff> );const arrayBuffer = await response.arrayBuffer();
Following the above example, we can use geotiff.js to parse the ArrayBuffer into a GeoTiff object. We can retrieve the actual image data itself from that object:
const geoTiff = await fromArrayBuffer( arrayBuffer );const geoTiffImage = await geoTiff.getImage();
Don’t forget to grab the image metadata and geographic data as well, we’ll need it later:
const tiffWidth = geoTiffImage.getWidth();const tiffHeight = geoTiffImage.getHeight();const tiepoint = geoTiffImage.getTiePoints()[ 0 ];const pixelScale = geoTiffImage.getFileDirectory().ModelPixelScale;const geoTransform = [ tiepoint.x, pixelScale[ 0 ], 0, tiepoint.y, 0, -1 * pixelScale[ 1 ] ];
If you have multiple bands in the image, you can get the exact number of them easily:
const bands = await geoTiffImage.getSamplesPerPixel();
Besides wind barbs (which can be nice for weather forecasters, but pretty useless for the general public), I can’t think of any other ways of rendering the weather model data besides isobands, isolines, or streamlines. Isobands are polygons that pertain to specific ranges of the data. You can use them to generate colorful temperature or snow accumulation maps. Isolines (or isopleths) are contour lines drawn at the boundary of data ranges. Streamlines help visualize data that has both a velocity and a direction. These can all be created as vectors and added to the map.
We will need to crack the GeoTIFF data open to build our geographic vectors. You can also just render it as an image to a canvas, but I wont cover that here (see the Acknowledgments section).
Get the image data for the appropriate band (where i is the band number):
const bandData = await geoTiffImage.readRasters({ samples: [ i ] });
Build a nested array of the raw data:
const dataArr = new Array( tiffHeight );for ( let i = 0; i < tiffHeight; i++ ) { dataArr[ i ] = new Array( tiffWidth ); for ( let ii = 0; ii < tiffWidth; ii++ ) { dataArr[ i ][ ii ] = bandData[ 0 ][ ii + i * tiffWidth ]; }}
We’re going to use the raster-marching-squares library to generate our features, but for performance purposes I want to run it as a web worker so that the user interface doesn’t lock up. If you’re using Angular, it is easy to set a web worker up with Angular-CLI by running ng generate web-worker.
Inside of the web worker, we’ll import raster-marching-squares as rastertools:
import * as rastertools from 'raster-marching-squares';
This provides isoband and isoline rendering as rastertools.isobands() or rastertools.isolines(). Both functions expect the following arguments:
The nested data array (dataArr)
The projection of the raster (geoTransform)
The intervals to break / space the data at. These intervals will always be present in the output from these functions, regardless of if there are actually any features in them or not. For instance, if you passed [-5,0,5] as the interval for a temperature model, you would receive three isobands or isolines pertaining to -5 degrees, 0 degrees, and 5 degrees. If the weather model had data within those ranges, those isolines or isobands would have geometry containing those regions. If not, they would be empty features.
We’ll eventually want to style the isobands or put labels on the isolines, so one thing I did was set up color scales for all of the various parameters I wanted to visualize, passing a color for a specific value. I then set up a function that would produce a fixed number of intervals (such as 100 — smooth, but takes awhile to calculate) from the color scale and use tinygradient to produce the CSS representation of that color scale to use for the legend. For instance, the color scale for snow accumulation looks like this:
"SnowAccumM": [ { value: 1.8288, color: "#ffcc01" }, { value: 1.2192, color: "#ff4501" }, { value: 0.6096, color: "#e51298" }, { value: 0.3048, color: "#9f0ded" }, { value: 0.0762, color: "#5993ff" }, { value: 0.00254, color: "#d6dadd" }, { value: 0, color: "#ffffff" }],
The interval creation function also bounds the intervals array with Number.MAX_SAFE_INTEGER and its negative equivalent. If you do it right, and throw some unit conversion in there, you can handle the isoband creation, styling, and legend in one compact class.
The worker that will run the isobands or isolines function will listen for the three necessary arguments. We’ll also pass in a type parameter to tell it which function to use:
addEventListener( 'message', ( { data } ) => { try { const features = rastertools[type]( data.data, data.geoTransform, data.intervals ); postMessage ( { features } ); } catch ( err ) { postMessage( { error: err.message } ); }}
The function has been wrapped in a try...catch, which is a nice idea, but useless in practice, because when the function screws up, it tends to just get stuck in a do...while loop until you run out of memory. This is likely due to some of the thousands of weather model rasters I convert a day getting corrupted, which I need to fix but...pull request anyone?
Now we can call the worker, pass it the necessary arguments, and wait for a response. You don’t have to use a Promise, it just suited me for my particular workflow:
const type = 'isobands';const rastertoolsWorker = new Worker( `../workers/rastertools.worker`, // the worker class ☭ { type: `module` } );new Promise( ( resolve, reject ) => { rastertoolsWorker.postMessage( { dataArr, geoTransform, intervals, // array of numbers type } ); rastertoolsWorker.addEventListener( 'message', event => resolve( event.data ) );} ).then (...) // the isobands are generated!
If you did 100 intervals, this might take a little while. Your laptop fan might kick on with surprising ferocity.
Note that I did not mention streamlines. If you use the raster-streamlines library, this calculation is refreshingly fast and likely doesn’t need to be put in a web worker.
If you used raster-marching-squares, this part is all taken care of for you. Basically, the vector features are generated from the rasters, and need to be tied back to where those pixels are actually located geographically. We can use the geoTransform provided by geotiff.js to get that transformation information (and hopefully your GeoTIFF was originally in EPSG:4326). We also want the information as a GeoJSON, which is an agnostic collection of geometries. Again, the library provides this collection, we just need to wrap it with L.geoJSON(<the features>) to create a layer we can add to the map. raster-streamlines works the same way.
The library also makes available the isoband’s data range in the properties of each feature. We can use this to style the isobands or add labels to the isolines. This is the other tricky part of the process, which I’ll cover shortly.
You also want to think about what renderer you want the web map to use. By default, Leaflet uses SVG. If you have huge, detailed isobands, performance will be abysmal. I instead opted to use a canvas-based renderer instead, which comes with a few headaches, but allows for acceptable performance once the features have been drawn onto the canvas.
We’re ready to style our layers now.
These are the easiest to style. You just need to pass a style function:
L.geoJSON(<the features>, { style: feature => { return { fillColor: getColor( feature.properties[ 0 ].lowerValue ), weight: 1.5, opacity: 1, color: getColor( feature.properties[ 0 ].lowerValue ), fillOpacity: 1 };});
getColor() is a function I wrote that takes a value and gets the interpolated color (using tinygradient) from the appropriate color scale as mentioned before. feature.properties has been populated with the value range, thanks to raster-marching-squares.
You’ll notice I also set the stroke/outline weight to 1.5, as there are often tiny slivers in between the polygons if they aren’t given outlines. With outlines in place, an important caveat is that if you lower the opacity of the layer (via the style function), the overlap of the fills and outlines will become noticeable. Instead, you’ll need to have the layer on its own map pane and change the opacity of the entire pane.
Styling the isolines themselves is super easy:
return feature => { return { weight: 1.5, color: '#000000' }}
But what about labels? This is actually very tricky. Since we are using a canvas renderer, the Leaflet plugin for drawing polyline labels is out of the question, as it only works on SVG. I don’t want to use different renderers for each layer either, in the case of overlaying contours/isolines onto isobands.
In this case, I found an awkwardly-named plugin (Leaflet.streetlabels) which does draw labels along polylines in the canvas renderer, by actually extending the renderer (so it is not a per-layer solution). It has a couple dependencies (one of which isn’t available via npm) so getting it set up was not straightforward.
There are a number of modifications necessary to get labels working properly.
By default, the plugin cant parse feature.properties as the isolines function places it in an array. It’s looking for a key, so it’s expecting feature.properties to be an object.The plugin has a filter so that it doesn’t attempt to draw labels on all features, just the ones with an appropriate properties object. For some reason, I think maybe due to how GeoJSON files can be found in the wild, it checks if the property is undefined by checking if the property is set to the string value 'undefined'. So if the key does not exist at all, it still tries to draw on the feature, which produces an error. I needed to modify the plugin to do this (and you can take care of issue #1 in the process).Drawing issues. The big issue is that it loves to draw labels upside down (even in the screenshot on its GitHub page), which is bad cartography. A smaller issue is that the labels follow the curve of the contours, which is nice, except on sharp curves where the label becomes unreadable.
By default, the plugin cant parse feature.properties as the isolines function places it in an array. It’s looking for a key, so it’s expecting feature.properties to be an object.
The plugin has a filter so that it doesn’t attempt to draw labels on all features, just the ones with an appropriate properties object. For some reason, I think maybe due to how GeoJSON files can be found in the wild, it checks if the property is undefined by checking if the property is set to the string value 'undefined'. So if the key does not exist at all, it still tries to draw on the feature, which produces an error. I needed to modify the plugin to do this (and you can take care of issue #1 in the process).
Drawing issues. The big issue is that it loves to draw labels upside down (even in the screenshot on its GitHub page), which is bad cartography. A smaller issue is that the labels follow the curve of the contours, which is nice, except on sharp curves where the label becomes unreadable.
In the end, I downloaded the code and prerequisites into my codebase so I could modify the plugin to filter and read from the feature properties more effectively. To fix the upside down label issue, I modified the base dependency (Canvas-TextPath) to flip all letters 180 degrees if they were upside down, while reversing their order. I also put a heavy clamp on the maximum amount of contour-following rotation, so that it didn’t create unreadable squished labels on curvy lines. Effective contour labeling is debatable — there’s not necessarily anything wrong with perfectly horizontal labels bisecting a contour line, either.
There were also some ‘todo’ comments about setting a custom font so I threw Roboto into the canvas draw commands to match the rest of my website’s layout. Maybe I’ll put a pull request out there some day :)
For point #1 listed above, we can circumvent the issue with arrays by doing a bit of work in the initialization of our isobands GeoJSON layer:
L.geoJSON( ..., { style, onEachFeature: ( feature, layer ) => { if ( !feature.properties[ 0 ] ) return; const contour = feature.properties[ 0 ].value; feature.properties = { contour // probably want to convert unit, add suffix :) } }}
Finally, in the initialization of the renderer I made it filter out shapes with paths that were too small (squished labels), turn on label collisions, and set the fill/stroke colors. This is where TypeScript gets annoying, as no definitions exist for these sketchy (as much as I appreciate their existence) plugins.
const options: any = { collisionFlg: true, propertyName: 'contour', fontStyle: { ... }}return new ( L as any ).ContourLabels( options );
That was all very annoying and frighteningly kludgy, but the renderer actually works nicely when you get it going — it redraws the labels as you pan and zoom.
Streamlines are a little easier as there is a Leaflet plugin that allows for arbitrary shapes or markers to be placed along polylines (not text though, which is why we had to go with the above strategy for contour lines).
The plugin is Leaflet.PolylineDecorator and it does its job pretty well. Once you generate the streamline layer, you can parse it for the LineString features the plugin expects:
const lines = layer.getLayers() .filter( ( layer: any ) => { return layer.feature.geometry.type === "LineString"; } ) .map( (layer: any ) => { const coordinates = layer.feature.geometry.coordinates; coordinates.forEach( coordinate => { coordinate.reverse(); } ); return L.polyline( coordinates ); } );
Yes, you can see I have some typing issues in my codebase.
We’ll also need to set up the pattern for the decorator, which is probably going to be some sort of arrow along the line. I guess the plugin handles rotation of the decorator automatically. Nice.
const pattern = { offset: '10%', repeat: '20%', symbol: L.Symbol.arrowHead( { pixelSize: 8, polygon: true, pathOptions: { stroke: false, fill: true, fillColor: '#000000', fillOpacity: opacity } } )}
Now pass it all to the plugin:
const streamlineArrows = L.polylineDecorator( lines, { patterns: [ pattern ]} );
Finally, you’ll probably want to combine the decorator with the streamline layer itself (let’s call it layer) into a single LayerGroup, for easy management.
L.layerGroup ([layer, streamlineArrows]);
Done! The only issues I encountered is that the plugin always puts the decorator on the overlay map pane (even when I try to circumvent that), which means if you have pane-based layer ordering, you’ll encounter some z-index problems. Maybe another pull request is in order...
Our map works great now, provided you extrapolated from the example code above. But what if we want to distribute the visualizations? We can of course use the Snipping Tool (or equivalent) to manually take a screenshot of the map, but that’s inconsistent. Unfortunately, we just don’t have any great options for downloading the map as we see it, as not everything is rendered onto the canvas (tooltips, annotations, etc.).
Keeping in the spirit of keeping things ̶s̶k̶e̶t̶c̶h̶y̶ ...I mean, client-side, we can further densify our node_modules directory towards a critical mass and use a library like dom-to-image to hopefully render the entire DOM tree of our map container as an image. This actually works pretty well out-of-the-box, but chokes on external web fonts and map layers that use CORS, so be wary.
Once you solve those issues, you can render the map pretty seamlessly, but you’ll need need file-saver to actually save the image to the disk.
import domtoimage from 'dom-to-image';import { saveAs } from 'file-saver';const image = await domtoimage.toJpeg( document.getElementsByClassName( 'map-container' )[ 0 ], { bgcolor: '#ffffff' } )saveAs( image, `my_weather_model_map_works.jpg` );
The performance of domtoimage is not great, so if you’re hoping to automate animated GIF creation, this doesn’t seem like a viable approach, although there is perhaps a way to do it with web workers. Unfortunately, we’ve definitely run into the brick wall of performance constraints on doing everything with JavaScript.
There’s lots of other things you can do with the data, perhaps the most famous example being those fancy animated wind maps. You can query it (hint: use the geoTransform), generate statistics, write a Discord server bot... But of course, you can do this all even easier on a server. Where the client-side rendering shines is in the visualization and interactivity of the weather models. Outside of that, it is difficult to justify the overhead and performance concerns of doing everything in the web browser.
This is certainly not the only way to go about things. Check out what is being done Leaflet.CanvasLayer.Field, for example. The potential of this technology is quickly developing and I’m sure in the next few years more robust and performant tools will become available. In fact, there are even WebAssembly wrappers for GDAL!
I’d like to thank Roger Veciana i Rovira for providing the wonderful resources and libraries that showed me this was even possible, and let me start building right away without having to write low-level raster processing algorithms.
If you attempt to dig up my website, it’s not production-ready and none of the clientside rendering is even available. However, all code and example images come from a working test version. One day... | [
{
"code": null,
"e": 752,
"s": 171,
"text": "Weather enthusiasts, meteorologists, and storm chasers are aware of the myriad of weather model visualization websites out on the web. These platforms allow you to view various parameters, levels, and forecast hours of dozens of different weather models. For example, when preparing for a day of storm chasing, a chaser may look at a few parameters for a certain area — the dewpoint in the morning, the CAPE later in the day, and the HRRR’s simulated reflectivity in the afternoon. Menus, buttons, and sliders are usually provided to switch forecast hours, models, and parameters."
},
{
"code": null,
"e": 1011,
"s": 752,
"text": "Typically, all of these weather model viewers are simply ways for the user to access pre-rendered, nonspatial weather models, despite the original data being geospatial in nature. Though interfaces differ, many things are consistent in weather model viewers:"
},
{
"code": null,
"e": 1243,
"s": 1011,
"text": "Geographic regions are fixed. You can only view preset areas, such as from a list of cities, states, or regions. The output images are fixed in size as well. A few viewers let you zoom in to certain areas and wait for a new render."
},
{
"code": null,
"e": 1437,
"s": 1243,
"text": "Geographic layers and information are scarce or non-existent. You may only have roads or counties visible on top of the weather model image, which can make specific areas difficult to pinpoint."
},
{
"code": null,
"e": 1617,
"s": 1437,
"text": "Many providers have viewers that are generally non-queryable, which means to get the actual value for any given point you need to compare the color of the data against the legend."
},
{
"code": null,
"e": 1823,
"s": 1617,
"text": "Model layer combinations and color schemes are static. You cannot overlay, for instance, wind streamlines at a certain height over another variable, unless the provider has made that combination available."
},
{
"code": null,
"e": 2262,
"s": 1823,
"text": "Though many of the providers have put serious care and thought into the presentation of the data, the aforementioned shortcomings can be significant and aggravating in certain circumstances. For instance, evaluating forecasted snowfall totals in mountainous terrain can be incredibly challenging if you just have county boundaries to orient yourself with, considering that snowfall totals may vary by tens of inches over just a few miles."
},
{
"code": null,
"e": 2288,
"s": 2262,
"text": "Consider the below image:"
},
{
"code": null,
"e": 2424,
"s": 2288,
"text": "Even as a forecaster with a geography degree I struggle with getting useful data out of this graphic. Looking at the state of Colorado:"
},
{
"code": null,
"e": 2771,
"s": 2424,
"text": "Where is Steamboat in relation to that yellow isoband in north Colorado? Is it in the blue or in the green? (this would be the difference between 2\" and 6\" of snow).On I-70, how does snowfall distribution change from the east of Vail Pass to west of it?How much snow is the Gore Range getting compared to the Tenmile Range to its immediate south?"
},
{
"code": null,
"e": 2937,
"s": 2771,
"text": "Where is Steamboat in relation to that yellow isoband in north Colorado? Is it in the blue or in the green? (this would be the difference between 2\" and 6\" of snow)."
},
{
"code": null,
"e": 3026,
"s": 2937,
"text": "On I-70, how does snowfall distribution change from the east of Vail Pass to west of it?"
},
{
"code": null,
"e": 3120,
"s": 3026,
"text": "How much snow is the Gore Range getting compared to the Tenmile Range to its immediate south?"
},
{
"code": null,
"e": 3398,
"s": 3120,
"text": "If you do enough forecasting in Colorado, you’ll eventually have the county outlines vs. mountain range relationship memorized down to the mile, because that’s usually all you have to work with when looking at the distribution of weather across the state on many model viewers."
},
{
"code": null,
"e": 4003,
"s": 3398,
"text": "That said, it is important to mention the benefits of these platforms — the most obvious being the use of pre-rendered static images. These are fast and it is easy to load all forecast hours of a model in just a few seconds, and you can often easily have the server generate an animated GIF of the data. The fixed regions prevent ‘misuse’ of the data — such as zooming in to a resolution beyond what the weather model is suited for. These two factors allow for consistent weather model visualization, which is helpful if you are downloading the images and archiving them for comparison or redistribution."
},
{
"code": null,
"e": 4761,
"s": 4003,
"text": "In a previous article, I discussed how you can build and automate your own weather model visualizer. This technique had an interesting twist in that, though the server is still rendering the data, it is serving it as a geospatial layer (OGC WMS) that can be added to interactive web maps. This strikes an nice balance between the performance of pre-rendered static images and the interactivity of fully geospatial data. I will show you how to take this one step farther and do the rendering entirely in the browser, no server needed! Per my link above, this article will assume you have the weather models available in GeoTIFF format and projected to EPSG:4326. You can convert raw weather model data (in GRIB2 format) to GeoTIFF with just one GDAL command."
},
{
"code": null,
"e": 5107,
"s": 4761,
"text": "The disadvantages of rendering weather model data on the client, using a web browser, are plentiful — but there are some potential use cases for the technology. Web development in the year 2020 seems to be just mature and powerful enough to make this an actually viable proposition for certain purposes. Here are the main issues we’ll encounter:"
},
{
"code": null,
"e": 5226,
"s": 5107,
"text": "Slowness. JavaScript is not an ideal language to turn raw multidimensional rasters into RGB images or vector isobands."
},
{
"code": null,
"e": 5299,
"s": 5226,
"text": "Data use. The raw weather model data is not as compact as a simple JPEG."
},
{
"code": null,
"e": 5419,
"s": 5299,
"text": "Compatibility. The final code we write wont work in Internet Explorer, and it will perform miserably on older hardware."
},
{
"code": null,
"e": 5470,
"s": 5419,
"text": "In contrast, here are some benefits we will enjoy:"
},
{
"code": null,
"e": 5675,
"s": 5470,
"text": "The ability to present the data on a fully interactive web map, which means we can add as many layers of geographic data (or other model parameters) as we want, and style it however we want, in real-time."
},
{
"code": null,
"e": 5984,
"s": 5675,
"text": "The data can be accessed directly, such as to query points or areas for the raw model data. This goes beyond just clicking on a map and getting the data at a point — a use case may be the ability to define a list of locations or set of points that present the data in a tabular format or overlaid on the map."
},
{
"code": null,
"e": 6500,
"s": 5984,
"text": "The ability to render weather model data, or combinations of the data, in any way we choose — as a raster, as isobands, as isolines (isopleths/contours), as streamlines, etc. The rendering, styling (for instance, width of the contours), and color bands can all be modified by the user (if desired) and update the visualization instantaneously. Various models can even be combined mathematically to produce specific visualizations, instead of having to set up the automated processing scripts to do so ahead of time."
},
{
"code": null,
"e": 6568,
"s": 6500,
"text": "We also have a few strategies to alleviate some of the pain points:"
},
{
"code": null,
"e": 6708,
"s": 6568,
"text": "Use web workers to process and render the GeoTIFFs. This will spread the intensive calculations across the various cores of the user’s CPU."
},
{
"code": null,
"e": 6956,
"s": 6708,
"text": "Use cloud-optimized GeoTIFFs (COGs) or the WCS standard to stream the raw data to the user only for the region and scale they are interested in. In addition, applying appropriate compression to the GeoTIFFs can bring them down to reasonable sizes."
},
{
"code": null,
"e": 7519,
"s": 6956,
"text": "With those points in mind, can you think of some use cases where you might enjoy the benefits of client-side rendering? For me, the quality of the visualizations comes immediately to mind. I used to have custom QGIS projects to export nice-looking maps with weather model data, but there was still manual labor involved. With a well-presented web browser visualization platform, I can do the analysis across multiple models, parameters, and forecast hours quickly while being able to export the weather model graphic and map for redistribution with just a click."
},
{
"code": null,
"e": 8138,
"s": 7519,
"text": "There were also some specific issues I encountered in my previously-mentioned article about using MapServer to distribute the weather model data. These issues were all related to visualization products where the graphics are heavily removed from the data itself, requiring various rasters to be rendered into a final RGB image (for example, streamlines or wind barbs on top of a wind speed raster) — which is incompatible with the scale and styling agnostic model data distribution strategy model I intended to employ with MapServer. These issues were fairly trivial to tackle when handled in the web browser, however:"
},
{
"code": null,
"e": 9138,
"s": 8138,
"text": "Weather model combination calculations. Several popular weather model visualizations are not possible simply by distributing the converted data without rendering an RGB image. The best example is Composite Reflectivity + Precipitation Type, which shows the simulated radar as you might expect — rain shows up with the typical color scale of green-yellow-red, while snow displays as shades of blue. This actually requires a combination of at least three different weather model parameter rasters, or five if you want to handle all precipitation types (ice pellets and frozen rain). There’s no way that I know of to do this on-the-fly in MapServer, as different color scales need to be used based on the precipitation type and combined into the final image. A more simple example is that wind direction in most models is not a single parameter, but instead two rasters (a horizontal and vertical vector component) that need to be combined with trigonometry to calculate the actual direction and speed."
},
{
"code": null,
"e": 9386,
"s": 9138,
"text": "Wind streamlines. MapServer is capable of producing contours from rasters, or even directional arrows across a raster field, but streamlines are not possible. Yet many popular products rely on streamlines to show things like mid-atmospheric winds."
},
{
"code": null,
"e": 9976,
"s": 9386,
"text": "One thing you may have noticed in the above examples is that, while serviceable, the visualizations don’t look that great. The images are small and the data is cramped, which doesn’t make things easy for forecasters. They’re even more troublesome when redistributed to weather forecast readers, who are likely not data geeks and just want to know where they should ski next weekend. I suppose one could concede that the pixelated, late-90s aesthetic of them does give a sense of pure data authority, and they certainly don’t waste any time on doing anything besides conveying the raw data."
},
{
"code": null,
"e": 10196,
"s": 9976,
"text": "Let’s take a look at what weather models may look like when rendered entirely in the web browser. These were taken from my website and are used in my forecasts. First off, here’s the interface I built for it in Angular:"
},
{
"code": null,
"e": 10224,
"s": 10196,
"text": "Some example output images:"
},
{
"code": null,
"e": 10386,
"s": 10224,
"text": "Now, let’s zoom in on the interactive map and enable some other layers. When I say adjustable, I mean this can be done in real-time, by the user, on the webpage:"
},
{
"code": null,
"e": 10422,
"s": 10386,
"text": "How about a layer with streamlines?"
},
{
"code": null,
"e": 10703,
"s": 10422,
"text": "We even have the dreaded Composite Reflectivity + Type layer working properly. You can see the snow as dark blues over the Rockies, with very light rain as greys (and, well, sorry about the slightly misleading light blue color) in Nebraska. This was all calculated in the browser."
},
{
"code": null,
"e": 10957,
"s": 10703,
"text": "Here are the main steps needed to accomplish client-side weather model rendering, once you have your web map in place. I used Leaflet, but ended up needing to extend it so much that OpenLayers may likely be more suitable if you’re starting from scratch."
},
{
"code": null,
"e": 12417,
"s": 10957,
"text": "Fetch the GeoTIFF data for the appropriate model, timestamp, parameter, level, and forecast hour, and read the stream as an ArrayBuffer.Parse the ArrayBuffer to get the geographic information and a nested array of raw data. Geotiff.js is the go-to library for this, although it does not play nicely with Angular unless you import the minified version. You’ll want to cache this data in case you want to make queries against it or re-render the visualizations.Pull out the appropriate band’s data (for multidimensional data, such as multiple forecast hours in one TIFF or multiple parameters in one) and use web workers to run a marching squares algorithm on the nested data array which you can use to produce isobands (polygons) or isolines (polylines), depending on if you want filled/colorized data or contours. You can use a library like raster-marching-squares. For streamlines, you can use the raster-streamlines library. This is the most computationally-expensive step. You’re going to want to cache all this data once it is calculated.Apply the necessary geographic transform to the isobands and isolines as you create them, and then supply them to your web map. For instance, in Leaflet, I make this data available as an L.GeoJSON layer. Make sure to supply the value of the data to each band or line so that it can be styled appropriately. Add it to the map.Add other functionality, such as point querying and visualization download (“Save as JPEG”)."
},
{
"code": null,
"e": 12554,
"s": 12417,
"text": "Fetch the GeoTIFF data for the appropriate model, timestamp, parameter, level, and forecast hour, and read the stream as an ArrayBuffer."
},
{
"code": null,
"e": 12878,
"s": 12554,
"text": "Parse the ArrayBuffer to get the geographic information and a nested array of raw data. Geotiff.js is the go-to library for this, although it does not play nicely with Angular unless you import the minified version. You’ll want to cache this data in case you want to make queries against it or re-render the visualizations."
},
{
"code": null,
"e": 13462,
"s": 12878,
"text": "Pull out the appropriate band’s data (for multidimensional data, such as multiple forecast hours in one TIFF or multiple parameters in one) and use web workers to run a marching squares algorithm on the nested data array which you can use to produce isobands (polygons) or isolines (polylines), depending on if you want filled/colorized data or contours. You can use a library like raster-marching-squares. For streamlines, you can use the raster-streamlines library. This is the most computationally-expensive step. You’re going to want to cache all this data once it is calculated."
},
{
"code": null,
"e": 13788,
"s": 13462,
"text": "Apply the necessary geographic transform to the isobands and isolines as you create them, and then supply them to your web map. For instance, in Leaflet, I make this data available as an L.GeoJSON layer. Make sure to supply the value of the data to each band or line so that it can be styled appropriately. Add it to the map."
},
{
"code": null,
"e": 13881,
"s": 13788,
"text": "Add other functionality, such as point querying and visualization download (“Save as JPEG”)."
},
{
"code": null,
"e": 14018,
"s": 13881,
"text": "Let’s dig in and go over specifics! I will be using TypeScript and ES6 syntax direct from my codebase, which uses the Angular framework."
},
{
"code": null,
"e": 14070,
"s": 14018,
"text": "This is the easiest part. Some strategies might be:"
},
{
"code": null,
"e": 14124,
"s": 14070,
"text": "Simply have the files downloadable from a web server."
},
{
"code": null,
"e": 14239,
"s": 14124,
"text": "Create an API that retrieves the appropriate file for the model, parameter, forecast hour, geographic region, etc."
},
{
"code": null,
"e": 14271,
"s": 14239,
"text": "✔️ Use Cloud-Optimized GeoTIFFs"
},
{
"code": null,
"e": 14372,
"s": 14271,
"text": "Use MapServer or another geographic data server to handle WCS requests and return data as a GeoTIFF."
},
{
"code": null,
"e": 14807,
"s": 14372,
"text": "Think about how you want your GeoTIFFs to be structured. To save on data, you likely want one TIFF returned per model, parameter, level, forecast hour, etc. However, you could store multiple forecast hours as several bands in one TIFF if the client wants to preload everything (for instance, to use a slider to view all the forecast hours). This will create an initial, longer download time but speed up overall parsing time slightly."
},
{
"code": null,
"e": 15329,
"s": 14807,
"text": "Don’t forget about compression. Though you can use JPEG compression on TIFFs to get their filesize down to, well, something comparable a JPEG’s — this isn’t responsible use of the data. These are not images, but instead arrays of raw data, the integrity of which should be respected before they are rendered. Also, I don’t think the geotiff.js library can handle that method of compression. I have found that a high level (zlevel = 9) of deflate reduced sizes by up to 50% without impacting parsing performance too badly."
},
{
"code": null,
"e": 15589,
"s": 15329,
"text": "You’ll likely retrieve the GeoTIFF with fetch or using the built-in functions of geotiff.js. The library can natively read cloud-optimized GeoTIFFs! If using a regular GeoTIFF, you’ll need to read the fetch request stream (if you made one) as an ArrayBuffer :"
},
{
"code": null,
"e": 15694,
"s": 15589,
"text": "const response = await fetch( <the url of your tiff> );const arrayBuffer = await response.arrayBuffer();"
},
{
"code": null,
"e": 15856,
"s": 15694,
"text": "Following the above example, we can use geotiff.js to parse the ArrayBuffer into a GeoTiff object. We can retrieve the actual image data itself from that object:"
},
{
"code": null,
"e": 15956,
"s": 15856,
"text": "const geoTiff = await fromArrayBuffer( arrayBuffer );const geoTiffImage = await geoTiff.getImage();"
},
{
"code": null,
"e": 16046,
"s": 15956,
"text": "Don’t forget to grab the image metadata and geographic data as well, we’ll need it later:"
},
{
"code": null,
"e": 16367,
"s": 16046,
"text": "const tiffWidth = geoTiffImage.getWidth();const tiffHeight = geoTiffImage.getHeight();const tiepoint = geoTiffImage.getTiePoints()[ 0 ];const pixelScale = geoTiffImage.getFileDirectory().ModelPixelScale;const geoTransform = [ tiepoint.x, pixelScale[ 0 ], 0, tiepoint.y, 0, -1 * pixelScale[ 1 ] ];"
},
{
"code": null,
"e": 16453,
"s": 16367,
"text": "If you have multiple bands in the image, you can get the exact number of them easily:"
},
{
"code": null,
"e": 16508,
"s": 16453,
"text": "const bands = await geoTiffImage.getSamplesPerPixel();"
},
{
"code": null,
"e": 17083,
"s": 16508,
"text": "Besides wind barbs (which can be nice for weather forecasters, but pretty useless for the general public), I can’t think of any other ways of rendering the weather model data besides isobands, isolines, or streamlines. Isobands are polygons that pertain to specific ranges of the data. You can use them to generate colorful temperature or snow accumulation maps. Isolines (or isopleths) are contour lines drawn at the boundary of data ranges. Streamlines help visualize data that has both a velocity and a direction. These can all be created as vectors and added to the map."
},
{
"code": null,
"e": 17275,
"s": 17083,
"text": "We will need to crack the GeoTIFF data open to build our geographic vectors. You can also just render it as an image to a canvas, but I wont cover that here (see the Acknowledgments section)."
},
{
"code": null,
"e": 17349,
"s": 17275,
"text": "Get the image data for the appropriate band (where i is the band number):"
},
{
"code": null,
"e": 17418,
"s": 17349,
"text": "const bandData = await geoTiffImage.readRasters({ samples: [ i ] });"
},
{
"code": null,
"e": 17456,
"s": 17418,
"text": "Build a nested array of the raw data:"
},
{
"code": null,
"e": 17696,
"s": 17456,
"text": "const dataArr = new Array( tiffHeight );for ( let i = 0; i < tiffHeight; i++ ) { dataArr[ i ] = new Array( tiffWidth ); for ( let ii = 0; ii < tiffWidth; ii++ ) { dataArr[ i ][ ii ] = bandData[ 0 ][ ii + i * tiffWidth ]; }}"
},
{
"code": null,
"e": 17994,
"s": 17696,
"text": "We’re going to use the raster-marching-squares library to generate our features, but for performance purposes I want to run it as a web worker so that the user interface doesn’t lock up. If you’re using Angular, it is easy to set a web worker up with Angular-CLI by running ng generate web-worker."
},
{
"code": null,
"e": 18073,
"s": 17994,
"text": "Inside of the web worker, we’ll import raster-marching-squares as rastertools:"
},
{
"code": null,
"e": 18129,
"s": 18073,
"text": "import * as rastertools from 'raster-marching-squares';"
},
{
"code": null,
"e": 18273,
"s": 18129,
"text": "This provides isoband and isoline rendering as rastertools.isobands() or rastertools.isolines(). Both functions expect the following arguments:"
},
{
"code": null,
"e": 18305,
"s": 18273,
"text": "The nested data array (dataArr)"
},
{
"code": null,
"e": 18349,
"s": 18305,
"text": "The projection of the raster (geoTransform)"
},
{
"code": null,
"e": 18870,
"s": 18349,
"text": "The intervals to break / space the data at. These intervals will always be present in the output from these functions, regardless of if there are actually any features in them or not. For instance, if you passed [-5,0,5] as the interval for a temperature model, you would receive three isobands or isolines pertaining to -5 degrees, 0 degrees, and 5 degrees. If the weather model had data within those ranges, those isolines or isobands would have geometry containing those regions. If not, they would be empty features."
},
{
"code": null,
"e": 19397,
"s": 18870,
"text": "We’ll eventually want to style the isobands or put labels on the isolines, so one thing I did was set up color scales for all of the various parameters I wanted to visualize, passing a color for a specific value. I then set up a function that would produce a fixed number of intervals (such as 100 — smooth, but takes awhile to calculate) from the color scale and use tinygradient to produce the CSS representation of that color scale to use for the legend. For instance, the color scale for snow accumulation looks like this:"
},
{
"code": null,
"e": 19690,
"s": 19397,
"text": "\"SnowAccumM\": [ { value: 1.8288, color: \"#ffcc01\" }, { value: 1.2192, color: \"#ff4501\" }, { value: 0.6096, color: \"#e51298\" }, { value: 0.3048, color: \"#9f0ded\" }, { value: 0.0762, color: \"#5993ff\" }, { value: 0.00254, color: \"#d6dadd\" }, { value: 0, color: \"#ffffff\" }],"
},
{
"code": null,
"e": 19951,
"s": 19690,
"text": "The interval creation function also bounds the intervals array with Number.MAX_SAFE_INTEGER and its negative equivalent. If you do it right, and throw some unit conversion in there, you can handle the isoband creation, styling, and legend in one compact class."
},
{
"code": null,
"e": 20127,
"s": 19951,
"text": "The worker that will run the isobands or isolines function will listen for the three necessary arguments. We’ll also pass in a type parameter to tell it which function to use:"
},
{
"code": null,
"e": 20431,
"s": 20127,
"text": "addEventListener( 'message', ( { data } ) => { try { const features = rastertools[type]( data.data, data.geoTransform, data.intervals ); postMessage ( { features } ); } catch ( err ) { postMessage( { error: err.message } ); }}"
},
{
"code": null,
"e": 20791,
"s": 20431,
"text": "The function has been wrapped in a try...catch, which is a nice idea, but useless in practice, because when the function screws up, it tends to just get stuck in a do...while loop until you run out of memory. This is likely due to some of the thousands of weather model rasters I convert a day getting corrupted, which I need to fix but...pull request anyone?"
},
{
"code": null,
"e": 20956,
"s": 20791,
"text": "Now we can call the worker, pass it the necessary arguments, and wait for a response. You don’t have to use a Promise, it just suited me for my particular workflow:"
},
{
"code": null,
"e": 21439,
"s": 20956,
"text": "const type = 'isobands';const rastertoolsWorker = new Worker( `../workers/rastertools.worker`, // the worker class ☭ { type: `module` } );new Promise( ( resolve, reject ) => { rastertoolsWorker.postMessage( { dataArr, geoTransform, intervals, // array of numbers type } ); rastertoolsWorker.addEventListener( 'message', event => resolve( event.data ) );} ).then (...) // the isobands are generated!"
},
{
"code": null,
"e": 21553,
"s": 21439,
"text": "If you did 100 intervals, this might take a little while. Your laptop fan might kick on with surprising ferocity."
},
{
"code": null,
"e": 21726,
"s": 21553,
"text": "Note that I did not mention streamlines. If you use the raster-streamlines library, this calculation is refreshingly fast and likely doesn’t need to be put in a web worker."
},
{
"code": null,
"e": 22368,
"s": 21726,
"text": "If you used raster-marching-squares, this part is all taken care of for you. Basically, the vector features are generated from the rasters, and need to be tied back to where those pixels are actually located geographically. We can use the geoTransform provided by geotiff.js to get that transformation information (and hopefully your GeoTIFF was originally in EPSG:4326). We also want the information as a GeoJSON, which is an agnostic collection of geometries. Again, the library provides this collection, we just need to wrap it with L.geoJSON(<the features>) to create a layer we can add to the map. raster-streamlines works the same way."
},
{
"code": null,
"e": 22602,
"s": 22368,
"text": "The library also makes available the isoband’s data range in the properties of each feature. We can use this to style the isobands or add labels to the isolines. This is the other tricky part of the process, which I’ll cover shortly."
},
{
"code": null,
"e": 22949,
"s": 22602,
"text": "You also want to think about what renderer you want the web map to use. By default, Leaflet uses SVG. If you have huge, detailed isobands, performance will be abysmal. I instead opted to use a canvas-based renderer instead, which comes with a few headaches, but allows for acceptable performance once the features have been drawn onto the canvas."
},
{
"code": null,
"e": 22986,
"s": 22949,
"text": "We’re ready to style our layers now."
},
{
"code": null,
"e": 23058,
"s": 22986,
"text": "These are the easiest to style. You just need to pass a style function:"
},
{
"code": null,
"e": 23316,
"s": 23058,
"text": "L.geoJSON(<the features>, { style: feature => { return { fillColor: getColor( feature.properties[ 0 ].lowerValue ), weight: 1.5, opacity: 1, color: getColor( feature.properties[ 0 ].lowerValue ), fillOpacity: 1 };});"
},
{
"code": null,
"e": 23570,
"s": 23316,
"text": "getColor() is a function I wrote that takes a value and gets the interpolated color (using tinygradient) from the appropriate color scale as mentioned before. feature.properties has been populated with the value range, thanks to raster-marching-squares."
},
{
"code": null,
"e": 23996,
"s": 23570,
"text": "You’ll notice I also set the stroke/outline weight to 1.5, as there are often tiny slivers in between the polygons if they aren’t given outlines. With outlines in place, an important caveat is that if you lower the opacity of the layer (via the style function), the overlap of the fills and outlines will become noticeable. Instead, you’ll need to have the layer on its own map pane and change the opacity of the entire pane."
},
{
"code": null,
"e": 24043,
"s": 23996,
"text": "Styling the isolines themselves is super easy:"
},
{
"code": null,
"e": 24125,
"s": 24043,
"text": "return feature => { return { weight: 1.5, color: '#000000' }}"
},
{
"code": null,
"e": 24434,
"s": 24125,
"text": "But what about labels? This is actually very tricky. Since we are using a canvas renderer, the Leaflet plugin for drawing polyline labels is out of the question, as it only works on SVG. I don’t want to use different renderers for each layer either, in the case of overlaying contours/isolines onto isobands."
},
{
"code": null,
"e": 24754,
"s": 24434,
"text": "In this case, I found an awkwardly-named plugin (Leaflet.streetlabels) which does draw labels along polylines in the canvas renderer, by actually extending the renderer (so it is not a per-layer solution). It has a couple dependencies (one of which isn’t available via npm) so getting it set up was not straightforward."
},
{
"code": null,
"e": 24832,
"s": 24754,
"text": "There are a number of modifications necessary to get labels working properly."
},
{
"code": null,
"e": 25816,
"s": 24832,
"text": "By default, the plugin cant parse feature.properties as the isolines function places it in an array. It’s looking for a key, so it’s expecting feature.properties to be an object.The plugin has a filter so that it doesn’t attempt to draw labels on all features, just the ones with an appropriate properties object. For some reason, I think maybe due to how GeoJSON files can be found in the wild, it checks if the property is undefined by checking if the property is set to the string value 'undefined'. So if the key does not exist at all, it still tries to draw on the feature, which produces an error. I needed to modify the plugin to do this (and you can take care of issue #1 in the process).Drawing issues. The big issue is that it loves to draw labels upside down (even in the screenshot on its GitHub page), which is bad cartography. A smaller issue is that the labels follow the curve of the contours, which is nice, except on sharp curves where the label becomes unreadable."
},
{
"code": null,
"e": 25995,
"s": 25816,
"text": "By default, the plugin cant parse feature.properties as the isolines function places it in an array. It’s looking for a key, so it’s expecting feature.properties to be an object."
},
{
"code": null,
"e": 26514,
"s": 25995,
"text": "The plugin has a filter so that it doesn’t attempt to draw labels on all features, just the ones with an appropriate properties object. For some reason, I think maybe due to how GeoJSON files can be found in the wild, it checks if the property is undefined by checking if the property is set to the string value 'undefined'. So if the key does not exist at all, it still tries to draw on the feature, which produces an error. I needed to modify the plugin to do this (and you can take care of issue #1 in the process)."
},
{
"code": null,
"e": 26802,
"s": 26514,
"text": "Drawing issues. The big issue is that it loves to draw labels upside down (even in the screenshot on its GitHub page), which is bad cartography. A smaller issue is that the labels follow the curve of the contours, which is nice, except on sharp curves where the label becomes unreadable."
},
{
"code": null,
"e": 27431,
"s": 26802,
"text": "In the end, I downloaded the code and prerequisites into my codebase so I could modify the plugin to filter and read from the feature properties more effectively. To fix the upside down label issue, I modified the base dependency (Canvas-TextPath) to flip all letters 180 degrees if they were upside down, while reversing their order. I also put a heavy clamp on the maximum amount of contour-following rotation, so that it didn’t create unreadable squished labels on curvy lines. Effective contour labeling is debatable — there’s not necessarily anything wrong with perfectly horizontal labels bisecting a contour line, either."
},
{
"code": null,
"e": 27638,
"s": 27431,
"text": "There were also some ‘todo’ comments about setting a custom font so I threw Roboto into the canvas draw commands to match the rest of my website’s layout. Maybe I’ll put a pull request out there some day :)"
},
{
"code": null,
"e": 27781,
"s": 27638,
"text": "For point #1 listed above, we can circumvent the issue with arrays by doing a bit of work in the initialization of our isobands GeoJSON layer:"
},
{
"code": null,
"e": 28064,
"s": 27781,
"text": "L.geoJSON( ..., { style, onEachFeature: ( feature, layer ) => { if ( !feature.properties[ 0 ] ) return; const contour = feature.properties[ 0 ].value; feature.properties = { contour // probably want to convert unit, add suffix :) } }}"
},
{
"code": null,
"e": 28380,
"s": 28064,
"text": "Finally, in the initialization of the renderer I made it filter out shapes with paths that were too small (squished labels), turn on label collisions, and set the fill/stroke colors. This is where TypeScript gets annoying, as no definitions exist for these sketchy (as much as I appreciate their existence) plugins."
},
{
"code": null,
"e": 28536,
"s": 28380,
"text": "const options: any = { collisionFlg: true, propertyName: 'contour', fontStyle: { ... }}return new ( L as any ).ContourLabels( options );"
},
{
"code": null,
"e": 28695,
"s": 28536,
"text": "That was all very annoying and frighteningly kludgy, but the renderer actually works nicely when you get it going — it redraws the labels as you pan and zoom."
},
{
"code": null,
"e": 28917,
"s": 28695,
"text": "Streamlines are a little easier as there is a Leaflet plugin that allows for arbitrary shapes or markers to be placed along polylines (not text though, which is why we had to go with the above strategy for contour lines)."
},
{
"code": null,
"e": 29095,
"s": 28917,
"text": "The plugin is Leaflet.PolylineDecorator and it does its job pretty well. Once you generate the streamline layer, you can parse it for the LineString features the plugin expects:"
},
{
"code": null,
"e": 29459,
"s": 29095,
"text": "const lines = layer.getLayers() .filter( ( layer: any ) => { return layer.feature.geometry.type === \"LineString\"; } ) .map( (layer: any ) => { const coordinates = layer.feature.geometry.coordinates; coordinates.forEach( coordinate => { coordinate.reverse(); } ); return L.polyline( coordinates ); } );"
},
{
"code": null,
"e": 29518,
"s": 29459,
"text": "Yes, you can see I have some typing issues in my codebase."
},
{
"code": null,
"e": 29714,
"s": 29518,
"text": "We’ll also need to set up the pattern for the decorator, which is probably going to be some sort of arrow along the line. I guess the plugin handles rotation of the decorator automatically. Nice."
},
{
"code": null,
"e": 29998,
"s": 29714,
"text": "const pattern = { offset: '10%', repeat: '20%', symbol: L.Symbol.arrowHead( { pixelSize: 8, polygon: true, pathOptions: { stroke: false, fill: true, fillColor: '#000000', fillOpacity: opacity } } )}"
},
{
"code": null,
"e": 30029,
"s": 29998,
"text": "Now pass it all to the plugin:"
},
{
"code": null,
"e": 30113,
"s": 30029,
"text": "const streamlineArrows = L.polylineDecorator( lines, { patterns: [ pattern ]} );"
},
{
"code": null,
"e": 30270,
"s": 30113,
"text": "Finally, you’ll probably want to combine the decorator with the streamline layer itself (let’s call it layer) into a single LayerGroup, for easy management."
},
{
"code": null,
"e": 30312,
"s": 30270,
"text": "L.layerGroup ([layer, streamlineArrows]);"
},
{
"code": null,
"e": 30588,
"s": 30312,
"text": "Done! The only issues I encountered is that the plugin always puts the decorator on the overlay map pane (even when I try to circumvent that), which means if you have pane-based layer ordering, you’ll encounter some z-index problems. Maybe another pull request is in order..."
},
{
"code": null,
"e": 31011,
"s": 30588,
"text": "Our map works great now, provided you extrapolated from the example code above. But what if we want to distribute the visualizations? We can of course use the Snipping Tool (or equivalent) to manually take a screenshot of the map, but that’s inconsistent. Unfortunately, we just don’t have any great options for downloading the map as we see it, as not everything is rendered onto the canvas (tooltips, annotations, etc.)."
},
{
"code": null,
"e": 31398,
"s": 31011,
"text": "Keeping in the spirit of keeping things ̶s̶k̶e̶t̶c̶h̶y̶ ...I mean, client-side, we can further densify our node_modules directory towards a critical mass and use a library like dom-to-image to hopefully render the entire DOM tree of our map container as an image. This actually works pretty well out-of-the-box, but chokes on external web fonts and map layers that use CORS, so be wary."
},
{
"code": null,
"e": 31541,
"s": 31398,
"text": "Once you solve those issues, you can render the map pretty seamlessly, but you’ll need need file-saver to actually save the image to the disk."
},
{
"code": null,
"e": 31786,
"s": 31541,
"text": "import domtoimage from 'dom-to-image';import { saveAs } from 'file-saver';const image = await domtoimage.toJpeg( document.getElementsByClassName( 'map-container' )[ 0 ], { bgcolor: '#ffffff' } )saveAs( image, `my_weather_model_map_works.jpg` );"
},
{
"code": null,
"e": 32106,
"s": 31786,
"text": "The performance of domtoimage is not great, so if you’re hoping to automate animated GIF creation, this doesn’t seem like a viable approach, although there is perhaps a way to do it with web workers. Unfortunately, we’ve definitely run into the brick wall of performance constraints on doing everything with JavaScript."
},
{
"code": null,
"e": 32615,
"s": 32106,
"text": "There’s lots of other things you can do with the data, perhaps the most famous example being those fancy animated wind maps. You can query it (hint: use the geoTransform), generate statistics, write a Discord server bot... But of course, you can do this all even easier on a server. Where the client-side rendering shines is in the visualization and interactivity of the weather models. Outside of that, it is difficult to justify the overhead and performance concerns of doing everything in the web browser."
},
{
"code": null,
"e": 32940,
"s": 32615,
"text": "This is certainly not the only way to go about things. Check out what is being done Leaflet.CanvasLayer.Field, for example. The potential of this technology is quickly developing and I’m sure in the next few years more robust and performant tools will become available. In fact, there are even WebAssembly wrappers for GDAL!"
},
{
"code": null,
"e": 33173,
"s": 32940,
"text": "I’d like to thank Roger Veciana i Rovira for providing the wonderful resources and libraries that showed me this was even possible, and let me start building right away without having to write low-level raster processing algorithms."
}
] |
How do I convert a datetime to a UTC timestamp in Python? | You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object. If you have the datetime object in local timezone, first replace the timezone info and then fetch the time.
from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp)
This will give the output −
1445212800.0
If you're on Python 2, then you can use the total_seconds function to get the total seconds since epoch. And if you want to get rid of the timestamp, you can first subtract time from 1 Jan 1970.
from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
print(timestamp)
This will give the output −
1445212800.0 | [
{
"code": null,
"e": 1420,
"s": 1062,
"text": "You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object. If you have the datetime object in local timezone, first replace the timezone info and then fetch the time. "
},
{
"code": null,
"e": 1551,
"s": 1420,
"text": "from datetime import timezone\ndt = datetime(2015, 10, 19)\ntimestamp = dt.replace(tzinfo=timezone.utc).timestamp()\nprint(timestamp)"
},
{
"code": null,
"e": 1579,
"s": 1551,
"text": "This will give the output −"
},
{
"code": null,
"e": 1592,
"s": 1579,
"text": "1445212800.0"
},
{
"code": null,
"e": 1788,
"s": 1592,
"text": "If you're on Python 2, then you can use the total_seconds function to get the total seconds since epoch. And if you want to get rid of the timestamp, you can first subtract time from 1 Jan 1970. "
},
{
"code": null,
"e": 1919,
"s": 1788,
"text": "from datetime import timezone\ndt = datetime(2015, 10, 19)\ntimestamp = (dt - datetime(1970, 1, 1)).total_seconds()\nprint(timestamp)"
},
{
"code": null,
"e": 1947,
"s": 1919,
"text": "This will give the output −"
},
{
"code": null,
"e": 1960,
"s": 1947,
"text": "1445212800.0"
}
] |
How to make page links in HTML Page? | With HTML, easily add page links to an HTML page. Link contact us, about, home or any other external website page using the page links, which gets added inside an HTML document. To make page links in an HTML page, use the <a> and </a> tags, which are the tags used to define the links.
The <a> tag indicates where the link starts and the </a> tag indicates where it ends. Whatever text gets added inside these tags, will work as a link. Add the URL for the link in the <a href=” ”>. Just keep in mind that you should use the <a>...</a> tags inside <body>...</body> tags.
You can try the following code to make page links in an HTML page:
<!DOCTYPE html>
<html>
<head>
<title>HTML Links</title>
</head>
<body>
<h1>Reach us here</h1>
<a href="https://www.tutorialspoint.com/about/contact_us.htm">Contact</a>
</body>
</html> | [
{
"code": null,
"e": 1348,
"s": 1062,
"text": "With HTML, easily add page links to an HTML page. Link contact us, about, home or any other external website page using the page links, which gets added inside an HTML document. To make page links in an HTML page, use the <a> and </a> tags, which are the tags used to define the links."
},
{
"code": null,
"e": 1633,
"s": 1348,
"text": "The <a> tag indicates where the link starts and the </a> tag indicates where it ends. Whatever text gets added inside these tags, will work as a link. Add the URL for the link in the <a href=” ”>. Just keep in mind that you should use the <a>...</a> tags inside <body>...</body> tags."
},
{
"code": null,
"e": 1700,
"s": 1633,
"text": "You can try the following code to make page links in an HTML page:"
},
{
"code": null,
"e": 1915,
"s": 1700,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Links</title>\n </head>\n\n <body>\n <h1>Reach us here</h1>\n <a href=\"https://www.tutorialspoint.com/about/contact_us.htm\">Contact</a>\n </body>\n</html>"
}
] |
How to create a 3D outset and inset border using CSS ? - GeeksforGeeks | 21 May, 2021
In this article, we will create a 3D outset and inset border using CSS. Inset border property makes the content appear embedded (inside the surface) and on the other hand, the outset property makes the content appear embossed (outside the surface). You can achieve this task by using the border-style property that is used to decorate the border.
3D inset border: It is used to define a 3D inset border and its effect depends on the border-color value.
Syntax:
element_name(or selector).inset {border-style: inset;}
Example 1:
HTML
<!DOCTYPE html><html> <head> <style> body { text-align: center; } p { font-size: 30px; margin-top: -50px; } p.inset { border-style: inset; /* Inset style property */ font-size: 40px; margin-top: 30px; } h2 { color: green; font-size: 50px; } </style></head> <body> <h2>GeeksForGeeks</h2> <p>A computer science portal for geeks</p> <p class="inset"> The content of this paragraph is styled using inset property </p> </body> </html>
Output:
3D outset border: It is used to define a 3D outset border and its effect depends on the border-color value.
Syntax:
element_name(or selector).outset {border-style: outset;}
Example 2:
HTML
<!DOCTYPE html><html> <head> <style> body { text-align: center; } p { font-size: 30px; margin-top: -50px; } p.outset { border-style: outset; /* outset style property */ font-size: 40px; margin-top: 30px; } h2 { color: green; font-size: 50px; } </style></head> <body> <h2>GeeksForGeeks</h2> <p>A computer science portal for geeks</p> <p class="outset"> The content of this paragraph is styled using outset property </p> </body> </html>
Output:
akshaysingh98088
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 25723,
"s": 25376,
"text": "In this article, we will create a 3D outset and inset border using CSS. Inset border property makes the content appear embedded (inside the surface) and on the other hand, the outset property makes the content appear embossed (outside the surface). You can achieve this task by using the border-style property that is used to decorate the border."
},
{
"code": null,
"e": 25829,
"s": 25723,
"text": "3D inset border: It is used to define a 3D inset border and its effect depends on the border-color value."
},
{
"code": null,
"e": 25837,
"s": 25829,
"text": "Syntax:"
},
{
"code": null,
"e": 25892,
"s": 25837,
"text": "element_name(or selector).inset {border-style: inset;}"
},
{
"code": null,
"e": 25903,
"s": 25892,
"text": "Example 1:"
},
{
"code": null,
"e": 25908,
"s": 25903,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } p { font-size: 30px; margin-top: -50px; } p.inset { border-style: inset; /* Inset style property */ font-size: 40px; margin-top: 30px; } h2 { color: green; font-size: 50px; } </style></head> <body> <h2>GeeksForGeeks</h2> <p>A computer science portal for geeks</p> <p class=\"inset\"> The content of this paragraph is styled using inset property </p> </body> </html>",
"e": 26557,
"s": 25908,
"text": null
},
{
"code": null,
"e": 26569,
"s": 26561,
"text": "Output:"
},
{
"code": null,
"e": 26681,
"s": 26573,
"text": "3D outset border: It is used to define a 3D outset border and its effect depends on the border-color value."
},
{
"code": null,
"e": 26691,
"s": 26683,
"text": "Syntax:"
},
{
"code": null,
"e": 26750,
"s": 26693,
"text": "element_name(or selector).outset {border-style: outset;}"
},
{
"code": null,
"e": 26763,
"s": 26752,
"text": "Example 2:"
},
{
"code": null,
"e": 26770,
"s": 26765,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } p { font-size: 30px; margin-top: -50px; } p.outset { border-style: outset; /* outset style property */ font-size: 40px; margin-top: 30px; } h2 { color: green; font-size: 50px; } </style></head> <body> <h2>GeeksForGeeks</h2> <p>A computer science portal for geeks</p> <p class=\"outset\"> The content of this paragraph is styled using outset property </p> </body> </html>",
"e": 27424,
"s": 26770,
"text": null
},
{
"code": null,
"e": 27432,
"s": 27424,
"text": "Output:"
},
{
"code": null,
"e": 27449,
"s": 27432,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 27464,
"s": 27449,
"text": "CSS-Properties"
},
{
"code": null,
"e": 27478,
"s": 27464,
"text": "CSS-Questions"
},
{
"code": null,
"e": 27485,
"s": 27478,
"text": "Picked"
},
{
"code": null,
"e": 27489,
"s": 27485,
"text": "CSS"
},
{
"code": null,
"e": 27506,
"s": 27489,
"text": "Web Technologies"
},
{
"code": null,
"e": 27604,
"s": 27506,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27613,
"s": 27604,
"text": "Comments"
},
{
"code": null,
"e": 27626,
"s": 27613,
"text": "Old Comments"
},
{
"code": null,
"e": 27663,
"s": 27626,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27692,
"s": 27663,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27731,
"s": 27692,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 27773,
"s": 27731,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 27820,
"s": 27773,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 27862,
"s": 27820,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27895,
"s": 27862,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27938,
"s": 27895,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27983,
"s": 27938,
"text": "Convert a string to an integer in JavaScript"
}
] |
Distinguish between Finite Automata and Turing Machine | Before understanding the differences between the finite automata (FA) and the turing machine (TM), let us learn about these concepts.
Finite automata is an abstract computing device
It is a mathematical model of a system with discrete inputs, outputs, states and set of transitions from state to state that occurs on input symbol from alphabet Σ
FA can be represented as following in the theory of computation (TOC) −
Graphical (Transition diagram)
Graphical (Transition diagram)
Tabular (Transition table)
Tabular (Transition table)
Mathematical (Transition function)
Mathematical (Transition function)
A Finite automata is a five tuples
M=(Q, Σ, δ,q0,F)
Where,
Q − Finite set called states
Q − Finite set called states
Σ − Finite set called alphabets
Σ − Finite set called alphabets
δ − Q × Σ → Q is the transition function
δ − Q × Σ → Q is the transition function
q0 ε Q is the start or initial state
q0 ε Q is the start or initial state
F − Final or accept state
F − Final or accept state
Turing machines are more powerful than both finite automata and pushdown automata. They are as powerful as any computer we have ever built.
A Turing machine can be formally described as seven tuples ( Q,X, Σ,δ,q0,B,F)
Where,
Q is a finite set of states
Q is a finite set of states
X is the tape alphabet
X is the tape alphabet
Σ is the input alphabet
Σ is the input alphabet
δ is a transition function: δ:QxX→QxXx{left shift, right shift}
δ is a transition function: δ:QxX→QxXx{left shift, right shift}
q0 is the initial state
q0 is the initial state
B is the blank symbol
B is the blank symbol
F is the final state.
F is the final state.
The major differences between Finite automata and Turing machine are given below − | [
{
"code": null,
"e": 1196,
"s": 1062,
"text": "Before understanding the differences between the finite automata (FA) and the turing machine (TM), let us learn about these concepts."
},
{
"code": null,
"e": 1244,
"s": 1196,
"text": "Finite automata is an abstract computing device"
},
{
"code": null,
"e": 1408,
"s": 1244,
"text": "It is a mathematical model of a system with discrete inputs, outputs, states and set of transitions from state to state that occurs on input symbol from alphabet Σ"
},
{
"code": null,
"e": 1480,
"s": 1408,
"text": "FA can be represented as following in the theory of computation (TOC) −"
},
{
"code": null,
"e": 1511,
"s": 1480,
"text": "Graphical (Transition diagram)"
},
{
"code": null,
"e": 1542,
"s": 1511,
"text": "Graphical (Transition diagram)"
},
{
"code": null,
"e": 1569,
"s": 1542,
"text": "Tabular (Transition table)"
},
{
"code": null,
"e": 1596,
"s": 1569,
"text": "Tabular (Transition table)"
},
{
"code": null,
"e": 1631,
"s": 1596,
"text": "Mathematical (Transition function)"
},
{
"code": null,
"e": 1666,
"s": 1631,
"text": "Mathematical (Transition function)"
},
{
"code": null,
"e": 1701,
"s": 1666,
"text": "A Finite automata is a five tuples"
},
{
"code": null,
"e": 1718,
"s": 1701,
"text": "M=(Q, Σ, δ,q0,F)"
},
{
"code": null,
"e": 1725,
"s": 1718,
"text": "Where,"
},
{
"code": null,
"e": 1754,
"s": 1725,
"text": "Q − Finite set called states"
},
{
"code": null,
"e": 1783,
"s": 1754,
"text": "Q − Finite set called states"
},
{
"code": null,
"e": 1815,
"s": 1783,
"text": "Σ − Finite set called alphabets"
},
{
"code": null,
"e": 1847,
"s": 1815,
"text": "Σ − Finite set called alphabets"
},
{
"code": null,
"e": 1888,
"s": 1847,
"text": "δ − Q × Σ → Q is the transition function"
},
{
"code": null,
"e": 1929,
"s": 1888,
"text": "δ − Q × Σ → Q is the transition function"
},
{
"code": null,
"e": 1966,
"s": 1929,
"text": "q0 ε Q is the start or initial state"
},
{
"code": null,
"e": 2003,
"s": 1966,
"text": "q0 ε Q is the start or initial state"
},
{
"code": null,
"e": 2029,
"s": 2003,
"text": "F − Final or accept state"
},
{
"code": null,
"e": 2055,
"s": 2029,
"text": "F − Final or accept state"
},
{
"code": null,
"e": 2195,
"s": 2055,
"text": "Turing machines are more powerful than both finite automata and pushdown automata. They are as powerful as any computer we have ever built."
},
{
"code": null,
"e": 2273,
"s": 2195,
"text": "A Turing machine can be formally described as seven tuples ( Q,X, Σ,δ,q0,B,F)"
},
{
"code": null,
"e": 2280,
"s": 2273,
"text": "Where,"
},
{
"code": null,
"e": 2308,
"s": 2280,
"text": "Q is a finite set of states"
},
{
"code": null,
"e": 2336,
"s": 2308,
"text": "Q is a finite set of states"
},
{
"code": null,
"e": 2359,
"s": 2336,
"text": "X is the tape alphabet"
},
{
"code": null,
"e": 2382,
"s": 2359,
"text": "X is the tape alphabet"
},
{
"code": null,
"e": 2406,
"s": 2382,
"text": "Σ is the input alphabet"
},
{
"code": null,
"e": 2430,
"s": 2406,
"text": "Σ is the input alphabet"
},
{
"code": null,
"e": 2494,
"s": 2430,
"text": "δ is a transition function: δ:QxX→QxXx{left shift, right shift}"
},
{
"code": null,
"e": 2558,
"s": 2494,
"text": "δ is a transition function: δ:QxX→QxXx{left shift, right shift}"
},
{
"code": null,
"e": 2582,
"s": 2558,
"text": "q0 is the initial state"
},
{
"code": null,
"e": 2606,
"s": 2582,
"text": "q0 is the initial state"
},
{
"code": null,
"e": 2628,
"s": 2606,
"text": "B is the blank symbol"
},
{
"code": null,
"e": 2650,
"s": 2628,
"text": "B is the blank symbol"
},
{
"code": null,
"e": 2672,
"s": 2650,
"text": "F is the final state."
},
{
"code": null,
"e": 2694,
"s": 2672,
"text": "F is the final state."
},
{
"code": null,
"e": 2777,
"s": 2694,
"text": "The major differences between Finite automata and Turing machine are given below −"
}
] |
Tk - Canvas Bitmap Widget | Bitmap widget is used to add bitmap to canvas. The syntax for bitmap widget is shown below −
canvasName create bitmap x y options
x and y set the location of bitmap −
The options available for the bitmap widget are listed below in the following table −
-anchor position
The bitmap will be positioned relative to the x and y locations. Center is default an other options are n, s, e, w, ne, se, sw, and nw.
-bitmap name
Defines the bitmap to display. The available bitmaps in Tk include warning, question, questhead, info, hourglass, error, gray12, gray25, gray50, and gray75.
A simple example for bitmap widget is shown below −
#!/usr/bin/wish
canvas .myCanvas -background red -width 100 -height 100
pack .myCanvas
.myCanvas create bitmap 50 50 -bitmap info
When we run the above program, we will get the following output −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2294,
"s": 2201,
"text": "Bitmap widget is used to add bitmap to canvas. The syntax for bitmap widget is shown below −"
},
{
"code": null,
"e": 2332,
"s": 2294,
"text": "canvasName create bitmap x y options\n"
},
{
"code": null,
"e": 2369,
"s": 2332,
"text": "x and y set the location of bitmap −"
},
{
"code": null,
"e": 2455,
"s": 2369,
"text": "The options available for the bitmap widget are listed below in the following table −"
},
{
"code": null,
"e": 2472,
"s": 2455,
"text": "-anchor position"
},
{
"code": null,
"e": 2608,
"s": 2472,
"text": "The bitmap will be positioned relative to the x and y locations. Center is default an other options are n, s, e, w, ne, se, sw, and nw."
},
{
"code": null,
"e": 2621,
"s": 2608,
"text": "-bitmap name"
},
{
"code": null,
"e": 2778,
"s": 2621,
"text": "Defines the bitmap to display. The available bitmaps in Tk include warning, question, questhead, info, hourglass, error, gray12, gray25, gray50, and gray75."
},
{
"code": null,
"e": 2830,
"s": 2778,
"text": "A simple example for bitmap widget is shown below −"
},
{
"code": null,
"e": 2962,
"s": 2830,
"text": "#!/usr/bin/wish\n\ncanvas .myCanvas -background red -width 100 -height 100 \npack .myCanvas\n.myCanvas create bitmap 50 50 -bitmap info"
},
{
"code": null,
"e": 3028,
"s": 2962,
"text": "When we run the above program, we will get the following output −"
},
{
"code": null,
"e": 3035,
"s": 3028,
"text": " Print"
},
{
"code": null,
"e": 3046,
"s": 3035,
"text": " Add Notes"
}
] |
Date Formatting Using printf | Date and time formatting can be done very easily using the printf method. You use a two-letter format, starting with t and ending in one of the letters of the table as shown in the following code.
Live Demo
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date
String str = String.format("Current Date/Time : %tc", date );
System.out.printf(str);
}
}
This will produce the following result −
Current Date/Time : Sat Dec 15 16:37:57 MST 2012
It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted.
The index must immediately follow the % and it must be terminated by a $.
Live Demo
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date
System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);
}
}
This will produce the following result −
Due date: February 09, 2004
Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again.
Live Demo
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display formatted date
System.out.printf("%s %tB %<te, %<tY", "Due date:", date);
}
}
This will produce the following result −
Due date: February 09, 2004 | [
{
"code": null,
"e": 1259,
"s": 1062,
"text": "Date and time formatting can be done very easily using the printf method. You use a two-letter format, starting with t and ending in one of the letters of the table as shown in the following code."
},
{
"code": null,
"e": 1269,
"s": 1259,
"text": "Live Demo"
},
{
"code": null,
"e": 1564,
"s": 1269,
"text": "import java.util.Date;\npublic class DateDemo {\n\n public static void main(String args[]) {\n // Instantiate a Date object\n Date date = new Date();\n\n // display time and date\n String str = String.format(\"Current Date/Time : %tc\", date );\n\n System.out.printf(str);\n }\n}"
},
{
"code": null,
"e": 1605,
"s": 1564,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 1654,
"s": 1605,
"text": "Current Date/Time : Sat Dec 15 16:37:57 MST 2012"
},
{
"code": null,
"e": 1833,
"s": 1654,
"text": "It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted."
},
{
"code": null,
"e": 1907,
"s": 1833,
"text": "The index must immediately follow the % and it must be terminated by a $."
},
{
"code": null,
"e": 1917,
"s": 1907,
"text": "Live Demo"
},
{
"code": null,
"e": 2184,
"s": 1917,
"text": "import java.util.Date;\npublic class DateDemo {\n\n public static void main(String args[]) {\n // Instantiate a Date object\n Date date = new Date();\n\n // display time and date\n System.out.printf(\"%1$s %2$tB %2$td, %2$tY\", \"Due date:\", date);\n }\n}"
},
{
"code": null,
"e": 2225,
"s": 2184,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2253,
"s": 2225,
"text": "Due date: February 09, 2004"
},
{
"code": null,
"e": 2391,
"s": 2253,
"text": "Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again."
},
{
"code": null,
"e": 2401,
"s": 2391,
"text": "Live Demo"
},
{
"code": null,
"e": 2663,
"s": 2401,
"text": "import java.util.Date;\npublic class DateDemo {\n\n public static void main(String args[]) {\n // Instantiate a Date object\n Date date = new Date();\n\n // display formatted date\n System.out.printf(\"%s %tB %<te, %<tY\", \"Due date:\", date);\n }\n}"
},
{
"code": null,
"e": 2704,
"s": 2663,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2732,
"s": 2704,
"text": "Due date: February 09, 2004"
}
] |
How do I declare a two-dimensional array in C++ using new? | A dynamic 2D array is basically an array of pointers to arrays. So you first need to initialize the array of pointers to pointers and then initialize each 1d array in a loop.
#include<iostream>
using namespace std;
int main() {
int rows = 3, cols = 4;
int** arr = new int*[rows];
for(int i = 0; i < rows; ++i)
arr[i] = new int[cols];
return 0;
}
This will create an 2D array of size 3x4. Be vary of clearing the memory in such cases as you'll need to delete the memory in the same way you allocated it but in reverse order, ie, you'll need to first delete 1D arrays then the array of pointers. | [
{
"code": null,
"e": 1237,
"s": 1062,
"text": "A dynamic 2D array is basically an array of pointers to arrays. So you first need to initialize the array of pointers to pointers and then initialize each 1d array in a loop."
},
{
"code": null,
"e": 1425,
"s": 1237,
"text": "#include<iostream>\nusing namespace std;\n\nint main() {\n int rows = 3, cols = 4;\n int** arr = new int*[rows];\n for(int i = 0; i < rows; ++i)\n arr[i] = new int[cols];\n return 0;\n}\n"
},
{
"code": null,
"e": 1673,
"s": 1425,
"text": "This will create an 2D array of size 3x4. Be vary of clearing the memory in such cases as you'll need to delete the memory in the same way you allocated it but in reverse order, ie, you'll need to first delete 1D arrays then the array of pointers."
}
] |
Performing Over-The-Air Update of ESP32 firmware | Say you have a thousand IoT devices out in the field. Now, if one fine day, you find a bug in the production code, and wish to fix it, will you recall all the thousand devices and flash the new firmware in them? Probably not! What you'll prefer to have is a way to update all the devices remotely, over-the-air. OTA updates are very common these days. Every now and then, you keep receiving software updates to your Android or iOS smartphones. Just like software updates can happen remotely, so can firmware updates. In this chapter, we will look at how to update the firmware of ESP32 remotely.
The process is quite simple. The device first downloads the new firmware in chunks and stores it in a separate area of the memory. Let's call this area the 'OTA space'. Let's call the area of the memory where the current code or the application code is stored as the 'Application space'. Once the entire firmware has been downloaded and verified, the device bootloader swings into action. Consider the bootloader as a code written in a separate area of the memory (let's call it the 'Bootloader space'), whose sole purpose is to load the correct code in the Application space every time the device restarts.
Thus, every time the device restarts, the code in the Bootloader space gets executed first. Most of the time, it simply passes control to the code in the Application space. However, after downloading the newer firmware, when the device restarts, the bootloader will notice that a newer application code is available. So it will flash that newer code from the OTA space into the Application space and then give control to the code in the Application space. The result will be that the device firmware will be upgraded.
Now, digressing a bit, the bootloader can also flash the factory reset code from the 'Factory Reset space' to the Application space, if the Application code is corrupted, or a factory reset command is sent. Also, often, the OTA code and the factory reset codes are stored on external storage devices like an SD Card or an external EEPROM or FLASH chip, if the microcontroller doesn't have enough space. However, in the case of ESP32, the OTA code can be stored in the microcontroller's memory itself.
We will be using an example code for this chapter. You can find it in File −> Examples −> Update −> AWS_S3_OTA_Update. It can also be found on GitHub.
This is one of the very detailed examples available for ESP32 on Arduino. The author of this sketch has even provided the expected Serial Monitor output of the sketch in comments. So while much of the code will be self−explanatory through the comments, we'll walk over the broad idea and also cover the important details. This code makes use of the Update library which, like many other libraries, makes working with ESP32 very easy, while keeping the rigorous work under−the−hood.
In this specific example, the author has kept the binary file of the new firmware in an AWS S3 bucket. Providing a detailed overview of AWS S3 is beyond the scope of this chapter, but very broadly, S3 (Simple Storage Service) is a cloud storage service provided by Amazon Web Services (AWS). Think of it like Google Drive. You upload files to your drive and share a link with people to share it. Similarly, you can upload a file to S3 and access it via a link. S3 is much more popular because a lot of other AWS services can interface seamlessly with it. Getting started with AWS S3 will be easy. You can get help from several resources available through a quick Google search. In the comments at the beginning of the sketch as well, a few steps to get started are mentioned.
An important recommendation to note is that you should use your own binary file for this code. The comments at the top of the sketch suggest that you can use the same binary file that the author has used. However, downloading a binary compiled on another machine/ another version of Arduino IDE has been known to cause errors sometimes in the OTA process. Also, using your own binary will make your learning more 'complete'. You can export the binary of any ESP32 sketch by going to Sketch −> Export Compiled Binary. The binary (.bin) file gets saved in the same folder in which your Arduino (.ino) file is saved.
Once your binary is saved, you just need to upload it to S3 and add the link to the bucket and address of the binary file in your code. The binary you save should have some print statement to indicate that it is different from the code you flash in the ESP32. A statement like "Hello from S3" maybe. Also, don't keep the S3 bucket link and bin address in the code as it is.
Alright! Enough talk! Let's begin the walkthrough now. We will begin by including the WiFi and Update libraries.
#include <WiFi.h>
#include <Update.h>
Next, we define a few variables, constants, and also the WiFiClient object. Remember to add your own WiFi credentials and S3 credentials.
WiFiClient client;
// Variables to validate
// response from S3
long contentLength = 0;
bool isValidContentType = false;
// Your SSID and PSWD that the chip needs
// to connect to
const char* SSID = "YOUR−SSID";
const char* PSWD = "YOUR−SSID−PSWD";
// S3 Bucket Config
String host = "bucket−name.s3.ap−south−1.amazonaws.com"; // Host => bucket−name.s3.region.amazonaws.com
int port = 80; // Non https. For HTTPS 443. As of today, HTTPS doesn't work.
String bin = "/sketch−name.ino.bin"; // bin file name with a slash in front.
Next, a helper function getHeaderValue() has been defined, which basically is used to check the value of a particular header. For example, if we get the header "Content-Length: 40" and it is stored in a String called headers, getHeaderValue(headers,"Content−Length: ") will return 40.
// Utility to extract header value from headers
String getHeaderValue(String header, String headerName) {
return header.substring(strlen(headerName.c_str()));
}
Next, the main function execOTA(), which performs the OTA. This function has the entire logic related to the OTA. If you look at the Setup, we simply connect to the WiFi and call the
execOTA() function.
void setup() {
//Begin Serial
Serial.begin(115200);
delay(10);
Serial.println("Connecting to " + String(SSID));
// Connect to provided SSID and PSWD
WiFi.begin(SSID, PSWD);
// Wait for connection to establish
while (WiFi.status() != WL_CONNECTED) {
Serial.print("."); // Keep the serial monitor lit!
delay(500);
}
// Connection Succeed
Serial.println("");
Serial.println("Connected to " + String(SSID));
// Execute OTA Update
execOTA();
}
So you would have understood that understanding the execOTA function means understanding this entire code. Therefore, let's begin the walkthrough of that function.
We begin by connecting to our host, which is the S3 bucket in this case. Once connected, we fetch the bin file from the bucket, using a GET request (refer to the HTTP tutorial for more
information on GET requests)
void execOTA() {
Serial.println("Connecting to: " + String(host));
// Connect to S3
if (client.connect(host.c_str(), port)) {
// Connection Succeed.
// Fecthing the bin
Serial.println("Fetching Bin: " + String(bin));
// Get the contents of the bin file
client.print(String("GET ") + bin + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Cache-Control: no-cache\r\n" +
"Connection: close\r\n\r\n");
Next, we wait for the client to get connected. We give a maximum of 5 seconds for the connection to get established, otherwise we say that the connection has timed out and return.
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println("Client Timeout !");
client.stop();
return;
}
}
Assuming that the code has not returned in the previous step, we have a successful connection established. The expected response from the server is provided in the comments. We begin by parsing that response. The response is read line by line, and each new line is stored in a variable called line. We specifically check for the following 3 things −
If the response status code is 200 (OK)
If the response status code is 200 (OK)
What is the Content-Length
What is the Content-Length
Whether the content type is application/octet-stream (this is the type expected for a binary file)
Whether the content type is application/octet-stream (this is the type expected for a binary file)
The first and third are required, and the second is just for information.
while (client.available()) {
// read line till /n
String line = client.readStringUntil('\n');
// remove space, to check if the line is end of headers
line.trim();
// if the the line is empty,
// this is end of headers
// break the while and feed the
// remaining `client` to the
// Update.writeStream();
if (!line.length()) {
//headers ended
break; // and get the OTA started
}
// Check if the HTTP Response is 200
// else break and Exit Update
if (line.startsWith("HTTP/1.1")) {
if (line.indexOf("200") < 0) {
Serial.println("Got a non 200 status code from server. Exiting OTA Update.");
break;
}
}
// extract headers here
// Start with content length
if (line.startsWith("Content-Length: ")) {
contentLength = atol((getHeaderValue(line, "Content-Length: ")).c_str());
Serial.println("Got " + String(contentLength) + " bytes from server");
}
// Next, the content type
if (line.startsWith("Content-Type: ")) {
String contentType = getHeaderValue(line, "Content-Type: ");
Serial.println("Got " + contentType + " payload.");
if (contentType == "application/octet-stream") {
isValidContentType = true;
}
}
}
With this, the if block that checks if the connection with the server was successful ends. It is followed by the else block, which just prints that we were unable to establish connection to the server.
} else {
// Connect to S3 failed
// May be try?
// Probably a choppy network?
Serial.println("Connection to " + String(host) + " failed. Please check your setup");
// retry??
// execOTA();
}
Next, if we have hopefully received the correct response from the server, we will have a positive contentLength (remember, we had initialized it with 0 at the top and so it will still be 0 if we somehow did not reach that line where we parse the Content−Length header). Also, we will have isValidContentType as true (remember, we had initialized it with false). So we check if both of these
conditions are true and if yes, proceed with the actual OTA. Note that so far, we have only made use of the WiFi library, for interacting with the server. Now if the server interaction turns out to be alright, we will begin use of the Update library, otherwise, we simply print that there was no content in the server response and flush the client. If the response was indeed correct, we first check if there is enough space in the memory to store the OTA file. By default, about 1.2 MB of space is reserved for the OTA file. So if the contentLength exceeds that, Update.begin() will return false. This 1.2MB number can change depending on the partitions of your ESP32.
// check contentLength and content type
if (contentLength && isValidContentType) {
// Check if there is enough to OTA Update
bool canBegin = Update.begin(contentLength);
Now, if we indeed have space to store the OTA file in memory, we begin writing the bytes to the memory area reserved for OTA (the OTA space), using the Update.writeStream() function. If we don't,
we simply print that message and flush the client, and exit the OTA process.
The Update.writeStream() function returns the number of bytes that were written to the OTA space. We then check if the number of bytes written is equal to the contentLength. If the Update is completed, in which case
the Update.end() function will return true, we check if it has finished properly, i.e. all bytes are written, using the Update.isFinished() function. If it returns true, meaning that all bytes have been written, we restart the ESP32, so that the bootloader can flash the new code from the OTA space to the Application space, and our firmware gets upgraded. If it returns false, we print the error received.
// If yes, begin
if (canBegin) {
Serial.println("Begin OTA. This may take 2 − 5 mins to complete. Things might be quite for a while.. Patience!");
// No activity would appear on the Serial monitor
// So be patient. This may take 2 - 5mins to complete
size_t written = Update.writeStream(client);
if (written == contentLength) {
Serial.println("Written : " + String(written) + " successfully");
} else {
Serial.println("Written only : " + String(written) + "/" + String(contentLength) + ". Retry?" );
// retry??
// execOTA();
}
if (Update.end()) {
Serial.println("OTA done!");
if (Update.isFinished()) {
Serial.println("Update successfully completed. Rebooting.");
ESP.restart();
} else {
Serial.println("Update not finished? Something went wrong!");
}
} else {
Serial.println("Error Occurred. Error #: " + String(Update.getError()));
}
} else {
// not enough space to begin OTA
// Understand the partitions and
// space availability
Serial.println("Not enough space to begin OTA");
client.flush();
}
}
Of course, you would have realized by now that we need not do anything in the loop here.
That's it. You've successfully upgraded the firmware of your ESP32 chip remotely. If you are more curious about what each function of the Update library does, you can refer to the comments
in the Update.h file.
OTA on ESP32
OTA on ESP32
54 Lectures
4.5 hours
Frahaan Hussain
20 Lectures
5 hours
Azaz Patel
20 Lectures
4 hours
Azaz Patel
0 Lectures
0 mins
Eduonix Learning Solutions
169 Lectures
12.5 hours
Kalob Taulien
29 Lectures
2 hours
Zenva
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2780,
"s": 2183,
"text": "Say you have a thousand IoT devices out in the field. Now, if one fine day, you find a bug in the production code, and wish to fix it, will you recall all the thousand devices and flash the new firmware in them? Probably not! What you'll prefer to have is a way to update all the devices remotely, over-the-air. OTA updates are very common these days. Every now and then, you keep receiving software updates to your Android or iOS smartphones. Just like software updates can happen remotely, so can firmware updates. In this chapter, we will look at how to update the firmware of ESP32 remotely. "
},
{
"code": null,
"e": 3389,
"s": 2780,
"text": "The process is quite simple. The device first downloads the new firmware in chunks and stores it in a separate area of the memory. Let's call this area the 'OTA space'. Let's call the area of the memory where the current code or the application code is stored as the 'Application space'. Once the entire firmware has been downloaded and verified, the device bootloader swings into action. Consider the bootloader as a code written in a separate area of the memory (let's call it the 'Bootloader space'), whose sole purpose is to load the correct code in the Application space every time the device restarts. "
},
{
"code": null,
"e": 3908,
"s": 3389,
"text": "Thus, every time the device restarts, the code in the Bootloader space gets executed first. Most of the time, it simply passes control to the code in the Application space. However, after downloading the newer firmware, when the device restarts, the bootloader will notice that a newer application code is available. So it will flash that newer code from the OTA space into the Application space and then give control to the code in the Application space. The result will be that the device firmware will be upgraded. "
},
{
"code": null,
"e": 4410,
"s": 3908,
"text": "Now, digressing a bit, the bootloader can also flash the factory reset code from the 'Factory Reset space' to the Application space, if the Application code is corrupted, or a factory reset command is sent. Also, often, the OTA code and the factory reset codes are stored on external storage devices like an SD Card or an external EEPROM or FLASH chip, if the microcontroller doesn't have enough space. However, in the case of ESP32, the OTA code can be stored in the microcontroller's memory itself. "
},
{
"code": null,
"e": 4561,
"s": 4410,
"text": "We will be using an example code for this chapter. You can find it in File −> Examples −> Update −> AWS_S3_OTA_Update. It can also be found on GitHub."
},
{
"code": null,
"e": 5044,
"s": 4561,
"text": "This is one of the very detailed examples available for ESP32 on Arduino. The author of this sketch has even provided the expected Serial Monitor output of the sketch in comments. So while much of the code will be self−explanatory through the comments, we'll walk over the broad idea and also cover the important details. This code makes use of the Update library which, like many other libraries, makes working with ESP32 very easy, while keeping the rigorous work under−the−hood. "
},
{
"code": null,
"e": 5820,
"s": 5044,
"text": "In this specific example, the author has kept the binary file of the new firmware in an AWS S3 bucket. Providing a detailed overview of AWS S3 is beyond the scope of this chapter, but very broadly, S3 (Simple Storage Service) is a cloud storage service provided by Amazon Web Services (AWS). Think of it like Google Drive. You upload files to your drive and share a link with people to share it. Similarly, you can upload a file to S3 and access it via a link. S3 is much more popular because a lot of other AWS services can interface seamlessly with it. Getting started with AWS S3 will be easy. You can get help from several resources available through a quick Google search. In the comments at the beginning of the sketch as well, a few steps to get started are mentioned."
},
{
"code": null,
"e": 6435,
"s": 5820,
"text": "An important recommendation to note is that you should use your own binary file for this code. The comments at the top of the sketch suggest that you can use the same binary file that the author has used. However, downloading a binary compiled on another machine/ another version of Arduino IDE has been known to cause errors sometimes in the OTA process. Also, using your own binary will make your learning more 'complete'. You can export the binary of any ESP32 sketch by going to Sketch −> Export Compiled Binary. The binary (.bin) file gets saved in the same folder in which your Arduino (.ino) file is saved. "
},
{
"code": null,
"e": 6810,
"s": 6435,
"text": "Once your binary is saved, you just need to upload it to S3 and add the link to the bucket and address of the binary file in your code. The binary you save should have some print statement to indicate that it is different from the code you flash in the ESP32. A statement like \"Hello from S3\" maybe. Also, don't keep the S3 bucket link and bin address in the code as it is. "
},
{
"code": null,
"e": 6924,
"s": 6810,
"text": "Alright! Enough talk! Let's begin the walkthrough now. We will begin by including the WiFi and Update libraries. "
},
{
"code": null,
"e": 6962,
"s": 6924,
"text": "#include <WiFi.h>\n#include <Update.h>"
},
{
"code": null,
"e": 7100,
"s": 6962,
"text": "Next, we define a few variables, constants, and also the WiFiClient object. Remember to add your own WiFi credentials and S3 credentials."
},
{
"code": null,
"e": 7630,
"s": 7100,
"text": "WiFiClient client;\n\n// Variables to validate\n// response from S3\nlong contentLength = 0;\nbool isValidContentType = false;\n\n// Your SSID and PSWD that the chip needs\n// to connect to\nconst char* SSID = \"YOUR−SSID\";\nconst char* PSWD = \"YOUR−SSID−PSWD\";\n\n// S3 Bucket Config\nString host = \"bucket−name.s3.ap−south−1.amazonaws.com\"; // Host => bucket−name.s3.region.amazonaws.com\nint port = 80; // Non https. For HTTPS 443. As of today, HTTPS doesn't work.\nString bin = \"/sketch−name.ino.bin\"; // bin file name with a slash in front."
},
{
"code": null,
"e": 7915,
"s": 7630,
"text": "Next, a helper function getHeaderValue() has been defined, which basically is used to check the value of a particular header. For example, if we get the header \"Content-Length: 40\" and it is stored in a String called headers, getHeaderValue(headers,\"Content−Length: \") will return 40."
},
{
"code": null,
"e": 8079,
"s": 7915,
"text": "// Utility to extract header value from headers\nString getHeaderValue(String header, String headerName) {\n return header.substring(strlen(headerName.c_str()));\n}"
},
{
"code": null,
"e": 8284,
"s": 8079,
"text": "Next, the main function execOTA(), which performs the OTA. This function has the entire logic related to the OTA. If you look at the Setup, we simply connect to the WiFi and call the \nexecOTA() function. "
},
{
"code": null,
"e": 8782,
"s": 8284,
"text": "void setup() {\n //Begin Serial\n Serial.begin(115200);\n delay(10);\n\n Serial.println(\"Connecting to \" + String(SSID));\n\n // Connect to provided SSID and PSWD\n WiFi.begin(SSID, PSWD);\n\n // Wait for connection to establish\n while (WiFi.status() != WL_CONNECTED) {\n Serial.print(\".\"); // Keep the serial monitor lit!\n delay(500);\n }\n\n // Connection Succeed\n Serial.println(\"\");\n Serial.println(\"Connected to \" + String(SSID));\n\n // Execute OTA Update\n execOTA();\n}"
},
{
"code": null,
"e": 8947,
"s": 8782,
"text": "So you would have understood that understanding the execOTA function means understanding this entire code. Therefore, let's begin the walkthrough of that function. "
},
{
"code": null,
"e": 9161,
"s": 8947,
"text": "We begin by connecting to our host, which is the S3 bucket in this case. Once connected, we fetch the bin file from the bucket, using a GET request (refer to the HTTP tutorial for more\ninformation on GET requests)"
},
{
"code": null,
"e": 9600,
"s": 9161,
"text": "void execOTA() {\n Serial.println(\"Connecting to: \" + String(host));\n // Connect to S3\n if (client.connect(host.c_str(), port)) {\n // Connection Succeed.\n // Fecthing the bin\n Serial.println(\"Fetching Bin: \" + String(bin));\n\n // Get the contents of the bin file\n client.print(String(\"GET \") + bin + \" HTTP/1.1\\r\\n\" +\n \"Host: \" + host + \"\\r\\n\" +\n \"Cache-Control: no-cache\\r\\n\" +\n \"Connection: close\\r\\n\\r\\n\");"
},
{
"code": null,
"e": 9780,
"s": 9600,
"text": "Next, we wait for the client to get connected. We give a maximum of 5 seconds for the connection to get established, otherwise we say that the connection has timed out and return."
},
{
"code": null,
"e": 9968,
"s": 9780,
"text": "unsigned long timeout = millis();\nwhile (client.available() == 0) {\n if (millis() - timeout > 5000) {\n Serial.println(\"Client Timeout !\");\n client.stop();\n return;\n }\n}"
},
{
"code": null,
"e": 10318,
"s": 9968,
"text": "Assuming that the code has not returned in the previous step, we have a successful connection established. The expected response from the server is provided in the comments. We begin by parsing that response. The response is read line by line, and each new line is stored in a variable called line. We specifically check for the following 3 things −"
},
{
"code": null,
"e": 10358,
"s": 10318,
"text": "If the response status code is 200 (OK)"
},
{
"code": null,
"e": 10398,
"s": 10358,
"text": "If the response status code is 200 (OK)"
},
{
"code": null,
"e": 10425,
"s": 10398,
"text": "What is the Content-Length"
},
{
"code": null,
"e": 10452,
"s": 10425,
"text": "What is the Content-Length"
},
{
"code": null,
"e": 10551,
"s": 10452,
"text": "Whether the content type is application/octet-stream (this is the type expected for a binary file)"
},
{
"code": null,
"e": 10650,
"s": 10551,
"text": "Whether the content type is application/octet-stream (this is the type expected for a binary file)"
},
{
"code": null,
"e": 10724,
"s": 10650,
"text": "The first and third are required, and the second is just for information."
},
{
"code": null,
"e": 11980,
"s": 10724,
"text": "while (client.available()) {\n // read line till /n\n String line = client.readStringUntil('\\n');\n // remove space, to check if the line is end of headers\n line.trim();\n\n // if the the line is empty,\n // this is end of headers\n // break the while and feed the\n // remaining `client` to the\n // Update.writeStream();\n if (!line.length()) {\n //headers ended\n break; // and get the OTA started\n }\n\n // Check if the HTTP Response is 200\n // else break and Exit Update\n if (line.startsWith(\"HTTP/1.1\")) {\n if (line.indexOf(\"200\") < 0) {\n Serial.println(\"Got a non 200 status code from server. Exiting OTA Update.\");\n break;\n }\n }\n\n // extract headers here\n // Start with content length\n if (line.startsWith(\"Content-Length: \")) {\n contentLength = atol((getHeaderValue(line, \"Content-Length: \")).c_str());\n Serial.println(\"Got \" + String(contentLength) + \" bytes from server\");\n }\n\n // Next, the content type\n if (line.startsWith(\"Content-Type: \")) {\n String contentType = getHeaderValue(line, \"Content-Type: \");\n Serial.println(\"Got \" + contentType + \" payload.\");\n if (contentType == \"application/octet-stream\") {\n isValidContentType = true;\n }\n }\n}"
},
{
"code": null,
"e": 12182,
"s": 11980,
"text": "With this, the if block that checks if the connection with the server was successful ends. It is followed by the else block, which just prints that we were unable to establish connection to the server."
},
{
"code": null,
"e": 12391,
"s": 12182,
"text": "} else {\n // Connect to S3 failed\n // May be try?\n // Probably a choppy network?\n Serial.println(\"Connection to \" + String(host) + \" failed. Please check your setup\");\n // retry??\n // execOTA();\n}"
},
{
"code": null,
"e": 13453,
"s": 12391,
"text": "Next, if we have hopefully received the correct response from the server, we will have a positive contentLength (remember, we had initialized it with 0 at the top and so it will still be 0 if we somehow did not reach that line where we parse the Content−Length header). Also, we will have isValidContentType as true (remember, we had initialized it with false). So we check if both of these\nconditions are true and if yes, proceed with the actual OTA. Note that so far, we have only made use of the WiFi library, for interacting with the server. Now if the server interaction turns out to be alright, we will begin use of the Update library, otherwise, we simply print that there was no content in the server response and flush the client. If the response was indeed correct, we first check if there is enough space in the memory to store the OTA file. By default, about 1.2 MB of space is reserved for the OTA file. So if the contentLength exceeds that, Update.begin() will return false. This 1.2MB number can change depending on the partitions of your ESP32. "
},
{
"code": null,
"e": 13629,
"s": 13453,
"text": "// check contentLength and content type\nif (contentLength && isValidContentType) {\n // Check if there is enough to OTA Update\n bool canBegin = Update.begin(contentLength);"
},
{
"code": null,
"e": 14527,
"s": 13629,
"text": "Now, if we indeed have space to store the OTA file in memory, we begin writing the bytes to the memory area reserved for OTA (the OTA space), using the Update.writeStream() function. If we don't,\nwe simply print that message and flush the client, and exit the OTA process. \nThe Update.writeStream() function returns the number of bytes that were written to the OTA space. We then check if the number of bytes written is equal to the contentLength. If the Update is completed, in which case\nthe Update.end() function will return true, we check if it has finished properly, i.e. all bytes are written, using the Update.isFinished() function. If it returns true, meaning that all bytes have been written, we restart the ESP32, so that the bootloader can flash the new code from the OTA space to the Application space, and our firmware gets upgraded. If it returns false, we print the error received. "
},
{
"code": null,
"e": 15750,
"s": 14527,
"text": " // If yes, begin\n if (canBegin) {\n Serial.println(\"Begin OTA. This may take 2 − 5 mins to complete. Things might be quite for a while.. Patience!\");\n // No activity would appear on the Serial monitor\n // So be patient. This may take 2 - 5mins to complete\n size_t written = Update.writeStream(client);\n\n if (written == contentLength) {\n Serial.println(\"Written : \" + String(written) + \" successfully\");\n } else {\n Serial.println(\"Written only : \" + String(written) + \"/\" + String(contentLength) + \". Retry?\" );\n // retry??\n // execOTA();\n }\n\n if (Update.end()) {\n Serial.println(\"OTA done!\");\n if (Update.isFinished()) {\n Serial.println(\"Update successfully completed. Rebooting.\");\n ESP.restart();\n } else {\n Serial.println(\"Update not finished? Something went wrong!\");\n }\n } else {\n Serial.println(\"Error Occurred. Error #: \" + String(Update.getError()));\n }\n } else {\n // not enough space to begin OTA\n // Understand the partitions and\n // space availability\n Serial.println(\"Not enough space to begin OTA\");\n client.flush();\n }\n}"
},
{
"code": null,
"e": 15840,
"s": 15750,
"text": "Of course, you would have realized by now that we need not do anything in the loop here. "
},
{
"code": null,
"e": 16052,
"s": 15840,
"text": "That's it. You've successfully upgraded the firmware of your ESP32 chip remotely. If you are more curious about what each function of the Update library does, you can refer to the comments\nin the Update.h file. "
},
{
"code": null,
"e": 16065,
"s": 16052,
"text": "OTA on ESP32"
},
{
"code": null,
"e": 16078,
"s": 16065,
"text": "OTA on ESP32"
},
{
"code": null,
"e": 16113,
"s": 16078,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 16130,
"s": 16113,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 16163,
"s": 16130,
"text": "\n 20 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 16175,
"s": 16163,
"text": " Azaz Patel"
},
{
"code": null,
"e": 16208,
"s": 16175,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 16220,
"s": 16208,
"text": " Azaz Patel"
},
{
"code": null,
"e": 16250,
"s": 16220,
"text": "\n 0 Lectures \n 0 mins\n"
},
{
"code": null,
"e": 16278,
"s": 16250,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 16315,
"s": 16278,
"text": "\n 169 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 16330,
"s": 16315,
"text": " Kalob Taulien"
},
{
"code": null,
"e": 16363,
"s": 16330,
"text": "\n 29 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 16370,
"s": 16363,
"text": " Zenva"
},
{
"code": null,
"e": 16377,
"s": 16370,
"text": " Print"
},
{
"code": null,
"e": 16388,
"s": 16377,
"text": " Add Notes"
}
] |
Python, Performance, and GPUs. A status update for using GPU... | by Matthew Rocklin | Towards Data Science | This blogpost was delivered in talk form at the recent PASC 2019 conference. Slides for that talk are here.
We’re improving the state of scalable GPU computing in Python.
This post lays out the current status, and describes future work. It also summarizes and links to several other more blogposts from recent months that drill down into different topics for the interested reader.
Broadly we cover briefly the following categories:
Python libraries written in CUDA like CuPy and RAPIDS
Python-CUDA compilers, specifically Numba
Scaling these libraries out with Dask
Network communication with UCX
Packaging with Conda
Probably the easiest way for a Python programmer to get access to GPU performance is to use a GPU-accelerated Python library. These provide a set of common operations that are well tuned and integrate well together.
Many users know libraries for deep learning like PyTorch and TensorFlow, but there are several other for more general purpose computing. These tend to copy the APIs of popular Python projects:
Numpy on the GPU: CuPy
Numpy on the GPU (again): Jax
Pandas on the GPU: RAPIDS cuDF
Scikit-Learn on the GPU: RAPIDS cuML
These libraries build GPU accelerated variants of popular Python libraries like NumPy, Pandas, and Scikit-Learn. In order to better understand the relative performance differences Peter Entschev recently put together a benchmark suite to help with comparisons. He has produced the following image showing the relative speedup between GPU and CPU:
There are lots of interesting results there. Peter goes into more depth in this in his blogpost.
More broadly though, we see that there is variability in performance. Our mental model for what is fast and slow on the CPU doesn’t neccessarily carry over to the GPU. Fortunately though, due consistent APIs, users that are familiar with Python can easily experiment with GPU acceleration without learning CUDA.
See also this recent blogpost about Numba stencils and the attached GPU notebook
The built-in operations in GPU libraries like CuPy and RAPIDS cover most common operations. However, in real-world settings we often find messy situations that require writing a little bit of custom code. Switching down to C/C++/CUDA in these cases can be challenging, especially for users that are primarily Python developers. This is where Numba can come in.
Python has this same problem on the CPU as well. Users often couldn’t be bothered to learn C/C++ to write fast custom code. To address this there are tools like Cython or Numba, which let Python programmers write fast numeric code without learning much beyond the Python language.
For example, Numba accelerates the for-loop style code below about 500x on the CPU, from slow Python speeds up to fast C/Fortran speeds.
import numba # We added these two lines for a 500x [email protected] # We added these two lines for a 500x speedupdef sum(x): total = 0 for i in range(x.shape[0]): total += x[i] return total
The ability to drop down to low-level performant code without context switching out of Python is useful, particularly if you don’t already know C/C++ or have a compiler chain set up for you (which is the case for most Python users today).
This benefit is even more pronounced on the GPU. While many Python programmers know a little bit of C, very few of them know CUDA. Even if they did, they would probably have difficulty in setting up the compiler tools and development environment.
Enter numba.cuda.jit Numba’s backend for CUDA. Numba.cuda.jit allows Python users to author, compile, and run CUDA code, written in Python, interactively without leaving a Python session. Here is an image of writing a stencil computation that smoothes a 2d-image all from within a Jupyter Notebook:
Here is a simplified comparison of Numba CPU/GPU code to compare programming style. The GPU code gets a 200x speed improvement over a single CPU core.
@numba.jitdef _smooth(x): out = np.empty_like(x) for i in range(1, x.shape[0] - 1): for j in range(1, x.shape[1] - 1): out[i,j] = (x[i-1, j-1] + x[i-1, j+0] + x[i-1, j+1] + x[i+0, j-1] + x[i+0, j+0] + x[i+0, j+1] + x[i+1, j-1] + x[i+1, j+0] + x[i+1, j+1])//9 return out
or if we use the fancy numba.stencil decorator ...
@numba.stencildef _smooth(x): return (x[-1, -1] + x[-1, 0] + x[-1, 1] + x[ 0, -1] + x[ 0, 0] + x[ 0, 1] + x[ 1, -1] + x[ 1, 0] + x[ 1, 1]) // 9
@numba.cuda.jitdef smooth_gpu(x, out): i, j = cuda.grid(2) n, m = x.shape if 1 <= i < n - 1 and 1 <= j < m - 1: out[i, j] = (x[i-1, j-1] + x[i-1, j] + x[i-1, j+1] + x[i , j-1] + x[i , j] + x[i , j+1] + x[i+1, j-1] + x[i+1, j] + x[i+1, j+1]) // 9
Numba.cuda.jit has been out in the wild for quite a while now. It’s accessible, mature, and fun to play with. If you have a machine with a GPU in it and some curiosity then we strongly recommend that you try it out.
conda install numba# orpip install numba>>> import numba.cuda
As mentioned in previous blogposts ( 1, 2, 3, 4 ) we’ve been generalizing Dask, to operate not just with Numpy arrays and Pandas dataframes, but with anything that looks enough like Numpy (like CuPy or Sparse or Jax) or enough like Pandas (like RAPIDS cuDF) to scale those libraries out too. This is working out well. Here is a brief video showing Dask array computing an SVD in parallel, and seeing what happens when we swap out the Numpy library for CuPy.
We see that there is about a 10x speed improvement on the computation. Most importantly, we were able to switch between a CPU implementation and a GPU implementation with a small one-line change, but continue using the sophisticated algorithms with Dask Array, like it’s parallel SVD implementation.
We also saw a relative slowdown in communication. In general almost all non-trivial Dask + GPU work today is becoming communication-bound. We’ve gotten fast enough at computation that the relative importance of communication has grown significantly.
See this talk by Akshay Venkatesh or view the slides
Also see this recent blogpost about UCX and Dask
We’ve been integrating the OpenUCX library into Python with UCX-Py. UCX provides uniform access to transports like TCP, InfiniBand, shared memory, and NVLink. UCX-Py is the first time that access to many of these transports has been easily accessible from the Python language.
Using UCX and Dask together we’re able to get significant speedups. Here is a trace of the SVD computation from before both before and after adding UCX:
Before UCX:
After UCX:
There is still a great deal to do here though (the blogpost linked above has several items in the Future Work section).
People can try out UCX and UCX-Py with highly experimental conda packages:
conda create -n ucx -c conda-forge -c jakirkham/label/ucx cudatoolkit=9.2 ucx-proc=*=gpu ucx ucx-py python=3.7
We hope that this work will also affect non-GPU users on HPC systems with Infiniband, or even users on consumer hardware due to the easy access to shared memory communication.
In an earlier blogpost we discussed the challenges around installing the wrong versions of CUDA enabled packages that don’t match the CUDA driver installed on the system. Fortunately due to recent work from Stan Seibert and Michael Sarahan at Anaconda, Conda 4.7 now has a special cuda meta-package that is set to the version of the installed driver. This should make it much easier for users in the future to install the correct package.
Conda 4.7 was just releasead, and comes with many new features other than the cuda meta-package. You can read more about it here.
conda update conda
There is still plenty of work to do in the packaging space today. Everyone who builds conda packages does it their own way, resulting in headache and heterogeneity. This is largely due to not having centralized infrastructure to build and test CUDA enabled packages, like we have in Conda Forge. Fortunately, the Conda Forge community is working together with Anaconda and NVIDIA to help resolve this, though that will likely take some time.
This post gave an update of the status of some of the efforts behind GPU computing in Python. It also provided a variety of links for future reading. We include them below if you would like to learn more:
Slides
Numpy on the GPU: CuPy
Numpy on the GPU (again): Jax
Pandas on the GPU: RAPIDS cuDF
Scikit-Learn on the GPU: RAPIDS cuML
Benchmark suite
Numba CUDA JIT notebook
A talk on UCX
A blogpost on UCX and Dask | [
{
"code": null,
"e": 280,
"s": 172,
"text": "This blogpost was delivered in talk form at the recent PASC 2019 conference. Slides for that talk are here."
},
{
"code": null,
"e": 343,
"s": 280,
"text": "We’re improving the state of scalable GPU computing in Python."
},
{
"code": null,
"e": 554,
"s": 343,
"text": "This post lays out the current status, and describes future work. It also summarizes and links to several other more blogposts from recent months that drill down into different topics for the interested reader."
},
{
"code": null,
"e": 605,
"s": 554,
"text": "Broadly we cover briefly the following categories:"
},
{
"code": null,
"e": 659,
"s": 605,
"text": "Python libraries written in CUDA like CuPy and RAPIDS"
},
{
"code": null,
"e": 701,
"s": 659,
"text": "Python-CUDA compilers, specifically Numba"
},
{
"code": null,
"e": 739,
"s": 701,
"text": "Scaling these libraries out with Dask"
},
{
"code": null,
"e": 770,
"s": 739,
"text": "Network communication with UCX"
},
{
"code": null,
"e": 791,
"s": 770,
"text": "Packaging with Conda"
},
{
"code": null,
"e": 1007,
"s": 791,
"text": "Probably the easiest way for a Python programmer to get access to GPU performance is to use a GPU-accelerated Python library. These provide a set of common operations that are well tuned and integrate well together."
},
{
"code": null,
"e": 1200,
"s": 1007,
"text": "Many users know libraries for deep learning like PyTorch and TensorFlow, but there are several other for more general purpose computing. These tend to copy the APIs of popular Python projects:"
},
{
"code": null,
"e": 1223,
"s": 1200,
"text": "Numpy on the GPU: CuPy"
},
{
"code": null,
"e": 1253,
"s": 1223,
"text": "Numpy on the GPU (again): Jax"
},
{
"code": null,
"e": 1284,
"s": 1253,
"text": "Pandas on the GPU: RAPIDS cuDF"
},
{
"code": null,
"e": 1321,
"s": 1284,
"text": "Scikit-Learn on the GPU: RAPIDS cuML"
},
{
"code": null,
"e": 1668,
"s": 1321,
"text": "These libraries build GPU accelerated variants of popular Python libraries like NumPy, Pandas, and Scikit-Learn. In order to better understand the relative performance differences Peter Entschev recently put together a benchmark suite to help with comparisons. He has produced the following image showing the relative speedup between GPU and CPU:"
},
{
"code": null,
"e": 1765,
"s": 1668,
"text": "There are lots of interesting results there. Peter goes into more depth in this in his blogpost."
},
{
"code": null,
"e": 2077,
"s": 1765,
"text": "More broadly though, we see that there is variability in performance. Our mental model for what is fast and slow on the CPU doesn’t neccessarily carry over to the GPU. Fortunately though, due consistent APIs, users that are familiar with Python can easily experiment with GPU acceleration without learning CUDA."
},
{
"code": null,
"e": 2158,
"s": 2077,
"text": "See also this recent blogpost about Numba stencils and the attached GPU notebook"
},
{
"code": null,
"e": 2519,
"s": 2158,
"text": "The built-in operations in GPU libraries like CuPy and RAPIDS cover most common operations. However, in real-world settings we often find messy situations that require writing a little bit of custom code. Switching down to C/C++/CUDA in these cases can be challenging, especially for users that are primarily Python developers. This is where Numba can come in."
},
{
"code": null,
"e": 2800,
"s": 2519,
"text": "Python has this same problem on the CPU as well. Users often couldn’t be bothered to learn C/C++ to write fast custom code. To address this there are tools like Cython or Numba, which let Python programmers write fast numeric code without learning much beyond the Python language."
},
{
"code": null,
"e": 2937,
"s": 2800,
"text": "For example, Numba accelerates the for-loop style code below about 500x on the CPU, from slow Python speeds up to fast C/Fortran speeds."
},
{
"code": null,
"e": 3148,
"s": 2937,
"text": "import numba # We added these two lines for a 500x [email protected] # We added these two lines for a 500x speedupdef sum(x): total = 0 for i in range(x.shape[0]): total += x[i] return total"
},
{
"code": null,
"e": 3387,
"s": 3148,
"text": "The ability to drop down to low-level performant code without context switching out of Python is useful, particularly if you don’t already know C/C++ or have a compiler chain set up for you (which is the case for most Python users today)."
},
{
"code": null,
"e": 3634,
"s": 3387,
"text": "This benefit is even more pronounced on the GPU. While many Python programmers know a little bit of C, very few of them know CUDA. Even if they did, they would probably have difficulty in setting up the compiler tools and development environment."
},
{
"code": null,
"e": 3933,
"s": 3634,
"text": "Enter numba.cuda.jit Numba’s backend for CUDA. Numba.cuda.jit allows Python users to author, compile, and run CUDA code, written in Python, interactively without leaving a Python session. Here is an image of writing a stencil computation that smoothes a 2d-image all from within a Jupyter Notebook:"
},
{
"code": null,
"e": 4084,
"s": 3933,
"text": "Here is a simplified comparison of Numba CPU/GPU code to compare programming style. The GPU code gets a 200x speed improvement over a single CPU core."
},
{
"code": null,
"e": 4427,
"s": 4084,
"text": "@numba.jitdef _smooth(x): out = np.empty_like(x) for i in range(1, x.shape[0] - 1): for j in range(1, x.shape[1] - 1): out[i,j] = (x[i-1, j-1] + x[i-1, j+0] + x[i-1, j+1] + x[i+0, j-1] + x[i+0, j+0] + x[i+0, j+1] + x[i+1, j-1] + x[i+1, j+0] + x[i+1, j+1])//9 return out"
},
{
"code": null,
"e": 4478,
"s": 4427,
"text": "or if we use the fancy numba.stencil decorator ..."
},
{
"code": null,
"e": 4647,
"s": 4478,
"text": "@numba.stencildef _smooth(x): return (x[-1, -1] + x[-1, 0] + x[-1, 1] + x[ 0, -1] + x[ 0, 0] + x[ 0, 1] + x[ 1, -1] + x[ 1, 0] + x[ 1, 1]) // 9"
},
{
"code": null,
"e": 4952,
"s": 4647,
"text": "@numba.cuda.jitdef smooth_gpu(x, out): i, j = cuda.grid(2) n, m = x.shape if 1 <= i < n - 1 and 1 <= j < m - 1: out[i, j] = (x[i-1, j-1] + x[i-1, j] + x[i-1, j+1] + x[i , j-1] + x[i , j] + x[i , j+1] + x[i+1, j-1] + x[i+1, j] + x[i+1, j+1]) // 9"
},
{
"code": null,
"e": 5168,
"s": 4952,
"text": "Numba.cuda.jit has been out in the wild for quite a while now. It’s accessible, mature, and fun to play with. If you have a machine with a GPU in it and some curiosity then we strongly recommend that you try it out."
},
{
"code": null,
"e": 5230,
"s": 5168,
"text": "conda install numba# orpip install numba>>> import numba.cuda"
},
{
"code": null,
"e": 5688,
"s": 5230,
"text": "As mentioned in previous blogposts ( 1, 2, 3, 4 ) we’ve been generalizing Dask, to operate not just with Numpy arrays and Pandas dataframes, but with anything that looks enough like Numpy (like CuPy or Sparse or Jax) or enough like Pandas (like RAPIDS cuDF) to scale those libraries out too. This is working out well. Here is a brief video showing Dask array computing an SVD in parallel, and seeing what happens when we swap out the Numpy library for CuPy."
},
{
"code": null,
"e": 5988,
"s": 5688,
"text": "We see that there is about a 10x speed improvement on the computation. Most importantly, we were able to switch between a CPU implementation and a GPU implementation with a small one-line change, but continue using the sophisticated algorithms with Dask Array, like it’s parallel SVD implementation."
},
{
"code": null,
"e": 6238,
"s": 5988,
"text": "We also saw a relative slowdown in communication. In general almost all non-trivial Dask + GPU work today is becoming communication-bound. We’ve gotten fast enough at computation that the relative importance of communication has grown significantly."
},
{
"code": null,
"e": 6291,
"s": 6238,
"text": "See this talk by Akshay Venkatesh or view the slides"
},
{
"code": null,
"e": 6340,
"s": 6291,
"text": "Also see this recent blogpost about UCX and Dask"
},
{
"code": null,
"e": 6617,
"s": 6340,
"text": "We’ve been integrating the OpenUCX library into Python with UCX-Py. UCX provides uniform access to transports like TCP, InfiniBand, shared memory, and NVLink. UCX-Py is the first time that access to many of these transports has been easily accessible from the Python language."
},
{
"code": null,
"e": 6770,
"s": 6617,
"text": "Using UCX and Dask together we’re able to get significant speedups. Here is a trace of the SVD computation from before both before and after adding UCX:"
},
{
"code": null,
"e": 6782,
"s": 6770,
"text": "Before UCX:"
},
{
"code": null,
"e": 6793,
"s": 6782,
"text": "After UCX:"
},
{
"code": null,
"e": 6913,
"s": 6793,
"text": "There is still a great deal to do here though (the blogpost linked above has several items in the Future Work section)."
},
{
"code": null,
"e": 6988,
"s": 6913,
"text": "People can try out UCX and UCX-Py with highly experimental conda packages:"
},
{
"code": null,
"e": 7099,
"s": 6988,
"text": "conda create -n ucx -c conda-forge -c jakirkham/label/ucx cudatoolkit=9.2 ucx-proc=*=gpu ucx ucx-py python=3.7"
},
{
"code": null,
"e": 7275,
"s": 7099,
"text": "We hope that this work will also affect non-GPU users on HPC systems with Infiniband, or even users on consumer hardware due to the easy access to shared memory communication."
},
{
"code": null,
"e": 7714,
"s": 7275,
"text": "In an earlier blogpost we discussed the challenges around installing the wrong versions of CUDA enabled packages that don’t match the CUDA driver installed on the system. Fortunately due to recent work from Stan Seibert and Michael Sarahan at Anaconda, Conda 4.7 now has a special cuda meta-package that is set to the version of the installed driver. This should make it much easier for users in the future to install the correct package."
},
{
"code": null,
"e": 7844,
"s": 7714,
"text": "Conda 4.7 was just releasead, and comes with many new features other than the cuda meta-package. You can read more about it here."
},
{
"code": null,
"e": 7863,
"s": 7844,
"text": "conda update conda"
},
{
"code": null,
"e": 8305,
"s": 7863,
"text": "There is still plenty of work to do in the packaging space today. Everyone who builds conda packages does it their own way, resulting in headache and heterogeneity. This is largely due to not having centralized infrastructure to build and test CUDA enabled packages, like we have in Conda Forge. Fortunately, the Conda Forge community is working together with Anaconda and NVIDIA to help resolve this, though that will likely take some time."
},
{
"code": null,
"e": 8510,
"s": 8305,
"text": "This post gave an update of the status of some of the efforts behind GPU computing in Python. It also provided a variety of links for future reading. We include them below if you would like to learn more:"
},
{
"code": null,
"e": 8517,
"s": 8510,
"text": "Slides"
},
{
"code": null,
"e": 8540,
"s": 8517,
"text": "Numpy on the GPU: CuPy"
},
{
"code": null,
"e": 8570,
"s": 8540,
"text": "Numpy on the GPU (again): Jax"
},
{
"code": null,
"e": 8601,
"s": 8570,
"text": "Pandas on the GPU: RAPIDS cuDF"
},
{
"code": null,
"e": 8638,
"s": 8601,
"text": "Scikit-Learn on the GPU: RAPIDS cuML"
},
{
"code": null,
"e": 8654,
"s": 8638,
"text": "Benchmark suite"
},
{
"code": null,
"e": 8678,
"s": 8654,
"text": "Numba CUDA JIT notebook"
},
{
"code": null,
"e": 8692,
"s": 8678,
"text": "A talk on UCX"
}
] |
Insecure Direct Object References | A direct object reference is likely to occur when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key without any validation mechanism which allows attackers to manipulate these references to access unauthorized data.
Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram.
The App uses unverified data in a SQL call that is accessing account information.
String sqlquery = "SELECT * FROM useraccounts WHERE account = ?";
PreparedStatement st = connection.prepareStatement(sqlquery, ??);
st.setString( 1, request.getParameter("acct"));
ResultSet results = st.executeQuery( );
The attacker modifies the query parameter in their browser to point to Admin.
http://webapp.com/app/accountInfo?acct=admin
Step 1 − Login to Webgoat and navigate to access control flaws Section. The goal is to retrieve the tomcat-users.xml by navigating to the path where it is located. Below is the snapshot of the scenario.
Step 2 − The path of the file is displayed in 'the current directory is' field - C:\Users\userName$\.extract\webapps\WebGoat\lesson_plans\en and we also know that the tomcat-users.xml file is kept under C:\xampp\tomcat\conf
Step 3 − We need to traverse all the way out of the current directory and navigate from C:\ Drive. We can perform the same by intercepting the traffic using Burp Suite.
Step 4 − If the attempt is successful, it displays the tomcat-users.xml with the message "Congratulations. You have successfully completed this lesson."
Developers can use the following resources/points as a guide to prevent insecure direct object reference during development phase itself.
Developers should use only one user or session for indirect object references.
Developers should use only one user or session for indirect object references.
It is also recommended to check the access before using a direct object reference from an untrusted source.
It is also recommended to check the access before using a direct object reference from an untrusted source.
36 Lectures
5 hours
Sharad Kumar
26 Lectures
2.5 hours
Harshit Srivastava
47 Lectures
2 hours
Dhabaleshwar Das
14 Lectures
1.5 hours
Harshit Srivastava
38 Lectures
3 hours
Harshit Srivastava
32 Lectures
3 hours
Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2719,
"s": 2440,
"text": "A direct object reference is likely to occur when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key without any validation mechanism which allows attackers to manipulate these references to access unauthorized data."
},
{
"code": null,
"e": 2871,
"s": 2719,
"text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram."
},
{
"code": null,
"e": 2953,
"s": 2871,
"text": "The App uses unverified data in a SQL call that is accessing account information."
},
{
"code": null,
"e": 3173,
"s": 2953,
"text": "String sqlquery = \"SELECT * FROM useraccounts WHERE account = ?\";\nPreparedStatement st = connection.prepareStatement(sqlquery, ??);\nst.setString( 1, request.getParameter(\"acct\"));\nResultSet results = st.executeQuery( );"
},
{
"code": null,
"e": 3251,
"s": 3173,
"text": "The attacker modifies the query parameter in their browser to point to Admin."
},
{
"code": null,
"e": 3297,
"s": 3251,
"text": "http://webapp.com/app/accountInfo?acct=admin\n"
},
{
"code": null,
"e": 3500,
"s": 3297,
"text": "Step 1 − Login to Webgoat and navigate to access control flaws Section. The goal is to retrieve the tomcat-users.xml by navigating to the path where it is located. Below is the snapshot of the scenario."
},
{
"code": null,
"e": 3724,
"s": 3500,
"text": "Step 2 − The path of the file is displayed in 'the current directory is' field - C:\\Users\\userName$\\.extract\\webapps\\WebGoat\\lesson_plans\\en and we also know that the tomcat-users.xml file is kept under C:\\xampp\\tomcat\\conf"
},
{
"code": null,
"e": 3893,
"s": 3724,
"text": "Step 3 − We need to traverse all the way out of the current directory and navigate from C:\\ Drive. We can perform the same by intercepting the traffic using Burp Suite."
},
{
"code": null,
"e": 4046,
"s": 3893,
"text": "Step 4 − If the attempt is successful, it displays the tomcat-users.xml with the message \"Congratulations. You have successfully completed this lesson.\""
},
{
"code": null,
"e": 4184,
"s": 4046,
"text": "Developers can use the following resources/points as a guide to prevent insecure direct object reference during development phase itself."
},
{
"code": null,
"e": 4263,
"s": 4184,
"text": "Developers should use only one user or session for indirect object references."
},
{
"code": null,
"e": 4342,
"s": 4263,
"text": "Developers should use only one user or session for indirect object references."
},
{
"code": null,
"e": 4450,
"s": 4342,
"text": "It is also recommended to check the access before using a direct object reference from an untrusted source."
},
{
"code": null,
"e": 4558,
"s": 4450,
"text": "It is also recommended to check the access before using a direct object reference from an untrusted source."
},
{
"code": null,
"e": 4591,
"s": 4558,
"text": "\n 36 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4605,
"s": 4591,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 4640,
"s": 4605,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4660,
"s": 4640,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4693,
"s": 4660,
"text": "\n 47 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4711,
"s": 4693,
"text": " Dhabaleshwar Das"
},
{
"code": null,
"e": 4746,
"s": 4711,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4766,
"s": 4746,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4799,
"s": 4766,
"text": "\n 38 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4819,
"s": 4799,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4852,
"s": 4819,
"text": "\n 32 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4872,
"s": 4852,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4879,
"s": 4872,
"text": " Print"
},
{
"code": null,
"e": 4890,
"s": 4879,
"text": " Add Notes"
}
] |
Python | Pandas Index.to_series() - GeeksforGeeks | 24 Dec, 2018
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 Index.to_series() function create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index. It is possible to set a new index label for the newly created Series by passing the list of new index labels.
Syntax: Index.to_series(index=None, name=None)
Parameters :index : index of resulting Series. If None, defaults to original indexname : name of resulting Series. If None, defaults to name of original index
Returns : Series : dtype will be based on the type of the Index values.
Example #1: Use Index.to_series() function to convert the index into a Series.
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick'], name ='Student') # Print the Indexprint(idx)
Output :
Let’s convert the index into a Series.
# convert the index into a seriesidx.to_series()
Output :The function has converted the index into a series. By default, the function has created the index of the series using the values of the original Index. Example #2: Use Index.to_series() function to convert the index into a series such that the series created uses new index value.
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Alice', 'Bob', 'Rachel', 'Tyler', 'Louis'], name ='Winners') # Print the Indexprint(idx)
Output :
Let’s convert the index into a series.
# convert the index into a seriesidx.to_series(index =['Student 1', 'Student 2', 'Student 3', 'Student 4', 'Student 5'])
Output :The function has converted the index into a series. We have passed a list of index labels to be used for the newly created Series.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24019,
"s": 23991,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 24233,
"s": 24019,
"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": 24504,
"s": 24233,
"text": "Pandas Index.to_series() function create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index. It is possible to set a new index label for the newly created Series by passing the list of new index labels."
},
{
"code": null,
"e": 24551,
"s": 24504,
"text": "Syntax: Index.to_series(index=None, name=None)"
},
{
"code": null,
"e": 24710,
"s": 24551,
"text": "Parameters :index : index of resulting Series. If None, defaults to original indexname : name of resulting Series. If None, defaults to name of original index"
},
{
"code": null,
"e": 24782,
"s": 24710,
"text": "Returns : Series : dtype will be based on the type of the Index values."
},
{
"code": null,
"e": 24861,
"s": 24782,
"text": "Example #1: Use Index.to_series() function to convert the index into a Series."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick'], name ='Student') # Print the Indexprint(idx)",
"e": 25058,
"s": 24861,
"text": null
},
{
"code": null,
"e": 25067,
"s": 25058,
"text": "Output :"
},
{
"code": null,
"e": 25106,
"s": 25067,
"text": "Let’s convert the index into a Series."
},
{
"code": "# convert the index into a seriesidx.to_series()",
"e": 25155,
"s": 25106,
"text": null
},
{
"code": null,
"e": 25445,
"s": 25155,
"text": "Output :The function has converted the index into a series. By default, the function has created the index of the series using the values of the original Index. Example #2: Use Index.to_series() function to convert the index into a series such that the series created uses new index value."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Alice', 'Bob', 'Rachel', 'Tyler', 'Louis'], name ='Winners') # Print the Indexprint(idx)",
"e": 25660,
"s": 25445,
"text": null
},
{
"code": null,
"e": 25669,
"s": 25660,
"text": "Output :"
},
{
"code": null,
"e": 25708,
"s": 25669,
"text": "Let’s convert the index into a series."
},
{
"code": "# convert the index into a seriesidx.to_series(index =['Student 1', 'Student 2', 'Student 3', 'Student 4', 'Student 5'])",
"e": 25862,
"s": 25708,
"text": null
},
{
"code": null,
"e": 26001,
"s": 25862,
"text": "Output :The function has converted the index into a series. We have passed a list of index labels to be used for the newly created Series."
},
{
"code": null,
"e": 26024,
"s": 26001,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 26038,
"s": 26024,
"text": "Python-pandas"
},
{
"code": null,
"e": 26045,
"s": 26038,
"text": "Python"
},
{
"code": null,
"e": 26143,
"s": 26045,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26152,
"s": 26143,
"text": "Comments"
},
{
"code": null,
"e": 26165,
"s": 26152,
"text": "Old Comments"
},
{
"code": null,
"e": 26183,
"s": 26165,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26218,
"s": 26183,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26240,
"s": 26218,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26272,
"s": 26240,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26302,
"s": 26272,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26344,
"s": 26302,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26387,
"s": 26344,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26413,
"s": 26387,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26457,
"s": 26413,
"text": "Reading and Writing to text files in Python"
}
] |
Arduino - delayMicroseconds () function | The delayMicroseconds() function accepts a single integer (or number) argument. This number represents the time and is measured in microseconds. There are a thousand microseconds in a millisecond, and a million microseconds in a second.
Currently, the largest value that can produce an accurate delay is 16383. This may change in future Arduino releases. For delays longer than a few thousand microseconds, you should use the delay() function instead.
delayMicroseconds (us) ;
where, us is the number of microseconds to pause (unsigned int)
/* Flashing LED
* ------------
* Turns on and off a light emitting diode(LED) connected to a digital
* pin, in intervals of 1 seconds. *
*/
int ledPin = 13; // LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop() {
digitalWrite(ledPin, HIGH); // sets the LED on
delayMicroseconds(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delayMicroseconds(1000); // waits for a second
}
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": 3107,
"s": 2870,
"text": "The delayMicroseconds() function accepts a single integer (or number) argument. This number represents the time and is measured in microseconds. There are a thousand microseconds in a millisecond, and a million microseconds in a second."
},
{
"code": null,
"e": 3322,
"s": 3107,
"text": "Currently, the largest value that can produce an accurate delay is 16383. This may change in future Arduino releases. For delays longer than a few thousand microseconds, you should use the delay() function instead."
},
{
"code": null,
"e": 3348,
"s": 3322,
"text": "delayMicroseconds (us) ;\n"
},
{
"code": null,
"e": 3412,
"s": 3348,
"text": "where, us is the number of microseconds to pause (unsigned int)"
},
{
"code": null,
"e": 3911,
"s": 3412,
"text": "/* Flashing LED\n * ------------\n * Turns on and off a light emitting diode(LED) connected to a digital\n * pin, in intervals of 1 seconds. *\n*/\n\nint ledPin = 13; // LED connected to digital pin 13\n\nvoid setup() {\n pinMode(ledPin, OUTPUT); // sets the digital pin as output\n}\n\nvoid loop() {\n digitalWrite(ledPin, HIGH); // sets the LED on\n delayMicroseconds(1000); // waits for a second\n digitalWrite(ledPin, LOW); // sets the LED off\n delayMicroseconds(1000); // waits for a second\n}"
},
{
"code": null,
"e": 3946,
"s": 3911,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3957,
"s": 3946,
"text": " Amit Rana"
},
{
"code": null,
"e": 3990,
"s": 3957,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4001,
"s": 3990,
"text": " Amit Rana"
},
{
"code": null,
"e": 4034,
"s": 4001,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4047,
"s": 4034,
"text": " Ashraf Said"
},
{
"code": null,
"e": 4082,
"s": 4047,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4095,
"s": 4082,
"text": " Ashraf Said"
},
{
"code": null,
"e": 4127,
"s": 4095,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 4140,
"s": 4127,
"text": " Ashraf Said"
},
{
"code": null,
"e": 4171,
"s": 4140,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 4184,
"s": 4171,
"text": " Ashraf Said"
},
{
"code": null,
"e": 4191,
"s": 4184,
"text": " Print"
},
{
"code": null,
"e": 4202,
"s": 4191,
"text": " Add Notes"
}
] |
Python | Compare tuples | 21 Nov, 2019
Sometimes, while working with records, we can have a problem in which we need to check if each element of one tuple is greater/smaller than it’s corresponding index in other tuple. This can have many possible applications. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using all() + generator expression + zip()The combination of above functionalities can be used to perform this task. In this, we just compare all elements using all(). The cross tuple access is done by zip() and generator expression gives us the logic to compare.
# Python3 code to demonstrate working of# Comparing tuples# using generator expression + all() + zip() # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (13, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Comparing tuples# using generator expression + all() + zip()res = all(x < y for x, y in zip(test_tup1, test_tup2)) # printing resultprint("Are all elements in second tuple greater than first ? : " + str(res))
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (13, 5, 18)
Are all elements in second tuple greater than first ? : True
Method #2 : Using all() + map() + lambdaThe combination of above functionalities can be used to perform this particular task. In this, we perform extension of logic to each element using map() and logic generation by lambda function.
# Python3 code to demonstrate working of# Comparing tuples# using all() + lambda + map() # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (13, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Comparing tuples# using all() + lambda + map()res = all(map(lambda i, j: i < j, test_tup1, test_tup2)) # printing resultprint("Are all elements in second tuple greater than first ? : " + str(res))
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (13, 5, 18)
Are all elements in second tuple greater than first ? : True
Python tuple-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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 315,
"s": 28,
"text": "Sometimes, while working with records, we can have a problem in which we need to check if each element of one tuple is greater/smaller than it’s corresponding index in other tuple. This can have many possible applications. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 591,
"s": 315,
"text": "Method #1 : Using all() + generator expression + zip()The combination of above functionalities can be used to perform this task. In this, we just compare all elements using all(). The cross tuple access is done by zip() and generator expression gives us the logic to compare."
},
{
"code": "# Python3 code to demonstrate working of# Comparing tuples# using generator expression + all() + zip() # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (13, 5, 18) # printing original tuples print(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Comparing tuples# using generator expression + all() + zip()res = all(x < y for x, y in zip(test_tup1, test_tup2)) # printing resultprint(\"Are all elements in second tuple greater than first ? : \" + str(res))",
"e": 1101,
"s": 591,
"text": null
},
{
"code": null,
"e": 1232,
"s": 1101,
"text": "The original tuple 1 : (10, 4, 5)\nThe original tuple 2 : (13, 5, 18)\nAre all elements in second tuple greater than first ? : True\n"
},
{
"code": null,
"e": 1468,
"s": 1234,
"text": "Method #2 : Using all() + map() + lambdaThe combination of above functionalities can be used to perform this particular task. In this, we perform extension of logic to each element using map() and logic generation by lambda function."
},
{
"code": "# Python3 code to demonstrate working of# Comparing tuples# using all() + lambda + map() # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (13, 5, 18) # printing original tuples print(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Comparing tuples# using all() + lambda + map()res = all(map(lambda i, j: i < j, test_tup1, test_tup2)) # printing resultprint(\"Are all elements in second tuple greater than first ? : \" + str(res))",
"e": 1952,
"s": 1468,
"text": null
},
{
"code": null,
"e": 2083,
"s": 1952,
"text": "The original tuple 1 : (10, 4, 5)\nThe original tuple 2 : (13, 5, 18)\nAre all elements in second tuple greater than first ? : True\n"
},
{
"code": null,
"e": 2105,
"s": 2083,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 2112,
"s": 2105,
"text": "Python"
},
{
"code": null,
"e": 2128,
"s": 2112,
"text": "Python Programs"
},
{
"code": null,
"e": 2226,
"s": 2128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2258,
"s": 2226,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2285,
"s": 2258,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2306,
"s": 2285,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2329,
"s": 2306,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2360,
"s": 2329,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2382,
"s": 2360,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2421,
"s": 2382,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2459,
"s": 2421,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2496,
"s": 2459,
"text": "Python Program for Fibonacci numbers"
}
] |
Karger’s algorithm for Minimum Cut | Set 1 (Introduction and Implementation) | 27 Jun, 2022
Given an undirected and unweighted graph, find the smallest cut (smallest number of edges that disconnects the graph into two components). The input graph may have parallel edges.
For example consider the following example, the smallest cut has 2 edges.
A Simple Solution use Max-Flow based s-t cut algorithm to find minimum cut. Consider every pair of vertices as source ‘s’ and sink ‘t’, and call minimum s-t cut algorithm to find the s-t cut. Return minimum of all s-t cuts. Best possible time complexity of this algorithm is O(V5) for a graph. [How? there are total possible V2 pairs and s-t cut algorithm for one pair takes O(V*E) time and E = O(V2)].
Below is simple Karger’s Algorithm for this purpose. Below Karger’s algorithm can be implemented in O(E) = O(V2) time.
1) Initialize contracted graph CG as copy of original graph
2) While there are more than 2 vertices.
a) Pick a random edge (u, v) in the contracted graph.
b) Merge (or contract) u and v into a single vertex (update
the contracted graph).
c) Remove self-loops
3) Return cut represented by two vertices.
Let us understand above algorithm through the example given.Let the first randomly picked vertex be ‘a‘ which connects vertices 0 and 1. We remove this edge and contract the graph (combine vertices 0 and 1). We get the following graph.
Let the next randomly picked edge be ‘d’. We remove this edge and combine vertices (0,1) and 3.
We need to remove self-loops in the graph. So we remove edge ‘c’
Now graph has two vertices, so we stop. The number of edges in the resultant graph is the cut produced by Karger’s algorithm.Karger’s algorithm is a Monte Carlo algorithm and cut produced by it may not be minimum. For example, the following diagram shows that a different order of picking random edges produces a min-cut of size 3.
Below is C++ implementation of above algorithm. The input graph is represented as a collection of edges and union-find data structure is used to keep track of components.
C++
Java
// Karger's algorithm to find Minimum Cut in an// undirected, unweighted and connected graph.#include <iostream>//#include <stdlib.h>#include <time.h> // a structure to represent a unweighted edge in graphstruct Edge{ int src, dest;}; // a structure to represent a connected, undirected// and unweighted graph as a collection of edges.struct Graph{ // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. // Since the graph is undirected, the edge // from src to dest is also edge from dest // to src. Both are counted as 1 edge here. Edge* edge;}; // A structure to represent a subset for union-findstruct subset{ int parent; int rank;}; // Function prototypes for union-find (These functions are defined// after kargerMinCut() )int find(struct subset subsets[], int i);void Union(struct subset subsets[], int x, int y); // A very basic implementation of Karger's randomized// algorithm for finding the minimum cut. Please note// that Karger's algorithm is a Monte Carlo Randomized algo// and the cut returned by the algorithm may not be// minimum alwaysint kargerMinCut(struct Graph* graph){ // Get data of given graph int V = graph->V, E = graph->E; Edge *edge = graph->edge; // Allocate memory for creating V subsets. struct subset *subsets = new subset[V]; // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } // Initially there are V vertices in // contracted graph int vertices = V; // Keep contracting vertices until there are // 2 vertices. while (vertices > 2) { // Pick a random edge int i = rand() % E; // Find vertices (or sets) of two corners // of current edge int subset1 = find(subsets, edge[i].src); int subset2 = find(subsets, edge[i].dest); // If two corners belong to same subset, // then no point considering this edge if (subset1 == subset2) continue; // Else contract the edge (or combine the // corners of edge into one vertex) else { printf("Contracting edge %d-%d\n", edge[i].src, edge[i].dest); vertices--; Union(subsets, subset1, subset2); } } // Now we have two vertices (or subsets) left in // the contracted graph, so count the edges between // two components and return the count. int cutedges = 0; for (int i=0; i<E; i++) { int subset1 = find(subsets, edge[i].src); int subset2 = find(subsets, edge[i].dest); if (subset1 != subset2) cutedges++; } return cutedges;} // A utility function to find set of an element i// (uses path compression technique)int find(struct subset subsets[], int i){ // find root and make root as parent of i // (path compression) if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent;} // A function that does union of two sets of x and y// (uses union by rank)void Union(struct subset subsets[], int x, int y){ int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root of high // rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and // increment its rank by one else { subsets[yroot].parent = xroot; subsets[xroot].rank++; }} // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){ Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[E]; return graph;} // Driver program to test above functionsint main(){ /* Let us create following unweighted graph 0------1 | \ | | \ | | \| 2------3 */ int V = 4; // Number of vertices in graph int E = 5; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 graph->edge[0].src = 0; graph->edge[0].dest = 1; // add edge 0-2 graph->edge[1].src = 0; graph->edge[1].dest = 2; // add edge 0-3 graph->edge[2].src = 0; graph->edge[2].dest = 3; // add edge 1-3 graph->edge[3].src = 1; graph->edge[3].dest = 3; // add edge 2-3 graph->edge[4].src = 2; graph->edge[4].dest = 3; // Use a different seed value for every run. srand(time(NULL)); printf("\nCut found by Karger's randomized algo is %d\n", kargerMinCut(graph)); return 0;}
//Java program to implement the Karger's algorithm to find Minimum Cut in an// undirected, unweighted and connected graph. import java.io.*;import java.util.*; class GFG { // a structure to represent a unweighted edge in graph public static class Edge { int src, dest; Edge(int s, int d){ this.src = s; this.dest = d; } } // a structure to represent a connected, undirected // and unweighted graph as a collection of edges. public static class Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. // Since the graph is undirected, the edge // from src to dest is also edge from dest // to src. Both are counted as 1 edge here. Edge edge[]; Graph(int v, int e){ this.V = v; this.E = e; this.edge = new Edge[e]; /*for(int i=0;i<e;i++){ this.edge[i]=new Edge(-1,-1); }*/ } } // A structure to represent a subset for union-find public static class subset { int parent; int rank; subset(int p, int r){ this.parent = p; this.rank = r; } } // A very basic implementation of Karger's randomized // algorithm for finding the minimum cut. Please note // that Karger's algorithm is a Monte Carlo Randomized algo // and the cut returned by the algorithm may not be // minimum always public static int kargerMinCut(Graph graph) { // Get data of given graph int V = graph.V, E = graph.E; Edge edge[] = graph.edge; // Allocate memory for creating V subsets. subset subsets[] = new subset[V]; // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v] = new subset(v,0); } // Initially there are V vertices in // contracted graph int vertices = V; // Keep contracting vertices until there are // 2 vertices. while (vertices > 2) { // Pick a random edge int i = ((int)(Math.random()*10)) % E; // Find vertices (or sets) of two corners // of current edge int subset1 = find(subsets, edge[i].src); int subset2 = find(subsets, edge[i].dest); // If two corners belong to same subset, // then no point considering this edge if (subset1 == subset2){ continue; } // Else contract the edge (or combine the // corners of edge into one vertex) else { System.out.println("Contracting edge "+edge[i].src+"-"+edge[i].dest); vertices--; Union(subsets, subset1, subset2); } } // Now we have two vertices (or subsets) left in // the contracted graph, so count the edges between // two components and return the count. int cutedges = 0; for (int i=0; i<E; i++) { int subset1 = find(subsets, edge[i].src); int subset2 = find(subsets, edge[i].dest); if (subset1 != subset2){ cutedges++; } } return cutedges; } // A utility function to find set of an element i // (uses path compression technique) public static int find(subset subsets[], int i) { // find root and make root as parent of i // (path compression) if (subsets[i].parent != i){ subsets[i].parent = find(subsets, subsets[i].parent); } return subsets[i].parent; } // A function that does union of two sets of x and y // (uses union by rank) public static void Union(subset subsets[], int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root of high // rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank){ subsets[xroot].parent = yroot; }else{ if (subsets[xroot].rank > subsets[yroot].rank){ subsets[yroot].parent = xroot; } // If ranks are same, then make one as root and // increment its rank by one else { subsets[yroot].parent = xroot; subsets[xroot].rank++; } } } // Driver program to test above functions public static void main (String[] args) { /* Let us create following unweighted graph 0------1 | \ | | \ | | \| 2------3 */ int V = 4; // Number of vertices in graph int E = 5; // Number of edges in graph // Creates a graph with V vertices and E edges Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0] = new Edge(0,1); // add edge 0-2 graph.edge[1] = new Edge(0,2); // add edge 0-3 graph.edge[2] = new Edge(0,3); // add edge 1-3 graph.edge[3] = new Edge(1,3); // add edge 2-3 graph.edge[4] = new Edge(2,3); System.out.println("Cut found by Karger's randomized algo is "+kargerMinCut(graph)); }}//This code is contributed by shruti456rawal
Contracting edge 0-1
Contracting edge 1-3
Cut found by Karger's randomized algo is 2
Note that the above program is based on outcome of a random function and may produce different output.In this post, we have discussed simple Karger’s algorithm and have seen that the algorithm doesn’t always produce min-cut. The above algorithm produces min-cut with probability greater or equal to that 1/(n2). See next post on Analysis and Applications of Karger’s Algorithm, applications, proof of this probability and improvements are discussed.
abhishek0719kadiyan
shruti456rawal
hardikkoriintern
graph-connectivity
Graph
Randomized
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jun, 2022"
},
{
"code": null,
"e": 232,
"s": 52,
"text": "Given an undirected and unweighted graph, find the smallest cut (smallest number of edges that disconnects the graph into two components). The input graph may have parallel edges."
},
{
"code": null,
"e": 306,
"s": 232,
"text": "For example consider the following example, the smallest cut has 2 edges."
},
{
"code": null,
"e": 710,
"s": 306,
"text": "A Simple Solution use Max-Flow based s-t cut algorithm to find minimum cut. Consider every pair of vertices as source ‘s’ and sink ‘t’, and call minimum s-t cut algorithm to find the s-t cut. Return minimum of all s-t cuts. Best possible time complexity of this algorithm is O(V5) for a graph. [How? there are total possible V2 pairs and s-t cut algorithm for one pair takes O(V*E) time and E = O(V2)]. "
},
{
"code": null,
"e": 830,
"s": 710,
"text": "Below is simple Karger’s Algorithm for this purpose. Below Karger’s algorithm can be implemented in O(E) = O(V2) time. "
},
{
"code": null,
"e": 1162,
"s": 830,
"text": "1) Initialize contracted graph CG as copy of original graph\n2) While there are more than 2 vertices.\n a) Pick a random edge (u, v) in the contracted graph.\n b) Merge (or contract) u and v into a single vertex (update \n the contracted graph).\n c) Remove self-loops\n3) Return cut represented by two vertices."
},
{
"code": null,
"e": 1399,
"s": 1162,
"text": "Let us understand above algorithm through the example given.Let the first randomly picked vertex be ‘a‘ which connects vertices 0 and 1. We remove this edge and contract the graph (combine vertices 0 and 1). We get the following graph. "
},
{
"code": null,
"e": 1496,
"s": 1399,
"text": "Let the next randomly picked edge be ‘d’. We remove this edge and combine vertices (0,1) and 3. "
},
{
"code": null,
"e": 1562,
"s": 1496,
"text": "We need to remove self-loops in the graph. So we remove edge ‘c’ "
},
{
"code": null,
"e": 1894,
"s": 1562,
"text": "Now graph has two vertices, so we stop. The number of edges in the resultant graph is the cut produced by Karger’s algorithm.Karger’s algorithm is a Monte Carlo algorithm and cut produced by it may not be minimum. For example, the following diagram shows that a different order of picking random edges produces a min-cut of size 3."
},
{
"code": null,
"e": 2067,
"s": 1894,
"text": "Below is C++ implementation of above algorithm. The input graph is represented as a collection of edges and union-find data structure is used to keep track of components. "
},
{
"code": null,
"e": 2071,
"s": 2067,
"text": "C++"
},
{
"code": null,
"e": 2076,
"s": 2071,
"text": "Java"
},
{
"code": "// Karger's algorithm to find Minimum Cut in an// undirected, unweighted and connected graph.#include <iostream>//#include <stdlib.h>#include <time.h> // a structure to represent a unweighted edge in graphstruct Edge{ int src, dest;}; // a structure to represent a connected, undirected// and unweighted graph as a collection of edges.struct Graph{ // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. // Since the graph is undirected, the edge // from src to dest is also edge from dest // to src. Both are counted as 1 edge here. Edge* edge;}; // A structure to represent a subset for union-findstruct subset{ int parent; int rank;}; // Function prototypes for union-find (These functions are defined// after kargerMinCut() )int find(struct subset subsets[], int i);void Union(struct subset subsets[], int x, int y); // A very basic implementation of Karger's randomized// algorithm for finding the minimum cut. Please note// that Karger's algorithm is a Monte Carlo Randomized algo// and the cut returned by the algorithm may not be// minimum alwaysint kargerMinCut(struct Graph* graph){ // Get data of given graph int V = graph->V, E = graph->E; Edge *edge = graph->edge; // Allocate memory for creating V subsets. struct subset *subsets = new subset[V]; // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } // Initially there are V vertices in // contracted graph int vertices = V; // Keep contracting vertices until there are // 2 vertices. while (vertices > 2) { // Pick a random edge int i = rand() % E; // Find vertices (or sets) of two corners // of current edge int subset1 = find(subsets, edge[i].src); int subset2 = find(subsets, edge[i].dest); // If two corners belong to same subset, // then no point considering this edge if (subset1 == subset2) continue; // Else contract the edge (or combine the // corners of edge into one vertex) else { printf(\"Contracting edge %d-%d\\n\", edge[i].src, edge[i].dest); vertices--; Union(subsets, subset1, subset2); } } // Now we have two vertices (or subsets) left in // the contracted graph, so count the edges between // two components and return the count. int cutedges = 0; for (int i=0; i<E; i++) { int subset1 = find(subsets, edge[i].src); int subset2 = find(subsets, edge[i].dest); if (subset1 != subset2) cutedges++; } return cutedges;} // A utility function to find set of an element i// (uses path compression technique)int find(struct subset subsets[], int i){ // find root and make root as parent of i // (path compression) if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent;} // A function that does union of two sets of x and y// (uses union by rank)void Union(struct subset subsets[], int x, int y){ int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root of high // rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and // increment its rank by one else { subsets[yroot].parent = xroot; subsets[xroot].rank++; }} // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){ Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[E]; return graph;} // Driver program to test above functionsint main(){ /* Let us create following unweighted graph 0------1 | \\ | | \\ | | \\| 2------3 */ int V = 4; // Number of vertices in graph int E = 5; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 graph->edge[0].src = 0; graph->edge[0].dest = 1; // add edge 0-2 graph->edge[1].src = 0; graph->edge[1].dest = 2; // add edge 0-3 graph->edge[2].src = 0; graph->edge[2].dest = 3; // add edge 1-3 graph->edge[3].src = 1; graph->edge[3].dest = 3; // add edge 2-3 graph->edge[4].src = 2; graph->edge[4].dest = 3; // Use a different seed value for every run. srand(time(NULL)); printf(\"\\nCut found by Karger's randomized algo is %d\\n\", kargerMinCut(graph)); return 0;}",
"e": 6808,
"s": 2076,
"text": null
},
{
"code": "//Java program to implement the Karger's algorithm to find Minimum Cut in an// undirected, unweighted and connected graph. import java.io.*;import java.util.*; class GFG { // a structure to represent a unweighted edge in graph public static class Edge { int src, dest; Edge(int s, int d){ this.src = s; this.dest = d; } } // a structure to represent a connected, undirected // and unweighted graph as a collection of edges. public static class Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. // Since the graph is undirected, the edge // from src to dest is also edge from dest // to src. Both are counted as 1 edge here. Edge edge[]; Graph(int v, int e){ this.V = v; this.E = e; this.edge = new Edge[e]; /*for(int i=0;i<e;i++){ this.edge[i]=new Edge(-1,-1); }*/ } } // A structure to represent a subset for union-find public static class subset { int parent; int rank; subset(int p, int r){ this.parent = p; this.rank = r; } } // A very basic implementation of Karger's randomized // algorithm for finding the minimum cut. Please note // that Karger's algorithm is a Monte Carlo Randomized algo // and the cut returned by the algorithm may not be // minimum always public static int kargerMinCut(Graph graph) { // Get data of given graph int V = graph.V, E = graph.E; Edge edge[] = graph.edge; // Allocate memory for creating V subsets. subset subsets[] = new subset[V]; // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v] = new subset(v,0); } // Initially there are V vertices in // contracted graph int vertices = V; // Keep contracting vertices until there are // 2 vertices. while (vertices > 2) { // Pick a random edge int i = ((int)(Math.random()*10)) % E; // Find vertices (or sets) of two corners // of current edge int subset1 = find(subsets, edge[i].src); int subset2 = find(subsets, edge[i].dest); // If two corners belong to same subset, // then no point considering this edge if (subset1 == subset2){ continue; } // Else contract the edge (or combine the // corners of edge into one vertex) else { System.out.println(\"Contracting edge \"+edge[i].src+\"-\"+edge[i].dest); vertices--; Union(subsets, subset1, subset2); } } // Now we have two vertices (or subsets) left in // the contracted graph, so count the edges between // two components and return the count. int cutedges = 0; for (int i=0; i<E; i++) { int subset1 = find(subsets, edge[i].src); int subset2 = find(subsets, edge[i].dest); if (subset1 != subset2){ cutedges++; } } return cutedges; } // A utility function to find set of an element i // (uses path compression technique) public static int find(subset subsets[], int i) { // find root and make root as parent of i // (path compression) if (subsets[i].parent != i){ subsets[i].parent = find(subsets, subsets[i].parent); } return subsets[i].parent; } // A function that does union of two sets of x and y // (uses union by rank) public static void Union(subset subsets[], int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root of high // rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank){ subsets[xroot].parent = yroot; }else{ if (subsets[xroot].rank > subsets[yroot].rank){ subsets[yroot].parent = xroot; } // If ranks are same, then make one as root and // increment its rank by one else { subsets[yroot].parent = xroot; subsets[xroot].rank++; } } } // Driver program to test above functions public static void main (String[] args) { /* Let us create following unweighted graph 0------1 | \\ | | \\ | | \\| 2------3 */ int V = 4; // Number of vertices in graph int E = 5; // Number of edges in graph // Creates a graph with V vertices and E edges Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0] = new Edge(0,1); // add edge 0-2 graph.edge[1] = new Edge(0,2); // add edge 0-3 graph.edge[2] = new Edge(0,3); // add edge 1-3 graph.edge[3] = new Edge(1,3); // add edge 2-3 graph.edge[4] = new Edge(2,3); System.out.println(\"Cut found by Karger's randomized algo is \"+kargerMinCut(graph)); }}//This code is contributed by shruti456rawal",
"e": 12287,
"s": 6808,
"text": null
},
{
"code": null,
"e": 12374,
"s": 12287,
"text": "Contracting edge 0-1\nContracting edge 1-3\n\nCut found by Karger's randomized algo is 2\n"
},
{
"code": null,
"e": 12825,
"s": 12374,
"text": "Note that the above program is based on outcome of a random function and may produce different output.In this post, we have discussed simple Karger’s algorithm and have seen that the algorithm doesn’t always produce min-cut. The above algorithm produces min-cut with probability greater or equal to that 1/(n2). See next post on Analysis and Applications of Karger’s Algorithm, applications, proof of this probability and improvements are discussed. "
},
{
"code": null,
"e": 12845,
"s": 12825,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 12860,
"s": 12845,
"text": "shruti456rawal"
},
{
"code": null,
"e": 12877,
"s": 12860,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 12896,
"s": 12877,
"text": "graph-connectivity"
},
{
"code": null,
"e": 12902,
"s": 12896,
"text": "Graph"
},
{
"code": null,
"e": 12913,
"s": 12902,
"text": "Randomized"
},
{
"code": null,
"e": 12919,
"s": 12913,
"text": "Graph"
}
] |
Python | Repeat each element K times in list | 08 Apr, 2019
Many times we have this particular use-case in which we need to repeat each element of list K times. The problems of making a double clone have been discussed but this problem extends to allow a flexible variable to define the number of times the element has to be repeated. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehensionThis particular task requires generally 2 loops and list comprehension can perform this particular task in one line and hence reduce the lines of codes and improving code readability.
# Python3 code to demonstrate # repeat element K times# using list comprehension # initializing list of liststest_list = [4, 5, 6] # printing original list print("The original list : " + str(test_list)) # declaring magnitude of repetitionK = 3 # using list comprehension# repeat elements K timesres = [ele for ele in test_list for i in range(K)] # printing result print("The list after adding elements : " + str(res))
The original list : [4, 5, 6]
The list after adding elements : [4, 4, 4, 5, 5, 5, 6, 6, 6]
Method #2 : Using itertools.chain.from_iterable() + itertools.repeat()This particular problem can also be solved using python inbuilt functions of itertools library. The repeat function, as name suggests does the task of repetition and grouping into a list is done by the from_iterable function.
# Python3 code to demonstrate # repeat element K times# using itertools.chain.from_iterable() + itertools.repeat()import itertools # initializing list of liststest_list = [4, 5, 6] # printing original list print("The original list : " + str(test_list)) # declaring magnitude of repetitionK = 3 # using itertools.chain.from_iterable() # + itertools.repeat() repeat elements K timesres = list(itertools.chain.from_iterable(itertools.repeat(i, K) for i in test_list)) # printing result print("The list after adding elements : " + str(res))
The original list : [4, 5, 6]
The list after adding elements : [4, 4, 4, 5, 5, 5, 6, 6, 6]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 362,
"s": 28,
"text": "Many times we have this particular use-case in which we need to repeat each element of list K times. The problems of making a double clone have been discussed but this problem extends to allow a flexible variable to define the number of times the element has to be repeated. Let’s discuss certain ways in which this can be performed."
},
{
"code": null,
"e": 582,
"s": 362,
"text": "Method #1 : Using list comprehensionThis particular task requires generally 2 loops and list comprehension can perform this particular task in one line and hence reduce the lines of codes and improving code readability."
},
{
"code": "# Python3 code to demonstrate # repeat element K times# using list comprehension # initializing list of liststest_list = [4, 5, 6] # printing original list print(\"The original list : \" + str(test_list)) # declaring magnitude of repetitionK = 3 # using list comprehension# repeat elements K timesres = [ele for ele in test_list for i in range(K)] # printing result print(\"The list after adding elements : \" + str(res))",
"e": 1008,
"s": 582,
"text": null
},
{
"code": null,
"e": 1101,
"s": 1008,
"text": "The original list : [4, 5, 6]\nThe list after adding elements : [4, 4, 4, 5, 5, 5, 6, 6, 6]\n"
},
{
"code": null,
"e": 1399,
"s": 1103,
"text": "Method #2 : Using itertools.chain.from_iterable() + itertools.repeat()This particular problem can also be solved using python inbuilt functions of itertools library. The repeat function, as name suggests does the task of repetition and grouping into a list is done by the from_iterable function."
},
{
"code": "# Python3 code to demonstrate # repeat element K times# using itertools.chain.from_iterable() + itertools.repeat()import itertools # initializing list of liststest_list = [4, 5, 6] # printing original list print(\"The original list : \" + str(test_list)) # declaring magnitude of repetitionK = 3 # using itertools.chain.from_iterable() # + itertools.repeat() repeat elements K timesres = list(itertools.chain.from_iterable(itertools.repeat(i, K) for i in test_list)) # printing result print(\"The list after adding elements : \" + str(res))",
"e": 1985,
"s": 1399,
"text": null
},
{
"code": null,
"e": 2078,
"s": 1985,
"text": "The original list : [4, 5, 6]\nThe list after adding elements : [4, 4, 4, 5, 5, 5, 6, 6, 6]\n"
},
{
"code": null,
"e": 2099,
"s": 2078,
"text": "Python list-programs"
},
{
"code": null,
"e": 2106,
"s": 2099,
"text": "Python"
},
{
"code": null,
"e": 2122,
"s": 2106,
"text": "Python Programs"
}
] |
Node.js Stream.pipeline() Method | 11 Oct, 2021
The stream.pipeline() method is a module method that is used to the pipe by linking the streams passing on errors and accurately cleaning up and providing a callback function when the pipeline is done.
Syntax:
stream.pipeline(...streams, callback)
Parameters: This method accepts two parameters as mentioned above and described below.
...streams: These are two or more streams which are to be piped together.
callback: This function is called when the pipeline is fully done and it shows an ‘error’ if the pipeline is not accomplished.
Return Value: It returns a cleanup function.
Below examples illustrate the use of stream.pipeline() method in Node.js:
Example 1:
// Node.js program to demonstrate the // stream.pipeline() method // Including fs and zlib modulevar fs = require('fs');const zlib = require('zlib'); // Constructing finished from streamconst { pipeline } = require('stream'); // Constructing promisify from// utilconst { promisify } = require('util'); // Defining pipelineAsync methodconst pipelineAsync = promisify(pipeline); // Constructing readable streamconst readable = fs.createReadStream("input.text"); // Constructing writable streamvar writable = fs.createWriteStream("output.text"); // Creating transform streamconst transform = zlib.createGzip(); // Async function(async function run() { try{ // pipelining three streams await pipelineAsync( readable, transform, writable ); console.log("pipeline accomplished."); } // Shows error catch(err) { console.error('pipeline failed with error:', err); } })();
Output:
Promise { }
pipeline accomplished.
Example 2:
// Node.js program to demonstrate the // stream.pipeline() method // Including fs and zlib modulevar fs = require('fs');const zlib = require('zlib'); // Constructing finished from streamconst { pipeline } = require('stream'); // Constructing promisify from// utilconst { promisify } = require('util'); // Defining pipelineAsync methodconst pipelineAsync = promisify(pipeline); // Constructing readable streamconst readable = fs.createReadStream("input.text"); // Constructing writable streamvar writable = fs.createWriteStream("output.text"); // Creating transform streamconst transform = zlib.createGzip(); // Async function(async function run() { try{ // pipelining three streams await pipelineAsync( readable, writable, transform ); console.log("pipeline accomplished."); } // Shows error catch(err) { console.error('pipeline failed with error:', err); } })();
Output: Here, the order of streams is not proper while piping so an error occurs.
Promise { }
pipeline failed with error: Error [ERR_STREAM_CANNOT_PIPE]: Cannot pipe, not readable
at WriteStream.Writable.pipe (_stream_writable.js:243:24)
at pipe (internal/streams/pipeline.js:57:15)
at Array.reduce ()
at pipeline (internal/streams/pipeline.js:88:18)
at Promise (internal/util.js:274:30)
at new Promise ()
at pipeline (internal/util.js:273:12)
at run (/home/runner/ThirstyTimelyKey/index.js:33:11)
at /home/runner/ThirstyTimelyKey/index.js:45:5
at Script.runInContext (vm.js:133:20)
Reference: https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback.
Akanksha_Rai
Node.js-Stream-module
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": "\n11 Oct, 2021"
},
{
"code": null,
"e": 230,
"s": 28,
"text": "The stream.pipeline() method is a module method that is used to the pipe by linking the streams passing on errors and accurately cleaning up and providing a callback function when the pipeline is done."
},
{
"code": null,
"e": 238,
"s": 230,
"text": "Syntax:"
},
{
"code": null,
"e": 276,
"s": 238,
"text": "stream.pipeline(...streams, callback)"
},
{
"code": null,
"e": 363,
"s": 276,
"text": "Parameters: This method accepts two parameters as mentioned above and described below."
},
{
"code": null,
"e": 437,
"s": 363,
"text": "...streams: These are two or more streams which are to be piped together."
},
{
"code": null,
"e": 564,
"s": 437,
"text": "callback: This function is called when the pipeline is fully done and it shows an ‘error’ if the pipeline is not accomplished."
},
{
"code": null,
"e": 609,
"s": 564,
"text": "Return Value: It returns a cleanup function."
},
{
"code": null,
"e": 683,
"s": 609,
"text": "Below examples illustrate the use of stream.pipeline() method in Node.js:"
},
{
"code": null,
"e": 694,
"s": 683,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // stream.pipeline() method // Including fs and zlib modulevar fs = require('fs');const zlib = require('zlib'); // Constructing finished from streamconst { pipeline } = require('stream'); // Constructing promisify from// utilconst { promisify } = require('util'); // Defining pipelineAsync methodconst pipelineAsync = promisify(pipeline); // Constructing readable streamconst readable = fs.createReadStream(\"input.text\"); // Constructing writable streamvar writable = fs.createWriteStream(\"output.text\"); // Creating transform streamconst transform = zlib.createGzip(); // Async function(async function run() { try{ // pipelining three streams await pipelineAsync( readable, transform, writable ); console.log(\"pipeline accomplished.\"); } // Shows error catch(err) { console.error('pipeline failed with error:', err); } })();",
"e": 1613,
"s": 694,
"text": null
},
{
"code": null,
"e": 1621,
"s": 1613,
"text": "Output:"
},
{
"code": null,
"e": 1657,
"s": 1621,
"text": "Promise { }\npipeline accomplished."
},
{
"code": null,
"e": 1668,
"s": 1657,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // stream.pipeline() method // Including fs and zlib modulevar fs = require('fs');const zlib = require('zlib'); // Constructing finished from streamconst { pipeline } = require('stream'); // Constructing promisify from// utilconst { promisify } = require('util'); // Defining pipelineAsync methodconst pipelineAsync = promisify(pipeline); // Constructing readable streamconst readable = fs.createReadStream(\"input.text\"); // Constructing writable streamvar writable = fs.createWriteStream(\"output.text\"); // Creating transform streamconst transform = zlib.createGzip(); // Async function(async function run() { try{ // pipelining three streams await pipelineAsync( readable, writable, transform ); console.log(\"pipeline accomplished.\"); } // Shows error catch(err) { console.error('pipeline failed with error:', err); } })();",
"e": 2587,
"s": 1668,
"text": null
},
{
"code": null,
"e": 2669,
"s": 2587,
"text": "Output: Here, the order of streams is not proper while piping so an error occurs."
},
{
"code": null,
"e": 3212,
"s": 2669,
"text": "Promise { }\npipeline failed with error: Error [ERR_STREAM_CANNOT_PIPE]: Cannot pipe, not readable\n at WriteStream.Writable.pipe (_stream_writable.js:243:24)\n at pipe (internal/streams/pipeline.js:57:15)\n at Array.reduce ()\n at pipeline (internal/streams/pipeline.js:88:18)\n at Promise (internal/util.js:274:30)\n at new Promise ()\n at pipeline (internal/util.js:273:12)\n at run (/home/runner/ThirstyTimelyKey/index.js:33:11)\n at /home/runner/ThirstyTimelyKey/index.js:45:5\n at Script.runInContext (vm.js:133:20)\n"
},
{
"code": null,
"e": 3299,
"s": 3212,
"text": "Reference: https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback."
},
{
"code": null,
"e": 3312,
"s": 3299,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3334,
"s": 3312,
"text": "Node.js-Stream-module"
},
{
"code": null,
"e": 3342,
"s": 3334,
"text": "Node.js"
},
{
"code": null,
"e": 3359,
"s": 3342,
"text": "Web Technologies"
}
] |
Difference between Angular and AngularJS | 30 Jun, 2022
In this article, we will learn about Angular JS & Angular, along with understanding the significant distinction between them.
Angular JS: AngularJS is a JavaScript open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications. It changes the static HTML to dynamic HTML. Its features like dynamic binding and dependency injection eliminate the need for code that we have to write otherwise. AngularJS is rapidly growing and because of this reason, we have different versions of AngularJS with the latest stable being 1.7.7. It is also important to note that Angular is different from AngularJS. It is an open-source project which can be freely used and changed by anyone. It extends HTML attributes with Directives, and data is bound with HTML.
Example: This example describes the String interpolation in AngularJS.
HTML
<!DOCTYPE html><html><head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head><body> <h1 style="color:green"> GeeksforGeeks </h1> <h3> AngularJS String Interpolation </h3> <div ng-app="" ng-init="Course='AngularJS'; Subject='Tutorial'; Company='GeeksforGeeks';"> <p> Learn {{ Course + " " + Subject }} from <a href="https://www.geeksforgeeks.org/angularjs/">{{Company}} </a> </p> </div></body></html>
Output:
Angular: It is a popular open-source Typescript framework created by Google for developing web applications. Front-end developers use frameworks like Angular or React for presenting and manipulating data efficiently. Updated Angular is much more efficient compared to the older version of Angular, especially, since the core functionality was moved to different modules. That’s why it becomes so much fast and smooth compare to the older one. Newly added angular CLI, & with the help of this command-line interface, we can install the required packages that facilitate creation & make the complex-structured code into a modular form that can be easy to manage.
Example: This example describes the String interpolation in Angular.
app.component.html
<h1 [style.color]="'green'" [style.font-family]="'Arial'" [style.text-align]="'center'"> {{ title }} : {{ about }}</h1><p [style.font-weight]="'bolder'"> This example illustrates {{ data }} in Angular.</p>
app.component.ts
import { Component } from "@angular/core";@Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"],})export class AppComponent { title = "GeeksforGeeks"; about = "Learning Portal for Geeks"; data = "String Interpolation";}
Output:
Difference between the AngularJS & Angular: Although, there are significant key differences between Angular JS & Angular, which can be categorized in the following way:
Architecture
It supports the Model-View-Controller design. The view processes the information available in the model to generate the output.
It uses components and directives. Components are the directives with a template.
Written Language
Written in JavaScript.
Written in Microsoft’s TypeScript language, which is a superset of ECMAScript 6 (ES6).
Mobile support
It does not support mobile browsers.
Angular is supported by all the popular mobile browsers.
Expression Syntax
ng-bind is used to bind data from view to model and vice versa.
Properties enclosed in “()” and “[]” are used to bind data between view and model.
Dependency Injection
It does not use Dependency Injection.
Angular is supported by all the popular mobile browsers.
Supported Languages
It only supports JavaScript.
It provides support for TypeScript and JavaScript.
Routing
AngularJS uses $routeprovider.when() for routing configuration.
Angular uses @Route Config{(...)} for routing configuration.
Structure
It is less manageable in comparison to Angular.
It has a better structure compared to AngularJS, easier to create and maintain for large applications but behind AngularJS in the case of small applications.
CLI
It does not come with a CLI tool.
It comes with the Angular CLI tool.
Examples Application
iStock, Netflix, and Angular JS official website.
Upwork, Gmail, and Wikiwand.
Note: Angular is a great framework, it has many improvements in terms of AngularJS, it is good for bigger applications along with good for smaller applications, but there is a huge competition between Angular and AngularJS.
ManasChhabra2
emallove
bunnyram19
bhaskargeeksforgeeks
siddharthredhu01
bijaybhaskar
Difference Between
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": "\n30 Jun, 2022"
},
{
"code": null,
"e": 178,
"s": 52,
"text": "In this article, we will learn about Angular JS & Angular, along with understanding the significant distinction between them."
},
{
"code": null,
"e": 946,
"s": 178,
"text": "Angular JS: AngularJS is a JavaScript open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications. It changes the static HTML to dynamic HTML. Its features like dynamic binding and dependency injection eliminate the need for code that we have to write otherwise. AngularJS is rapidly growing and because of this reason, we have different versions of AngularJS with the latest stable being 1.7.7. It is also important to note that Angular is different from AngularJS. It is an open-source project which can be freely used and changed by anyone. It extends HTML attributes with Directives, and data is bound with HTML."
},
{
"code": null,
"e": 1017,
"s": 946,
"text": "Example: This example describes the String interpolation in AngularJS."
},
{
"code": null,
"e": 1022,
"s": 1017,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head><body> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3> AngularJS String Interpolation </h3> <div ng-app=\"\" ng-init=\"Course='AngularJS'; Subject='Tutorial'; Company='GeeksforGeeks';\"> <p> Learn {{ Course + \" \" + Subject }} from <a href=\"https://www.geeksforgeeks.org/angularjs/\">{{Company}} </a> </p> </div></body></html>",
"e": 1611,
"s": 1022,
"text": null
},
{
"code": null,
"e": 1619,
"s": 1611,
"text": "Output:"
},
{
"code": null,
"e": 2282,
"s": 1621,
"text": "Angular: It is a popular open-source Typescript framework created by Google for developing web applications. Front-end developers use frameworks like Angular or React for presenting and manipulating data efficiently. Updated Angular is much more efficient compared to the older version of Angular, especially, since the core functionality was moved to different modules. That’s why it becomes so much fast and smooth compare to the older one. Newly added angular CLI, & with the help of this command-line interface, we can install the required packages that facilitate creation & make the complex-structured code into a modular form that can be easy to manage."
},
{
"code": null,
"e": 2351,
"s": 2282,
"text": "Example: This example describes the String interpolation in Angular."
},
{
"code": null,
"e": 2370,
"s": 2351,
"text": "app.component.html"
},
{
"code": "<h1 [style.color]=\"'green'\" [style.font-family]=\"'Arial'\" [style.text-align]=\"'center'\"> {{ title }} : {{ about }}</h1><p [style.font-weight]=\"'bolder'\"> This example illustrates {{ data }} in Angular.</p>",
"e": 2581,
"s": 2370,
"text": null
},
{
"code": null,
"e": 2598,
"s": 2581,
"text": "app.component.ts"
},
{
"code": "import { Component } from \"@angular/core\";@Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styleUrls: [\"./app.component.css\"],})export class AppComponent { title = \"GeeksforGeeks\"; about = \"Learning Portal for Geeks\"; data = \"String Interpolation\";}",
"e": 2875,
"s": 2598,
"text": null
},
{
"code": null,
"e": 2883,
"s": 2875,
"text": "Output:"
},
{
"code": null,
"e": 3054,
"s": 2885,
"text": "Difference between the AngularJS & Angular: Although, there are significant key differences between Angular JS & Angular, which can be categorized in the following way:"
},
{
"code": null,
"e": 3067,
"s": 3054,
"text": "Architecture"
},
{
"code": null,
"e": 3196,
"s": 3067,
"text": "It supports the Model-View-Controller design. The view processes the information available in the model to generate the output. "
},
{
"code": null,
"e": 3278,
"s": 3196,
"text": "It uses components and directives. Components are the directives with a template."
},
{
"code": null,
"e": 3295,
"s": 3278,
"text": "Written Language"
},
{
"code": null,
"e": 3319,
"s": 3295,
"text": "Written in JavaScript. "
},
{
"code": null,
"e": 3406,
"s": 3319,
"text": "Written in Microsoft’s TypeScript language, which is a superset of ECMAScript 6 (ES6)."
},
{
"code": null,
"e": 3421,
"s": 3406,
"text": "Mobile support"
},
{
"code": null,
"e": 3459,
"s": 3421,
"text": "It does not support mobile browsers. "
},
{
"code": null,
"e": 3516,
"s": 3459,
"text": "Angular is supported by all the popular mobile browsers."
},
{
"code": null,
"e": 3534,
"s": 3516,
"text": "Expression Syntax"
},
{
"code": null,
"e": 3599,
"s": 3534,
"text": "ng-bind is used to bind data from view to model and vice versa. "
},
{
"code": null,
"e": 3683,
"s": 3599,
"text": "Properties enclosed in “()” and “[]” are used to bind data between view and model. "
},
{
"code": null,
"e": 3704,
"s": 3683,
"text": "Dependency Injection"
},
{
"code": null,
"e": 3743,
"s": 3704,
"text": "It does not use Dependency Injection. "
},
{
"code": null,
"e": 3800,
"s": 3743,
"text": "Angular is supported by all the popular mobile browsers."
},
{
"code": null,
"e": 3820,
"s": 3800,
"text": "Supported Languages"
},
{
"code": null,
"e": 3849,
"s": 3820,
"text": "It only supports JavaScript."
},
{
"code": null,
"e": 3900,
"s": 3849,
"text": "It provides support for TypeScript and JavaScript."
},
{
"code": null,
"e": 3908,
"s": 3900,
"text": "Routing"
},
{
"code": null,
"e": 3973,
"s": 3908,
"text": "AngularJS uses $routeprovider.when() for routing configuration. "
},
{
"code": null,
"e": 4034,
"s": 3973,
"text": "Angular uses @Route Config{(...)} for routing configuration."
},
{
"code": null,
"e": 4044,
"s": 4034,
"text": "Structure"
},
{
"code": null,
"e": 4093,
"s": 4044,
"text": "It is less manageable in comparison to Angular. "
},
{
"code": null,
"e": 4251,
"s": 4093,
"text": "It has a better structure compared to AngularJS, easier to create and maintain for large applications but behind AngularJS in the case of small applications."
},
{
"code": null,
"e": 4255,
"s": 4251,
"text": "CLI"
},
{
"code": null,
"e": 4289,
"s": 4255,
"text": "It does not come with a CLI tool."
},
{
"code": null,
"e": 4325,
"s": 4289,
"text": "It comes with the Angular CLI tool."
},
{
"code": null,
"e": 4346,
"s": 4325,
"text": "Examples Application"
},
{
"code": null,
"e": 4396,
"s": 4346,
"text": "iStock, Netflix, and Angular JS official website."
},
{
"code": null,
"e": 4425,
"s": 4396,
"text": "Upwork, Gmail, and Wikiwand."
},
{
"code": null,
"e": 4649,
"s": 4425,
"text": "Note: Angular is a great framework, it has many improvements in terms of AngularJS, it is good for bigger applications along with good for smaller applications, but there is a huge competition between Angular and AngularJS."
},
{
"code": null,
"e": 4663,
"s": 4649,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 4672,
"s": 4663,
"text": "emallove"
},
{
"code": null,
"e": 4683,
"s": 4672,
"text": "bunnyram19"
},
{
"code": null,
"e": 4704,
"s": 4683,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 4721,
"s": 4704,
"text": "siddharthredhu01"
},
{
"code": null,
"e": 4734,
"s": 4721,
"text": "bijaybhaskar"
},
{
"code": null,
"e": 4753,
"s": 4734,
"text": "Difference Between"
},
{
"code": null,
"e": 4770,
"s": 4753,
"text": "Web Technologies"
}
] |
How to Perform Debouncing in ReactJS ? | 29 Jun, 2021
A Debouncing Events in ReactJS will allow you to call a function that ensures that a time-consuming task does not fire so often. It’s a function that takes a function as a parameter and wraps that function in a closure and returns it so this new function displays the “wait for a bit” behavior.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app react-debouncing
Step 2: After creating your project folder i.e. react-debouncing, move to it using the following command:
cd react-debouncing
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install lodash
Project Structure: It will look like the following.
Project Directory
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, { Component } from "react";import { debounce } from "lodash"; class WidgetText extends Component { state = { text: "" }; handleChange = (e) => { this.setState({ text: e.target.value }); }; render() { return ( <div> <input onChange={this.handleChange} /> <textarea value={this.state.text} /> </div> ); }} class App extends Component { state = { show: true }; handleToggle = debounce(() => { this.setState(prevState => ({ show: !prevState.show })); }, 500); render() { return ( <div> <button onClick={this.handleToggle}>Toggle</button> {this.state.show ? <WidgetText /> : null} </div> ); }} export default App;
Explanation:
Have a simple page with a toggle button, if we click it the input fields go away and click it again to get the input field back and if we type in the input box the text will immediately mirror in the text area below.
We have a React WidgetText component, and it essentially just has the input and text area and then the app component itself has the toggle button.
Conditionally so if we click the toggle button it will come in into the handler grab, the previous state look at it shows bool off of the state and flip it, So if it was true then it will render the WidgetText if it is false we do not render the WidgetText.
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:
React-Questions
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 349,
"s": 54,
"text": "A Debouncing Events in ReactJS will allow you to call a function that ensures that a time-consuming task does not fire so often. It’s a function that takes a function as a parameter and wraps that function in a closure and returns it so this new function displays the “wait for a bit” behavior."
},
{
"code": null,
"e": 399,
"s": 349,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 463,
"s": 399,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 505,
"s": 463,
"text": "npx create-react-app react-debouncing "
},
{
"code": null,
"e": 611,
"s": 505,
"text": "Step 2: After creating your project folder i.e. react-debouncing, move to it using the following command:"
},
{
"code": null,
"e": 631,
"s": 611,
"text": "cd react-debouncing"
},
{
"code": null,
"e": 738,
"s": 633,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 757,
"s": 738,
"text": "npm install lodash"
},
{
"code": null,
"e": 809,
"s": 757,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 827,
"s": 809,
"text": "Project Directory"
},
{
"code": null,
"e": 957,
"s": 827,
"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": 964,
"s": 957,
"text": "App.js"
},
{
"code": "import React, { Component } from \"react\";import { debounce } from \"lodash\"; class WidgetText extends Component { state = { text: \"\" }; handleChange = (e) => { this.setState({ text: e.target.value }); }; render() { return ( <div> <input onChange={this.handleChange} /> <textarea value={this.state.text} /> </div> ); }} class App extends Component { state = { show: true }; handleToggle = debounce(() => { this.setState(prevState => ({ show: !prevState.show })); }, 500); render() { return ( <div> <button onClick={this.handleToggle}>Toggle</button> {this.state.show ? <WidgetText /> : null} </div> ); }} export default App;",
"e": 1678,
"s": 964,
"text": null
},
{
"code": null,
"e": 1691,
"s": 1678,
"text": "Explanation:"
},
{
"code": null,
"e": 1908,
"s": 1691,
"text": "Have a simple page with a toggle button, if we click it the input fields go away and click it again to get the input field back and if we type in the input box the text will immediately mirror in the text area below."
},
{
"code": null,
"e": 2055,
"s": 1908,
"text": "We have a React WidgetText component, and it essentially just has the input and text area and then the app component itself has the toggle button."
},
{
"code": null,
"e": 2313,
"s": 2055,
"text": "Conditionally so if we click the toggle button it will come in into the handler grab, the previous state look at it shows bool off of the state and flip it, So if it was true then it will render the WidgetText if it is false we do not render the WidgetText."
},
{
"code": null,
"e": 2426,
"s": 2313,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2436,
"s": 2426,
"text": "npm start"
},
{
"code": null,
"e": 2535,
"s": 2436,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2551,
"s": 2535,
"text": "React-Questions"
},
{
"code": null,
"e": 2566,
"s": 2551,
"text": "ReactJS-Basics"
},
{
"code": null,
"e": 2574,
"s": 2566,
"text": "ReactJS"
},
{
"code": null,
"e": 2591,
"s": 2574,
"text": "Web Technologies"
}
] |
NLP | Singularizing Plural Nouns and Swapping Infinite Phrases | 26 Feb, 2019
Let’s understand this with an example :
Is our child training enough?Is are our child training enough?
Is our child training enough?
Is are our child training enough?
The verb ‘is’ can only be used with singular nouns. For plural nouns, we use ‘are’. This problem is very common in the real world and we can correct this mistake by creating verb correction mappings that are used depending on whether there’s plural or singular noun in the chunk.
Code #1 : singularize_plural_noun() class
def singularize_plural_noun(chunk): nnsidx = first_chunk_index(chunk, tag_equals('NNS')) if nnsidx is not None and nnsidx + 1 < len(chunk) and chunk[nnsidx + 1][1][:2] == 'NN': noun, nnstag = chunk[nnsidx] chunk[nnsidx] = (noun.rstrip('s'), nnstag.rstrip('S')) return chunk
Code #2 : Singularizing Plurals
singularize_plural_noun([('recipes', 'NNS'), ('book', 'NN')])
Output :
[('recipe', 'NN'), ('book', 'NN')]
The code above looks for the tag NNS to look for Plural Noun. After founding it, if the next word is a noun (determined by making sure the tag starts with NN), then we depluralize the plural noun by removing ‘s’ from the right side of both the tag and the word.
Swapping Infinite PhrasesAn infinitive phrase is of the form A of B, such as ‘world of movies’. On can transform this to ‘movies world’ and it still holds the same meaning.
Code #3 : Let’s understand the swap_infinitive_phrase() class
def swap_infinitive_phrase(chunk): def inpred(wt): word, tag = wt return tag == 'IN' and word != 'like' inidx = first_chunk_index(chunk, inpred) if inidx is None: return chunk nnidx = first_chunk_index(chunk, tag_startswith('NN'), start = inidx, step =-1) or 0 return chunk[:nnidx] + chunk[inidx + 1:] + chunk[nnidx:inidx]
Code #4 : Let’s evaluate swap_infinitive_phrase
from transforms import swap_infinitive_phrase swap_infinitive_phrase([('book', 'NN'), ('of', 'IN'), ('recipes', 'NNS')])
Output :
[('recipes', 'NNS'), ('book', 'NN')]
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Supervised and Unsupervised learning
Search Algorithms in AI
ML | Monte Carlo Tree Search (MCTS)
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Feb, 2019"
},
{
"code": null,
"e": 68,
"s": 28,
"text": "Let’s understand this with an example :"
},
{
"code": null,
"e": 131,
"s": 68,
"text": "Is our child training enough?Is are our child training enough?"
},
{
"code": null,
"e": 161,
"s": 131,
"text": "Is our child training enough?"
},
{
"code": null,
"e": 195,
"s": 161,
"text": "Is are our child training enough?"
},
{
"code": null,
"e": 475,
"s": 195,
"text": "The verb ‘is’ can only be used with singular nouns. For plural nouns, we use ‘are’. This problem is very common in the real world and we can correct this mistake by creating verb correction mappings that are used depending on whether there’s plural or singular noun in the chunk."
},
{
"code": null,
"e": 517,
"s": 475,
"text": "Code #1 : singularize_plural_noun() class"
},
{
"code": "def singularize_plural_noun(chunk): nnsidx = first_chunk_index(chunk, tag_equals('NNS')) if nnsidx is not None and nnsidx + 1 < len(chunk) and chunk[nnsidx + 1][1][:2] == 'NN': noun, nnstag = chunk[nnsidx] chunk[nnsidx] = (noun.rstrip('s'), nnstag.rstrip('S')) return chunk",
"e": 854,
"s": 517,
"text": null
},
{
"code": null,
"e": 887,
"s": 854,
"text": " Code #2 : Singularizing Plurals"
},
{
"code": "singularize_plural_noun([('recipes', 'NNS'), ('book', 'NN')])",
"e": 949,
"s": 887,
"text": null
},
{
"code": null,
"e": 958,
"s": 949,
"text": "Output :"
},
{
"code": null,
"e": 994,
"s": 958,
"text": "[('recipe', 'NN'), ('book', 'NN')]\n"
},
{
"code": null,
"e": 1256,
"s": 994,
"text": "The code above looks for the tag NNS to look for Plural Noun. After founding it, if the next word is a noun (determined by making sure the tag starts with NN), then we depluralize the plural noun by removing ‘s’ from the right side of both the tag and the word."
},
{
"code": null,
"e": 1429,
"s": 1256,
"text": "Swapping Infinite PhrasesAn infinitive phrase is of the form A of B, such as ‘world of movies’. On can transform this to ‘movies world’ and it still holds the same meaning."
},
{
"code": null,
"e": 1491,
"s": 1429,
"text": "Code #3 : Let’s understand the swap_infinitive_phrase() class"
},
{
"code": "def swap_infinitive_phrase(chunk): def inpred(wt): word, tag = wt return tag == 'IN' and word != 'like' inidx = first_chunk_index(chunk, inpred) if inidx is None: return chunk nnidx = first_chunk_index(chunk, tag_startswith('NN'), start = inidx, step =-1) or 0 return chunk[:nnidx] + chunk[inidx + 1:] + chunk[nnidx:inidx]",
"e": 1958,
"s": 1491,
"text": null
},
{
"code": null,
"e": 2007,
"s": 1958,
"text": " Code #4 : Let’s evaluate swap_infinitive_phrase"
},
{
"code": "from transforms import swap_infinitive_phrase swap_infinitive_phrase([('book', 'NN'), ('of', 'IN'), ('recipes', 'NNS')])",
"e": 2153,
"s": 2007,
"text": null
},
{
"code": null,
"e": 2162,
"s": 2153,
"text": "Output :"
},
{
"code": null,
"e": 2200,
"s": 2162,
"text": "[('recipes', 'NNS'), ('book', 'NN')]\n"
},
{
"code": null,
"e": 2228,
"s": 2200,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 2240,
"s": 2228,
"text": "Python-nltk"
},
{
"code": null,
"e": 2257,
"s": 2240,
"text": "Machine Learning"
},
{
"code": null,
"e": 2264,
"s": 2257,
"text": "Python"
},
{
"code": null,
"e": 2281,
"s": 2264,
"text": "Machine Learning"
},
{
"code": null,
"e": 2379,
"s": 2281,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2402,
"s": 2379,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 2425,
"s": 2402,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 2462,
"s": 2425,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 2486,
"s": 2462,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 2522,
"s": 2486,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2550,
"s": 2522,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2572,
"s": 2550,
"text": "Python map() function"
},
{
"code": null,
"e": 2622,
"s": 2572,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2640,
"s": 2622,
"text": "Python Dictionary"
}
] |
Creating an ArrayList with Multiple Object Types in Java | 22 Oct, 2021
ArrayList class Java is basically a resizable array i.e. it can grow and shrink in size dynamically according to the values that we add to it. It is present in java.util package.
Syntax: To create an ArrayList of Integer type is mentioned below.
List<Integer> list = new ArrayList <Integer>();
It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types.
We will discuss how we can use the Object class to create an ArrayList.
Object class is the root of the class hierarchy. It is being extended by every class in Java either directly or indirectly. If a class doesn’t inherit from any other class then it extends the Object class directly otherwise if it extends any class then it extends the Object class indirectly from its base class. We can use the Object class to declare our ArrayList using the syntax mentioned below.
ArrayList<Object> list = new ArrayList<Object>();
The above list can hold values of any type. The code given below presents an example of the ArrayList with the Objects of multiple types.
Java
// Java program to create an ArrayList with// Multiple Object Types in Java import java.util.ArrayList; public class GFG { public static void main(String[] args) { // Creating an ArrayList of Object type ArrayList<Object> arr = new ArrayList<Object>(); // Inserting String value in arr arr.add("GeeksForGeeks"); // Inserting Integer value in arr arr.add(14); // Inserting Long value in arr arr.add(1800L); // Inserting Double value in arr arr.add(6.0D); // Inserting Float value in arr arr.add(1.99F); // arr after all insertions: ["GeeksForGeeks", 14, // 1800L, 6.0D, 1.99F] System.out.print( "ArrayList after all insertions: "); display(arr); // Replacing element at index 0 (i.e. an String) // with an Integer type value 50 arr.set(0, 50); // Replacing element at index 1 (Integer value) // with a Double type value arr.set(1, 10.0D); // arr after modifications: [50, 10.0D, // 1800L, 6.0D, 1.99F] System.out.print("ArrayList after modifications: "); display(arr); } // Function to display elements of the ArrayList public static void display(ArrayList<Object> arr) { for (int i = 0; i < arr.size(); i++) { System.out.print(arr.get(i) + " "); } System.out.println(); }}
ArrayList after all insertions: GeeksForGeeks 14 1800 6.0 1.99
ArrayList after modifications: 50 10.0 1800 6.0 1.99
ruhelaa48
Java-ArrayList
Java-Collections
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 208,
"s": 28,
"text": "ArrayList class Java is basically a resizable array i.e. it can grow and shrink in size dynamically according to the values that we add to it. It is present in java.util package. "
},
{
"code": null,
"e": 275,
"s": 208,
"text": "Syntax: To create an ArrayList of Integer type is mentioned below."
},
{
"code": null,
"e": 323,
"s": 275,
"text": "List<Integer> list = new ArrayList <Integer>();"
},
{
"code": null,
"e": 515,
"s": 323,
"text": "It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types. "
},
{
"code": null,
"e": 587,
"s": 515,
"text": "We will discuss how we can use the Object class to create an ArrayList."
},
{
"code": null,
"e": 988,
"s": 587,
"text": "Object class is the root of the class hierarchy. It is being extended by every class in Java either directly or indirectly. If a class doesn’t inherit from any other class then it extends the Object class directly otherwise if it extends any class then it extends the Object class indirectly from its base class. We can use the Object class to declare our ArrayList using the syntax mentioned below. "
},
{
"code": null,
"e": 1038,
"s": 988,
"text": "ArrayList<Object> list = new ArrayList<Object>();"
},
{
"code": null,
"e": 1176,
"s": 1038,
"text": "The above list can hold values of any type. The code given below presents an example of the ArrayList with the Objects of multiple types."
},
{
"code": null,
"e": 1181,
"s": 1176,
"text": "Java"
},
{
"code": "// Java program to create an ArrayList with// Multiple Object Types in Java import java.util.ArrayList; public class GFG { public static void main(String[] args) { // Creating an ArrayList of Object type ArrayList<Object> arr = new ArrayList<Object>(); // Inserting String value in arr arr.add(\"GeeksForGeeks\"); // Inserting Integer value in arr arr.add(14); // Inserting Long value in arr arr.add(1800L); // Inserting Double value in arr arr.add(6.0D); // Inserting Float value in arr arr.add(1.99F); // arr after all insertions: [\"GeeksForGeeks\", 14, // 1800L, 6.0D, 1.99F] System.out.print( \"ArrayList after all insertions: \"); display(arr); // Replacing element at index 0 (i.e. an String) // with an Integer type value 50 arr.set(0, 50); // Replacing element at index 1 (Integer value) // with a Double type value arr.set(1, 10.0D); // arr after modifications: [50, 10.0D, // 1800L, 6.0D, 1.99F] System.out.print(\"ArrayList after modifications: \"); display(arr); } // Function to display elements of the ArrayList public static void display(ArrayList<Object> arr) { for (int i = 0; i < arr.size(); i++) { System.out.print(arr.get(i) + \" \"); } System.out.println(); }}",
"e": 2617,
"s": 1181,
"text": null
},
{
"code": null,
"e": 2737,
"s": 2620,
"text": "ArrayList after all insertions: GeeksForGeeks 14 1800 6.0 1.99 \nArrayList after modifications: 50 10.0 1800 6.0 1.99"
},
{
"code": null,
"e": 2749,
"s": 2739,
"text": "ruhelaa48"
},
{
"code": null,
"e": 2764,
"s": 2749,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 2781,
"s": 2764,
"text": "Java-Collections"
},
{
"code": null,
"e": 2788,
"s": 2781,
"text": "Picked"
},
{
"code": null,
"e": 2793,
"s": 2788,
"text": "Java"
},
{
"code": null,
"e": 2807,
"s": 2793,
"text": "Java Programs"
},
{
"code": null,
"e": 2812,
"s": 2807,
"text": "Java"
},
{
"code": null,
"e": 2829,
"s": 2812,
"text": "Java-Collections"
}
] |
Find Maximum and Minimum of two numbers using Absolute function | 04 Dec, 2021
Given two numbers, the task is to print the maximum and minimum of the given numbers using Absolute function.Examples:
Input: 99, 18
Output: Maximum = 99
Minimum = 18
Input: -10, 20
Output: Maximum = 20
Minimum = -10
Input: -1, -5
Output: Maximum = -1
Minimum = -5
Approach: This problem can be solved by applying the concept of Absolute Function and BODMAS rule.
For Maximum:
[(x + y + abs(x - y)) / 2]
For Minimum:
[(x + y - abs(x - y)) / 2]
Let us consider two number x and y where x = 20, y = 70 respectively.For Maximum:
[(x + y + abs(x - y)) / 2]
=> [(20 + 70)+ abs(20-70)) / 2]
=> 140 / 2 = 70 [MAXIMUM]
For Minimum:
[(x + y - abs(x - y)) / 2]
=> [(20 + 70) - abs(20-70)) / 2]
=> 40 / 2 = 20 [MINIMUM]
C++
C
Java
C#
Python3
Javascript
// C++ program to find maximum and// minimum using Absolute function#include <bits/stdc++.h>using namespace std; // Function to return maximum// among the two numbersint maximum(int x, int y){ return ((x + y + abs(x - y)) / 2);} // Function to return minimum// among the two numbersint minimum(int x, int y){ return ((x + y - abs(x - y)) / 2);} // Driver codeint main(){ int x = 99, y = 18; // Displaying the maximum value cout <<"Maximum: " << maximum(x, y) << endl; // Displaying the minimum value cout << "Minimum: " << minimum(x, y) << endl; return 0;} // This code is contributed by SHUBHAMSINGH10
// C program to find maximum and// minimum using Absolute function #include <stdio.h>#include <stdlib.h> // Function to return maximum// among the two numbersint maximum(int x, int y){ return ((x + y + abs(x - y)) / 2);} // Function to return minimum// among the two numbersint minimum(int x, int y){ return ((x + y - abs(x - y)) / 2);} // Driver codevoid main(){ int x = 99, y = 18; // Displaying the maximum value printf("Maximum: %d\n", maximum(x, y)); // Displaying the minimum value printf("Minimum: %d\n", minimum(x, y));}
// Java program to find maximum and // minimum using Absolute function class GFG{ // Function to return maximum // among the two numbers static int maximum(int x, int y) { return ((x + y + Math.abs(x - y)) / 2); } // Function to return minimum // among the two numbers static int minimum(int x, int y) { return ((x + y - Math.abs(x - y)) / 2); } // Driver code public static void main (String[] args) { int x = 99, y = 18; // Displaying the maximum value System.out.println("Maximum: " + maximum(x, y)); // Displaying the minimum value System.out.println("Minimum: " + minimum(x, y)); } } // This code is contributed by AnkitRai01
// C# program to find maximum and // minimum using Absolute functionusing System; class GFG{ // Function to return maximum // among the two numbers static int maximum(int x, int y) { return ((x + y + Math.Abs(x - y)) / 2); } // Function to return minimum // among the two numbers static int minimum(int x, int y) { return ((x + y - Math.Abs(x - y)) / 2); } // Driver code public static void Main() { int x = 99, y = 18; // Displaying the maximum value Console.WriteLine("Maximum: " + maximum(x, y)); // Displaying the minimum value Console.WriteLine("Minimum: " + minimum(x, y)); } } // This code is contributed by AnkitRai01
# Python3 program to find maximum and# minimum using Absolute function # Function to return maximum# among the two numbersdef maximum(x, y): return ((x + y + abs(x - y)) // 2) # Function to return minimum# among the two numbersdef minimum(x, y): return ((x + y - abs(x - y)) // 2) # Driver codex = 99y = 18 # Displaying the maximum valueprint("Maximum:", maximum(x, y)) # Displaying the minimum valueprint("Minimum:", minimum(x, y)) # This code is contributed by mohit kumar 29
<script> // JavaScript program to find maximum and// minimum using Absolute function // Function to return maximum // among the two numbers function maximum(x,y) { return ((x + y + Math.abs(x - y)) / 2); } // Function to return minimum // among the two numbers function minimum(x,y) { return ((x + y - Math.abs(x - y)) / 2); } // Driver code let x = 99, y = 18; // Displaying the maximum value document.write("Maximum: " + maximum(x, y)+"<br>"); // Displaying the minimum value document.write("Minimum: " + minimum(x, y)); // This code is contributed by sravan kumar </script>
Maximum: 99
Minimum: 18
mohit kumar 29
ankthon
SHUBHAMSINGH10
sravankumar8128
Numbers
Technical Scripter 2019
Mathematical
School Programming
Technical Scripter
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2021"
},
{
"code": null,
"e": 149,
"s": 28,
"text": "Given two numbers, the task is to print the maximum and minimum of the given numbers using Absolute function.Examples: "
},
{
"code": null,
"e": 321,
"s": 149,
"text": "Input: 99, 18\nOutput: Maximum = 99\n Minimum = 18\n\nInput: -10, 20\nOutput: Maximum = 20\n Minimum = -10\n\nInput: -1, -5\nOutput: Maximum = -1\n Minimum = -5"
},
{
"code": null,
"e": 424,
"s": 323,
"text": "Approach: This problem can be solved by applying the concept of Absolute Function and BODMAS rule. "
},
{
"code": null,
"e": 439,
"s": 424,
"text": "For Maximum: "
},
{
"code": null,
"e": 467,
"s": 439,
"text": "[(x + y + abs(x - y)) / 2]\n"
},
{
"code": null,
"e": 482,
"s": 467,
"text": "For Minimum: "
},
{
"code": null,
"e": 509,
"s": 482,
"text": "[(x + y - abs(x - y)) / 2]"
},
{
"code": null,
"e": 593,
"s": 509,
"text": "Let us consider two number x and y where x = 20, y = 70 respectively.For Maximum: "
},
{
"code": null,
"e": 678,
"s": 593,
"text": "[(x + y + abs(x - y)) / 2]\n=> [(20 + 70)+ abs(20-70)) / 2]\n=> 140 / 2 = 70 [MAXIMUM]"
},
{
"code": null,
"e": 693,
"s": 678,
"text": "For Minimum: "
},
{
"code": null,
"e": 778,
"s": 693,
"text": "[(x + y - abs(x - y)) / 2]\n=> [(20 + 70) - abs(20-70)) / 2]\n=> 40 / 2 = 20 [MINIMUM]"
},
{
"code": null,
"e": 784,
"s": 780,
"text": "C++"
},
{
"code": null,
"e": 786,
"s": 784,
"text": "C"
},
{
"code": null,
"e": 791,
"s": 786,
"text": "Java"
},
{
"code": null,
"e": 794,
"s": 791,
"text": "C#"
},
{
"code": null,
"e": 802,
"s": 794,
"text": "Python3"
},
{
"code": null,
"e": 813,
"s": 802,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum and// minimum using Absolute function#include <bits/stdc++.h>using namespace std; // Function to return maximum// among the two numbersint maximum(int x, int y){ return ((x + y + abs(x - y)) / 2);} // Function to return minimum// among the two numbersint minimum(int x, int y){ return ((x + y - abs(x - y)) / 2);} // Driver codeint main(){ int x = 99, y = 18; // Displaying the maximum value cout <<\"Maximum: \" << maximum(x, y) << endl; // Displaying the minimum value cout << \"Minimum: \" << minimum(x, y) << endl; return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 1456,
"s": 813,
"text": null
},
{
"code": "// C program to find maximum and// minimum using Absolute function #include <stdio.h>#include <stdlib.h> // Function to return maximum// among the two numbersint maximum(int x, int y){ return ((x + y + abs(x - y)) / 2);} // Function to return minimum// among the two numbersint minimum(int x, int y){ return ((x + y - abs(x - y)) / 2);} // Driver codevoid main(){ int x = 99, y = 18; // Displaying the maximum value printf(\"Maximum: %d\\n\", maximum(x, y)); // Displaying the minimum value printf(\"Minimum: %d\\n\", minimum(x, y));}",
"e": 2022,
"s": 1456,
"text": null
},
{
"code": "// Java program to find maximum and // minimum using Absolute function class GFG{ // Function to return maximum // among the two numbers static int maximum(int x, int y) { return ((x + y + Math.abs(x - y)) / 2); } // Function to return minimum // among the two numbers static int minimum(int x, int y) { return ((x + y - Math.abs(x - y)) / 2); } // Driver code public static void main (String[] args) { int x = 99, y = 18; // Displaying the maximum value System.out.println(\"Maximum: \" + maximum(x, y)); // Displaying the minimum value System.out.println(\"Minimum: \" + minimum(x, y)); } } // This code is contributed by AnkitRai01",
"e": 2802,
"s": 2022,
"text": null
},
{
"code": "// C# program to find maximum and // minimum using Absolute functionusing System; class GFG{ // Function to return maximum // among the two numbers static int maximum(int x, int y) { return ((x + y + Math.Abs(x - y)) / 2); } // Function to return minimum // among the two numbers static int minimum(int x, int y) { return ((x + y - Math.Abs(x - y)) / 2); } // Driver code public static void Main() { int x = 99, y = 18; // Displaying the maximum value Console.WriteLine(\"Maximum: \" + maximum(x, y)); // Displaying the minimum value Console.WriteLine(\"Minimum: \" + minimum(x, y)); } } // This code is contributed by AnkitRai01",
"e": 3578,
"s": 2802,
"text": null
},
{
"code": "# Python3 program to find maximum and# minimum using Absolute function # Function to return maximum# among the two numbersdef maximum(x, y): return ((x + y + abs(x - y)) // 2) # Function to return minimum# among the two numbersdef minimum(x, y): return ((x + y - abs(x - y)) // 2) # Driver codex = 99y = 18 # Displaying the maximum valueprint(\"Maximum:\", maximum(x, y)) # Displaying the minimum valueprint(\"Minimum:\", minimum(x, y)) # This code is contributed by mohit kumar 29",
"e": 4076,
"s": 3578,
"text": null
},
{
"code": "<script> // JavaScript program to find maximum and// minimum using Absolute function // Function to return maximum // among the two numbers function maximum(x,y) { return ((x + y + Math.abs(x - y)) / 2); } // Function to return minimum // among the two numbers function minimum(x,y) { return ((x + y - Math.abs(x - y)) / 2); } // Driver code let x = 99, y = 18; // Displaying the maximum value document.write(\"Maximum: \" + maximum(x, y)+\"<br>\"); // Displaying the minimum value document.write(\"Minimum: \" + minimum(x, y)); // This code is contributed by sravan kumar </script>",
"e": 4790,
"s": 4076,
"text": null
},
{
"code": null,
"e": 4814,
"s": 4790,
"text": "Maximum: 99\nMinimum: 18"
},
{
"code": null,
"e": 4831,
"s": 4816,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 4839,
"s": 4831,
"text": "ankthon"
},
{
"code": null,
"e": 4854,
"s": 4839,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 4870,
"s": 4854,
"text": "sravankumar8128"
},
{
"code": null,
"e": 4878,
"s": 4870,
"text": "Numbers"
},
{
"code": null,
"e": 4902,
"s": 4878,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 4915,
"s": 4902,
"text": "Mathematical"
},
{
"code": null,
"e": 4934,
"s": 4915,
"text": "School Programming"
},
{
"code": null,
"e": 4953,
"s": 4934,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4966,
"s": 4953,
"text": "Mathematical"
},
{
"code": null,
"e": 4974,
"s": 4966,
"text": "Numbers"
}
] |
Minimum steps required to reach the end of a matrix | Set 2 | 13 May, 2021
Given a 2d-matrix mat[][] consisting of positive integers, the task is to find the minimum number of steps required to reach the end of the matrix. If we are at cell (i, j) we can go to cells (i, j + arr[i][j]) or (i + arr[i][j], j). We cannot go out of bounds. If no path exists then print -1.
Examples:
Input: mat[][] = { {2, 1, 2}, {1, 1, 1}, {1, 1, 1}} Output: 2 The path will be {0, 0} -> {0, 2} -> {2, 2} Thus, we are reaching there in two steps.Input: mat[][] = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1}} Output: 4
Approach: We have already discussed a dynamic programming-based approach for this problem in this article. This problem can also be solved using breadth first search (BFS).The algorithm is as follows:
Push (0, 0) in a queue.
Traverse (0, 0) i.e. push all the cells it can visit in the queue.
Repeat the above steps, i.e. traverse all the elements in the queue individually again if they have not been visited/traversed before.
Repeat till we don’t reach the cell (N-1, N-1).
The depth of this traversal will give the minimum steps required to reach the end.
Remember to mark a cell visited after it has been traversed. For this, we will use a 2D boolean array.
Why BFS works?
This whole scenario can be considered equivalent to a directed-graph where each cell is connected to at-most two more cells({i, j+arr[i][j]} and {i+arr[i][j], j}).
The graph is un-weighted. BFS can find the shortest path in such scenarios.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>#define n 3using namespace std; // Function to return the minimum steps// required to reach the end of the matrixint minSteps(int arr[][n]){ // Array to determine whether // a cell has been visited before bool v[n][n] = { 0 }; // Queue for bfs queue<pair<int, int> > q; // Initializing queue q.push({ 0, 0 }); // To store the depth of search int depth = 0; // BFS algorithm while (q.size() != 0) { // Current queue size int x = q.size(); while (x--) { // Top-most element of queue pair<int, int> y = q.front(); // To store index of cell // for simplicity int i = y.first, j = y.second; q.pop(); // Base case if (v[i][j]) continue; // If we reach (n-1, n-1) if (i == n - 1 && j == n - 1) return depth; // Marking the cell visited v[i][j] = 1; // Pushing the adjacent cells in the // queue that can be visited // from the current cell if (i + arr[i][j] < n) q.push({ i + arr[i][j], j }); if (j + arr[i][j] < n) q.push({ i, j + arr[i][j] }); } depth++; } return -1;} // Driver codeint main(){ int arr[n][n] = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; cout << minSteps(arr); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static int n= 3 ;static class Pair{ int first , second; Pair(int a, int b) { first = a; second = b; }} // Function to return the minimum steps// required to reach the end of the matrixstatic int minSteps(int arr[][]){ // Array to determine whether // a cell has been visited before boolean v[][] = new boolean[n][n]; // Queue for bfs Queue<Pair> q = new LinkedList<Pair>(); // Initializing queue q.add(new Pair( 0, 0 )); // To store the depth of search int depth = 0; // BFS algorithm while (q.size() != 0) { // Current queue size int x = q.size(); while (x-->0) { // Top-most element of queue Pair y = q.peek(); // To store index of cell // for simplicity int i = y.first, j = y.second; q.remove(); // Base case if (v[i][j]) continue; // If we reach (n-1, n-1) if (i == n - 1 && j == n - 1) return depth; // Marking the cell visited v[i][j] = true; // Pushing the adjacent cells in the // queue that can be visited // from the current cell if (i + arr[i][j] < n) q.add(new Pair( i + arr[i][j], j )); if (j + arr[i][j] < n) q.add(new Pair( i, j + arr[i][j] )); } depth++; } return -1;} // Driver codepublic static void main(String args[]){ int arr[][] = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; System.out.println(minSteps(arr));}} // This code is contributed by Arnab Kundu
# Python 3 implementation of the approachn = 3 # Function to return the minimum steps# required to reach the end of the matrixdef minSteps(arr): # Array to determine whether # a cell has been visited before v = [[0 for i in range(n)] for j in range(n)] # Queue for bfs q = [[0,0]] # To store the depth of search depth = 0 # BFS algorithm while (len(q) != 0): # Current queue size x = len(q) while (x > 0): # Top-most element of queue y = q[0] # To store index of cell # for simplicity i = y[0] j = y[1] q.remove(q[0]) x -= 1 # Base case if (v[i][j]): continue # If we reach (n-1, n-1) if (i == n - 1 and j == n - 1): return depth # Marking the cell visited v[i][j] = 1 # Pushing the adjacent cells in the # queue that can be visited # from the current cell if (i + arr[i][j] < n): q.append([i + arr[i][j], j]) if (j + arr[i][j] < n): q.append([i, j + arr[i][j]]) depth += 1 return -1 # Driver codeif __name__ == '__main__': arr = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] print(minSteps(arr)) # This code is contributed by# Surendra_Gangwar
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int n= 3 ;public class Pair{ public int first , second; public Pair(int a, int b) { first = a; second = b; }} // Function to return the minimum steps// required to reach the end of the matrixstatic int minSteps(int [,]arr){ // Array to determine whether // a cell has been visited before Boolean [,]v = new Boolean[n,n]; // Queue for bfs Queue<Pair> q = new Queue<Pair>(); // Initializing queue q.Enqueue(new Pair( 0, 0 )); // To store the depth of search int depth = 0; // BFS algorithm while (q.Count != 0) { // Current queue size int x = q.Count; while (x-->0) { // Top-most element of queue Pair y = q.Peek(); // To store index of cell // for simplicity int i = y.first, j = y.second; q.Dequeue(); // Base case if (v[i,j]) continue; // If we reach (n-1, n-1) if (i == n - 1 && j == n - 1) return depth; // Marking the cell visited v[i,j] = true; // Pushing the adjacent cells in the // queue that can be visited // from the current cell if (i + arr[i,j] < n) q.Enqueue(new Pair( i + arr[i,j], j )); if (j + arr[i,j] < n) q.Enqueue(new Pair( i, j + arr[i,j] )); } depth++; } return -1;} // Driver codepublic static void Main(){ int [,]arr = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; Console.WriteLine(minSteps(arr));}} // This code contributed by Rajput-Ji
<script> // Javascript implementation of the approachvar n = 3; // Function to return the minimum steps// required to reach the end of the matrixfunction minSteps(arr){ // Array to determine whether // a cell has been visited before var v = Array.from(Array(n), ()=> Array(n).fill(0)); // Queue for bfs var q = []; // Initializing queue q.push([0, 0 ]); // To store the depth of search var depth = 0; // BFS algorithm while (q.length != 0) { // Current queue size var x = q.length; while (x--) { // Top-most element of queue var y = q[0]; // To store index of cell // for simplicity var i = y[0], j = y[1]; q.shift(); // Base case if (v[i][j]) continue; // If we reach (n-1, n-1) if (i == n - 1 && j == n - 1) return depth; // Marking the cell visited v[i][j] = 1; // Pushing the adjacent cells in the // queue that can be visited // from the current cell if (i + arr[i][j] < n) q.push([ i + arr[i][j], j ]); if (j + arr[i][j] < n) q.push([i, j + arr[i][j] ]); } depth++; } return -1;} // Driver codevar arr = [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ];document.write( minSteps(arr)); </script>
4
Time Complexity: O(n2)
SURENDRA_GANGWAR
andrew1234
Rajput-Ji
itsok
BFS
Matrix
Queue
Searching
Searching
Matrix
Queue
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
Rotate a matrix by 90 degree in clockwise direction without using any extra space
The Celebrity Problem
Unique paths in a Grid with Obstacles
Inplace rotate square matrix by 90 degrees | Set 1
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue in Python
Queue Interface In Java
Introduction to Data Structures | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 349,
"s": 54,
"text": "Given a 2d-matrix mat[][] consisting of positive integers, the task is to find the minimum number of steps required to reach the end of the matrix. If we are at cell (i, j) we can go to cells (i, j + arr[i][j]) or (i + arr[i][j], j). We cannot go out of bounds. If no path exists then print -1."
},
{
"code": null,
"e": 361,
"s": 349,
"text": "Examples: "
},
{
"code": null,
"e": 572,
"s": 361,
"text": "Input: mat[][] = { {2, 1, 2}, {1, 1, 1}, {1, 1, 1}} Output: 2 The path will be {0, 0} -> {0, 2} -> {2, 2} Thus, we are reaching there in two steps.Input: mat[][] = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1}} Output: 4 "
},
{
"code": null,
"e": 775,
"s": 572,
"text": "Approach: We have already discussed a dynamic programming-based approach for this problem in this article. This problem can also be solved using breadth first search (BFS).The algorithm is as follows: "
},
{
"code": null,
"e": 799,
"s": 775,
"text": "Push (0, 0) in a queue."
},
{
"code": null,
"e": 866,
"s": 799,
"text": "Traverse (0, 0) i.e. push all the cells it can visit in the queue."
},
{
"code": null,
"e": 1001,
"s": 866,
"text": "Repeat the above steps, i.e. traverse all the elements in the queue individually again if they have not been visited/traversed before."
},
{
"code": null,
"e": 1049,
"s": 1001,
"text": "Repeat till we don’t reach the cell (N-1, N-1)."
},
{
"code": null,
"e": 1132,
"s": 1049,
"text": "The depth of this traversal will give the minimum steps required to reach the end."
},
{
"code": null,
"e": 1236,
"s": 1132,
"text": "Remember to mark a cell visited after it has been traversed. For this, we will use a 2D boolean array. "
},
{
"code": null,
"e": 1252,
"s": 1236,
"text": "Why BFS works? "
},
{
"code": null,
"e": 1416,
"s": 1252,
"text": "This whole scenario can be considered equivalent to a directed-graph where each cell is connected to at-most two more cells({i, j+arr[i][j]} and {i+arr[i][j], j})."
},
{
"code": null,
"e": 1492,
"s": 1416,
"text": "The graph is un-weighted. BFS can find the shortest path in such scenarios."
},
{
"code": null,
"e": 1545,
"s": 1492,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1549,
"s": 1545,
"text": "C++"
},
{
"code": null,
"e": 1554,
"s": 1549,
"text": "Java"
},
{
"code": null,
"e": 1562,
"s": 1554,
"text": "Python3"
},
{
"code": null,
"e": 1565,
"s": 1562,
"text": "C#"
},
{
"code": null,
"e": 1576,
"s": 1565,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>#define n 3using namespace std; // Function to return the minimum steps// required to reach the end of the matrixint minSteps(int arr[][n]){ // Array to determine whether // a cell has been visited before bool v[n][n] = { 0 }; // Queue for bfs queue<pair<int, int> > q; // Initializing queue q.push({ 0, 0 }); // To store the depth of search int depth = 0; // BFS algorithm while (q.size() != 0) { // Current queue size int x = q.size(); while (x--) { // Top-most element of queue pair<int, int> y = q.front(); // To store index of cell // for simplicity int i = y.first, j = y.second; q.pop(); // Base case if (v[i][j]) continue; // If we reach (n-1, n-1) if (i == n - 1 && j == n - 1) return depth; // Marking the cell visited v[i][j] = 1; // Pushing the adjacent cells in the // queue that can be visited // from the current cell if (i + arr[i][j] < n) q.push({ i + arr[i][j], j }); if (j + arr[i][j] < n) q.push({ i, j + arr[i][j] }); } depth++; } return -1;} // Driver codeint main(){ int arr[n][n] = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; cout << minSteps(arr); return 0;}",
"e": 3106,
"s": 1576,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static int n= 3 ;static class Pair{ int first , second; Pair(int a, int b) { first = a; second = b; }} // Function to return the minimum steps// required to reach the end of the matrixstatic int minSteps(int arr[][]){ // Array to determine whether // a cell has been visited before boolean v[][] = new boolean[n][n]; // Queue for bfs Queue<Pair> q = new LinkedList<Pair>(); // Initializing queue q.add(new Pair( 0, 0 )); // To store the depth of search int depth = 0; // BFS algorithm while (q.size() != 0) { // Current queue size int x = q.size(); while (x-->0) { // Top-most element of queue Pair y = q.peek(); // To store index of cell // for simplicity int i = y.first, j = y.second; q.remove(); // Base case if (v[i][j]) continue; // If we reach (n-1, n-1) if (i == n - 1 && j == n - 1) return depth; // Marking the cell visited v[i][j] = true; // Pushing the adjacent cells in the // queue that can be visited // from the current cell if (i + arr[i][j] < n) q.add(new Pair( i + arr[i][j], j )); if (j + arr[i][j] < n) q.add(new Pair( i, j + arr[i][j] )); } depth++; } return -1;} // Driver codepublic static void main(String args[]){ int arr[][] = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; System.out.println(minSteps(arr));}} // This code is contributed by Arnab Kundu",
"e": 4869,
"s": 3106,
"text": null
},
{
"code": "# Python 3 implementation of the approachn = 3 # Function to return the minimum steps# required to reach the end of the matrixdef minSteps(arr): # Array to determine whether # a cell has been visited before v = [[0 for i in range(n)] for j in range(n)] # Queue for bfs q = [[0,0]] # To store the depth of search depth = 0 # BFS algorithm while (len(q) != 0): # Current queue size x = len(q) while (x > 0): # Top-most element of queue y = q[0] # To store index of cell # for simplicity i = y[0] j = y[1] q.remove(q[0]) x -= 1 # Base case if (v[i][j]): continue # If we reach (n-1, n-1) if (i == n - 1 and j == n - 1): return depth # Marking the cell visited v[i][j] = 1 # Pushing the adjacent cells in the # queue that can be visited # from the current cell if (i + arr[i][j] < n): q.append([i + arr[i][j], j]) if (j + arr[i][j] < n): q.append([i, j + arr[i][j]]) depth += 1 return -1 # Driver codeif __name__ == '__main__': arr = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] print(minSteps(arr)) # This code is contributed by# Surendra_Gangwar",
"e": 6296,
"s": 4869,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int n= 3 ;public class Pair{ public int first , second; public Pair(int a, int b) { first = a; second = b; }} // Function to return the minimum steps// required to reach the end of the matrixstatic int minSteps(int [,]arr){ // Array to determine whether // a cell has been visited before Boolean [,]v = new Boolean[n,n]; // Queue for bfs Queue<Pair> q = new Queue<Pair>(); // Initializing queue q.Enqueue(new Pair( 0, 0 )); // To store the depth of search int depth = 0; // BFS algorithm while (q.Count != 0) { // Current queue size int x = q.Count; while (x-->0) { // Top-most element of queue Pair y = q.Peek(); // To store index of cell // for simplicity int i = y.first, j = y.second; q.Dequeue(); // Base case if (v[i,j]) continue; // If we reach (n-1, n-1) if (i == n - 1 && j == n - 1) return depth; // Marking the cell visited v[i,j] = true; // Pushing the adjacent cells in the // queue that can be visited // from the current cell if (i + arr[i,j] < n) q.Enqueue(new Pair( i + arr[i,j], j )); if (j + arr[i,j] < n) q.Enqueue(new Pair( i, j + arr[i,j] )); } depth++; } return -1;} // Driver codepublic static void Main(){ int [,]arr = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; Console.WriteLine(minSteps(arr));}} // This code contributed by Rajput-Ji",
"e": 8075,
"s": 6296,
"text": null
},
{
"code": "<script> // Javascript implementation of the approachvar n = 3; // Function to return the minimum steps// required to reach the end of the matrixfunction minSteps(arr){ // Array to determine whether // a cell has been visited before var v = Array.from(Array(n), ()=> Array(n).fill(0)); // Queue for bfs var q = []; // Initializing queue q.push([0, 0 ]); // To store the depth of search var depth = 0; // BFS algorithm while (q.length != 0) { // Current queue size var x = q.length; while (x--) { // Top-most element of queue var y = q[0]; // To store index of cell // for simplicity var i = y[0], j = y[1]; q.shift(); // Base case if (v[i][j]) continue; // If we reach (n-1, n-1) if (i == n - 1 && j == n - 1) return depth; // Marking the cell visited v[i][j] = 1; // Pushing the adjacent cells in the // queue that can be visited // from the current cell if (i + arr[i][j] < n) q.push([ i + arr[i][j], j ]); if (j + arr[i][j] < n) q.push([i, j + arr[i][j] ]); } depth++; } return -1;} // Driver codevar arr = [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ];document.write( minSteps(arr)); </script>",
"e": 9539,
"s": 8075,
"text": null
},
{
"code": null,
"e": 9541,
"s": 9539,
"text": "4"
},
{
"code": null,
"e": 9567,
"s": 9543,
"text": "Time Complexity: O(n2) "
},
{
"code": null,
"e": 9584,
"s": 9567,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 9595,
"s": 9584,
"text": "andrew1234"
},
{
"code": null,
"e": 9605,
"s": 9595,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9611,
"s": 9605,
"text": "itsok"
},
{
"code": null,
"e": 9615,
"s": 9611,
"text": "BFS"
},
{
"code": null,
"e": 9622,
"s": 9615,
"text": "Matrix"
},
{
"code": null,
"e": 9628,
"s": 9622,
"text": "Queue"
},
{
"code": null,
"e": 9638,
"s": 9628,
"text": "Searching"
},
{
"code": null,
"e": 9648,
"s": 9638,
"text": "Searching"
},
{
"code": null,
"e": 9655,
"s": 9648,
"text": "Matrix"
},
{
"code": null,
"e": 9661,
"s": 9655,
"text": "Queue"
},
{
"code": null,
"e": 9665,
"s": 9661,
"text": "BFS"
},
{
"code": null,
"e": 9763,
"s": 9665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9787,
"s": 9763,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 9869,
"s": 9787,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 9891,
"s": 9869,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 9929,
"s": 9891,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 9980,
"s": 9929,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 10020,
"s": 9980,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 10054,
"s": 10020,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 10070,
"s": 10054,
"text": "Queue in Python"
},
{
"code": null,
"e": 10094,
"s": 10070,
"text": "Queue Interface In Java"
}
] |
Window | Window.requestAnimationFrame() Method | 23 Oct, 2019
Nowadays, various web development technologies are introduced to create elegant web pages. While talking about elegant web pages, one of the most important things that come to mind is animation. There are many ways to generate them, modern CSS is one of them but JavaScript has always been a power-packed option to do so.
The requestAnimationFrame() is one of the methods present in JavaScript to powerfully incorporate amazing and simple animations within our project. Earlier methods like setTimeout() or setInterval() were used which was okay but they slow down the whole process. The main problem with them was of synchronization. The transition time was very slow and didn’t match with the user’s system perfectly.
Here, requestAnimationFrame() came into the picture. Basically, requestAnimationFrame() method easily syncs in with your browser timings and generate a call to perform the specific animation before the actual loading of the screen. Further, it also slows down its process when the animation is actually not in the use thus saving resources.
Syntax:
window.requestAnimationFrame( callback );
Parameter: This method accepts single parameter as mentioned above and described below:
callback: Unless you want the animation to stop, you should write the callback function so that it calls itself so that a request to the next frame is made. Callback function takes timestamp or simply a time value at which it should start executing.
Return Values: This method returns a non zero long integer value that acts as a unique identity for the animation entry in callback function.
Below examples illustrate the requestAnimationFrame() method in Web API:
Example 1:
<!DOCTYPE html><html><head> <title> Window.requestAnimationFrame() Method </title></head> <body> <div id="gfg"> <h1 style="color:green;">GeeksforGeeks</h1> <h4>Window.requestAnimation()</h4> </div> <script type="text/javascript"> // Setting the start point for animation var start = null; var element = document.getElementById('gfg'); function startAnim(timestamp) { // Timestamp is an integer that represents the number // of seconds elapsed since January 1 1970. if (!start) start = timestamp; // Setting the difference between timestamp // and the set start point as our progress var progress = timestamp - start; // Moving our div element element.style.transform = 'translateX(' + Math.min(progress / 10, 700) + 'px)'; window.requestAnimationFrame(startAnim); } window.requestAnimationFrame(startAnim); </script></body> </html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <style> div { position: absolute; left: 10px; top: 50px; padding: auto; color: white } h1 { color: green; } </style></head> <body> <div id="gfg"> <h1>GeeksforGeeks</h1></div> <center> <button onclick="start()">Start the animation</button> </center> <script type="text/javascript"> var x = document.getElementById("gfg"); // Initializing variables var requestId; var stopped; var starttime; function startAnim(time) { // Set left style to a function of time if it is not stopped if (!stopped) { // We use the difference between time returned // by Data.now() and the animation starttime x.style.left = ((Date.now() - starttime) / 10 % 700) + "px"; requestId = window.requestAnimationFrame(startAnim); } } function start() { // Return the number of milliseconds since 1970/01/01: starttime = Date.now(); // Starting point of animation requestId = window.requestAnimationFrame(startAnim); stopped = false; // Means animation will not stop } </script></body> </html>
Output:
Supported Browsers: The browsers supported by Window.requestAnimationFrame() Method are listed below:
Google Chrome 23.0
Internet Explorer 10.0
Firefox 11.0
Opera 10.0
Safari 6.1
Picked
Web-API
JavaScript
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": "\n23 Oct, 2019"
},
{
"code": null,
"e": 350,
"s": 28,
"text": "Nowadays, various web development technologies are introduced to create elegant web pages. While talking about elegant web pages, one of the most important things that come to mind is animation. There are many ways to generate them, modern CSS is one of them but JavaScript has always been a power-packed option to do so."
},
{
"code": null,
"e": 748,
"s": 350,
"text": "The requestAnimationFrame() is one of the methods present in JavaScript to powerfully incorporate amazing and simple animations within our project. Earlier methods like setTimeout() or setInterval() were used which was okay but they slow down the whole process. The main problem with them was of synchronization. The transition time was very slow and didn’t match with the user’s system perfectly."
},
{
"code": null,
"e": 1089,
"s": 748,
"text": "Here, requestAnimationFrame() came into the picture. Basically, requestAnimationFrame() method easily syncs in with your browser timings and generate a call to perform the specific animation before the actual loading of the screen. Further, it also slows down its process when the animation is actually not in the use thus saving resources."
},
{
"code": null,
"e": 1097,
"s": 1089,
"text": "Syntax:"
},
{
"code": null,
"e": 1139,
"s": 1097,
"text": "window.requestAnimationFrame( callback );"
},
{
"code": null,
"e": 1227,
"s": 1139,
"text": "Parameter: This method accepts single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 1477,
"s": 1227,
"text": "callback: Unless you want the animation to stop, you should write the callback function so that it calls itself so that a request to the next frame is made. Callback function takes timestamp or simply a time value at which it should start executing."
},
{
"code": null,
"e": 1619,
"s": 1477,
"text": "Return Values: This method returns a non zero long integer value that acts as a unique identity for the animation entry in callback function."
},
{
"code": null,
"e": 1692,
"s": 1619,
"text": "Below examples illustrate the requestAnimationFrame() method in Web API:"
},
{
"code": null,
"e": 1703,
"s": 1692,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html><head> <title> Window.requestAnimationFrame() Method </title></head> <body> <div id=\"gfg\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h4>Window.requestAnimation()</h4> </div> <script type=\"text/javascript\"> // Setting the start point for animation var start = null; var element = document.getElementById('gfg'); function startAnim(timestamp) { // Timestamp is an integer that represents the number // of seconds elapsed since January 1 1970. if (!start) start = timestamp; // Setting the difference between timestamp // and the set start point as our progress var progress = timestamp - start; // Moving our div element element.style.transform = 'translateX(' + Math.min(progress / 10, 700) + 'px)'; window.requestAnimationFrame(startAnim); } window.requestAnimationFrame(startAnim); </script></body> </html> ",
"e": 2766,
"s": 1703,
"text": null
},
{
"code": null,
"e": 2774,
"s": 2766,
"text": "Output:"
},
{
"code": null,
"e": 2785,
"s": 2774,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <style> div { position: absolute; left: 10px; top: 50px; padding: auto; color: white } h1 { color: green; } </style></head> <body> <div id=\"gfg\"> <h1>GeeksforGeeks</h1></div> <center> <button onclick=\"start()\">Start the animation</button> </center> <script type=\"text/javascript\"> var x = document.getElementById(\"gfg\"); // Initializing variables var requestId; var stopped; var starttime; function startAnim(time) { // Set left style to a function of time if it is not stopped if (!stopped) { // We use the difference between time returned // by Data.now() and the animation starttime x.style.left = ((Date.now() - starttime) / 10 % 700) + \"px\"; requestId = window.requestAnimationFrame(startAnim); } } function start() { // Return the number of milliseconds since 1970/01/01: starttime = Date.now(); // Starting point of animation requestId = window.requestAnimationFrame(startAnim); stopped = false; // Means animation will not stop } </script></body> </html>",
"e": 4137,
"s": 2785,
"text": null
},
{
"code": null,
"e": 4145,
"s": 4137,
"text": "Output:"
},
{
"code": null,
"e": 4247,
"s": 4145,
"text": "Supported Browsers: The browsers supported by Window.requestAnimationFrame() Method are listed below:"
},
{
"code": null,
"e": 4266,
"s": 4247,
"text": "Google Chrome 23.0"
},
{
"code": null,
"e": 4289,
"s": 4266,
"text": "Internet Explorer 10.0"
},
{
"code": null,
"e": 4302,
"s": 4289,
"text": "Firefox 11.0"
},
{
"code": null,
"e": 4313,
"s": 4302,
"text": "Opera 10.0"
},
{
"code": null,
"e": 4324,
"s": 4313,
"text": "Safari 6.1"
},
{
"code": null,
"e": 4331,
"s": 4324,
"text": "Picked"
},
{
"code": null,
"e": 4339,
"s": 4331,
"text": "Web-API"
},
{
"code": null,
"e": 4350,
"s": 4339,
"text": "JavaScript"
},
{
"code": null,
"e": 4367,
"s": 4350,
"text": "Web Technologies"
}
] |
R - Break Statement | The break statement in R programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
It can be used to terminate a case in the switch statement (covered in the next chapter).
The basic syntax for creating a break statement in R is −
break
v <- c("Hello","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt + 1
if(cnt > 5) {
break
}
}
When the above code is compiled and executed, it produces the following result −
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2479,
"s": 2402,
"text": "The break statement in R programming language has the following two usages −"
},
{
"code": null,
"e": 2639,
"s": 2479,
"text": "When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 2799,
"s": 2639,
"text": "When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 2889,
"s": 2799,
"text": "It can be used to terminate a case in the switch statement (covered in the next chapter)."
},
{
"code": null,
"e": 2979,
"s": 2889,
"text": "It can be used to terminate a case in the switch statement (covered in the next chapter)."
},
{
"code": null,
"e": 3037,
"s": 2979,
"text": "The basic syntax for creating a break statement in R is −"
},
{
"code": null,
"e": 3044,
"s": 3037,
"text": "break\n"
},
{
"code": null,
"e": 3154,
"s": 3044,
"text": "v <- c(\"Hello\",\"loop\")\ncnt <- 2\n\nrepeat {\n print(v)\n cnt <- cnt + 1\n\t\n if(cnt > 5) {\n break\n }\n}"
},
{
"code": null,
"e": 3235,
"s": 3154,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3316,
"s": 3235,
"text": "[1] \"Hello\" \"loop\" \n[1] \"Hello\" \"loop\" \n[1] \"Hello\" \"loop\" \n[1] \"Hello\" \"loop\" \n"
},
{
"code": null,
"e": 3349,
"s": 3316,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3364,
"s": 3349,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3399,
"s": 3364,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3414,
"s": 3399,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3449,
"s": 3414,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3464,
"s": 3449,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3497,
"s": 3464,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3511,
"s": 3497,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3546,
"s": 3511,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3561,
"s": 3546,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3596,
"s": 3561,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3610,
"s": 3596,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3617,
"s": 3610,
"text": " Print"
},
{
"code": null,
"e": 3628,
"s": 3617,
"text": " Add Notes"
}
] |
numpy.hstack() in Python - GeeksforGeeks | 06 Jan, 2019
numpy.hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array.
Syntax : numpy.hstack(tup)
Parameters :tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the second axis.
Return : [stacked ndarray] The stacked array of the input arrays.
Code #1 :
# Python program explaining# hstack() function import numpy as geek # input arrayin_arr1 = geek.array([ 1, 2, 3] )print ("1st Input array : \n", in_arr1) in_arr2 = geek.array([ 4, 5, 6] )print ("2nd Input array : \n", in_arr2) # Stacking the two arrays horizontallyout_arr = geek.hstack((in_arr1, in_arr2))print ("Output horizontally stacked array:\n ", out_arr)
1st Input array :
[1 2 3]
2nd Input array :
[4 5 6]
Output horizontally stacked array:
[1 2 3 4 5 6]
Code #2 :
# Python program explaining# hstack() function import numpy as geek # input arrayin_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )print ("1st Input array : \n", in_arr1) in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )print ("2nd Input array : \n", in_arr2) # Stacking the two arrays horizontallyout_arr = geek.hstack((in_arr1, in_arr2))print ("Output stacked array :\n ", out_arr)
1st Input array :
[[ 1 2 3]
[-1 -2 -3]]
2nd Input array :
[[ 4 5 6]
[-4 -5 -6]]
Output stacked array :
[[ 1 2 3 4 5 6]
[-1 -2 -3 -4 -5 -6]]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python | [
{
"code": null,
"e": 24468,
"s": 24440,
"text": "\n06 Jan, 2019"
},
{
"code": null,
"e": 24594,
"s": 24468,
"text": "numpy.hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array."
},
{
"code": null,
"e": 24621,
"s": 24594,
"text": "Syntax : numpy.hstack(tup)"
},
{
"code": null,
"e": 24768,
"s": 24621,
"text": "Parameters :tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the second axis."
},
{
"code": null,
"e": 24834,
"s": 24768,
"text": "Return : [stacked ndarray] The stacked array of the input arrays."
},
{
"code": null,
"e": 24844,
"s": 24834,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# hstack() function import numpy as geek # input arrayin_arr1 = geek.array([ 1, 2, 3] )print (\"1st Input array : \\n\", in_arr1) in_arr2 = geek.array([ 4, 5, 6] )print (\"2nd Input array : \\n\", in_arr2) # Stacking the two arrays horizontallyout_arr = geek.hstack((in_arr1, in_arr2))print (\"Output horizontally stacked array:\\n \", out_arr)",
"e": 25213,
"s": 24844,
"text": null
},
{
"code": null,
"e": 25321,
"s": 25213,
"text": "1st Input array : \n [1 2 3]\n2nd Input array : \n [4 5 6]\nOutput horizontally stacked array:\n [1 2 3 4 5 6]\n"
},
{
"code": null,
"e": 25332,
"s": 25321,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# hstack() function import numpy as geek # input arrayin_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )print (\"1st Input array : \\n\", in_arr1) in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )print (\"2nd Input array : \\n\", in_arr2) # Stacking the two arrays horizontallyout_arr = geek.hstack((in_arr1, in_arr2))print (\"Output stacked array :\\n \", out_arr)",
"e": 25723,
"s": 25332,
"text": null
},
{
"code": null,
"e": 25882,
"s": 25723,
"text": "1st Input array : \n [[ 1 2 3]\n [-1 -2 -3]]\n2nd Input array : \n [[ 4 5 6]\n [-4 -5 -6]]\nOutput stacked array :\n [[ 1 2 3 4 5 6]\n [-1 -2 -3 -4 -5 -6]]\n"
},
{
"code": null,
"e": 25913,
"s": 25882,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 25926,
"s": 25913,
"text": "Python-numpy"
},
{
"code": null,
"e": 25933,
"s": 25926,
"text": "Python"
},
{
"code": null,
"e": 26031,
"s": 25933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26040,
"s": 26031,
"text": "Comments"
},
{
"code": null,
"e": 26053,
"s": 26040,
"text": "Old Comments"
},
{
"code": null,
"e": 26071,
"s": 26053,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26106,
"s": 26071,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26128,
"s": 26106,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26160,
"s": 26128,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26202,
"s": 26160,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26246,
"s": 26202,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26271,
"s": 26246,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26308,
"s": 26271,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26364,
"s": 26308,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Retrieve MIN and MAX date in a single MySQL query from a column with date values | For this, you can use aggregate function MIN() and MAX(). Let us first create a table −
mysql> create table DemoTable(AdmissionDate date);
Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-01-21');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('2018-12-31');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('2016-11-01');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('2019-04-11');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2016-02-01');
Query OK, 1 row affected (0.28 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------+
| AdmissionDate |
+---------------+
| 2019-01-21 |
| 2018-12-31 |
| 2016-11-01 |
| 2019-04-11 |
| 2016-02-01 |
+---------------+
5 rows in set (0.00 sec)
Following is the query to retrieve MIN and MAX date in a single query −
mysql> select MIN(AdmissionDate) AS MinDate,MAX(AdmissionDate) AS MaxDate from DemoTable;
This will produce the following output −
+------------+------------+
| MinDate | MaxDate |
+------------+------------+
| 2016-02-01 | 2019-04-11 |
+------------+------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "For this, you can use aggregate function MIN() and MAX(). Let us first create a table −"
},
{
"code": null,
"e": 1238,
"s": 1150,
"text": "mysql> create table DemoTable(AdmissionDate date);\nQuery OK, 0 rows affected (0.76 sec)"
},
{
"code": null,
"e": 1294,
"s": 1238,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1729,
"s": 1294,
"text": "mysql> insert into DemoTable values('2019-01-21');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('2018-12-31');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values('2016-11-01');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('2019-04-11');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('2016-02-01');\nQuery OK, 1 row affected (0.28 sec)"
},
{
"code": null,
"e": 1789,
"s": 1729,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1820,
"s": 1789,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1861,
"s": 1820,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2048,
"s": 1861,
"text": "+---------------+\n| AdmissionDate |\n+---------------+\n| 2019-01-21 |\n| 2018-12-31 |\n| 2016-11-01 |\n| 2019-04-11 |\n| 2016-02-01 |\n+---------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2120,
"s": 2048,
"text": "Following is the query to retrieve MIN and MAX date in a single query −"
},
{
"code": null,
"e": 2210,
"s": 2120,
"text": "mysql> select MIN(AdmissionDate) AS MinDate,MAX(AdmissionDate) AS MaxDate from DemoTable;"
},
{
"code": null,
"e": 2251,
"s": 2210,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2415,
"s": 2251,
"text": "+------------+------------+\n| MinDate | MaxDate |\n+------------+------------+\n| 2016-02-01 | 2019-04-11 |\n+------------+------------+\n1 row in set (0.00 sec)"
}
] |
Write a program in JavaScript to check if two strings are anagrams of each other or not | Given two strings ‘a’ and string ‘b’, we have to check if they are anagrams of each other or not and return True/False. For example,
Input-1 −
String a= “india”
String b= “nidia”
Output −
True
Explanation − Since the given string ‘b’ contains all the characters in the string ‘a’ thus we will return True.
Input-2 −
String a= “hackathon”
String b= “achcthoon”
Output −
False
Explanation − Since the given string ‘b’ doesn’t have all the characters as string ‘a’ have thus we will return False.
In the given strings ‘a’ and ‘b’, we will check if they are of the same length and then we will sort the strings. If both the strings are equal, then return “True”; if not, then print “False”.
Take Input two strings ‘a’ and ‘b’
Take Input two strings ‘a’ and ‘b’
A function checkStringAnagrams(string a, string b) which will return true if they are anagram of each other otherwise false.
A function checkStringAnagrams(string a, string b) which will return true if they are anagram of each other otherwise false.
Find the length of both strings and check if they are the same.
Find the length of both strings and check if they are the same.
Now sort both strings in lexicographically order and check if they are equal or not.
Now sort both strings in lexicographically order and check if they are equal or not.
Return true or false accordingly.
Return true or false accordingly.
function checkStringsAnagram(a, b) {
let len1 = a.length;
let len2 = b.length;
if(len1 !== len2){
console.log('Invalid Input');
return
}
let str1 = a.split('').sort().join('');
let str2 = b.split('').sort().join('');
if(str1 === str2){
console.log("True");
} else {
console.log("False");
}
}
checkStringsAnagram("indian","ndiani")
Running the above code will generate the output as,
True
Since the string ‘indian’ has the same set of characters as in the other string ‘ndiani’, both are anagrams of each other, and hence, and we will return True. | [
{
"code": null,
"e": 1195,
"s": 1062,
"text": "Given two strings ‘a’ and string ‘b’, we have to check if they are anagrams of each other or not and return True/False. For example,"
},
{
"code": null,
"e": 1205,
"s": 1195,
"text": "Input-1 −"
},
{
"code": null,
"e": 1241,
"s": 1205,
"text": "String a= “india”\nString b= “nidia”"
},
{
"code": null,
"e": 1250,
"s": 1241,
"text": "Output −"
},
{
"code": null,
"e": 1255,
"s": 1250,
"text": "True"
},
{
"code": null,
"e": 1368,
"s": 1255,
"text": "Explanation − Since the given string ‘b’ contains all the characters in the string ‘a’ thus we will return True."
},
{
"code": null,
"e": 1378,
"s": 1368,
"text": "Input-2 −"
},
{
"code": null,
"e": 1422,
"s": 1378,
"text": "String a= “hackathon”\nString b= “achcthoon”"
},
{
"code": null,
"e": 1431,
"s": 1422,
"text": "Output −"
},
{
"code": null,
"e": 1437,
"s": 1431,
"text": "False"
},
{
"code": null,
"e": 1556,
"s": 1437,
"text": "Explanation − Since the given string ‘b’ doesn’t have all the characters as string ‘a’ have thus we will return False."
},
{
"code": null,
"e": 1749,
"s": 1556,
"text": "In the given strings ‘a’ and ‘b’, we will check if they are of the same length and then we will sort the strings. If both the strings are equal, then return “True”; if not, then print “False”."
},
{
"code": null,
"e": 1784,
"s": 1749,
"text": "Take Input two strings ‘a’ and ‘b’"
},
{
"code": null,
"e": 1819,
"s": 1784,
"text": "Take Input two strings ‘a’ and ‘b’"
},
{
"code": null,
"e": 1944,
"s": 1819,
"text": "A function checkStringAnagrams(string a, string b) which will return true if they are anagram of each other otherwise false."
},
{
"code": null,
"e": 2069,
"s": 1944,
"text": "A function checkStringAnagrams(string a, string b) which will return true if they are anagram of each other otherwise false."
},
{
"code": null,
"e": 2133,
"s": 2069,
"text": "Find the length of both strings and check if they are the same."
},
{
"code": null,
"e": 2197,
"s": 2133,
"text": "Find the length of both strings and check if they are the same."
},
{
"code": null,
"e": 2282,
"s": 2197,
"text": "Now sort both strings in lexicographically order and check if they are equal or not."
},
{
"code": null,
"e": 2367,
"s": 2282,
"text": "Now sort both strings in lexicographically order and check if they are equal or not."
},
{
"code": null,
"e": 2401,
"s": 2367,
"text": "Return true or false accordingly."
},
{
"code": null,
"e": 2435,
"s": 2401,
"text": "Return true or false accordingly."
},
{
"code": null,
"e": 2818,
"s": 2435,
"text": "function checkStringsAnagram(a, b) {\n let len1 = a.length;\n let len2 = b.length;\n if(len1 !== len2){\n console.log('Invalid Input');\n return\n }\n let str1 = a.split('').sort().join('');\n let str2 = b.split('').sort().join('');\n if(str1 === str2){\n console.log(\"True\");\n } else { \n console.log(\"False\");\n }\n}\ncheckStringsAnagram(\"indian\",\"ndiani\")"
},
{
"code": null,
"e": 2870,
"s": 2818,
"text": "Running the above code will generate the output as,"
},
{
"code": null,
"e": 2875,
"s": 2870,
"text": "True"
},
{
"code": null,
"e": 3034,
"s": 2875,
"text": "Since the string ‘indian’ has the same set of characters as in the other string ‘ndiani’, both are anagrams of each other, and hence, and we will return True."
}
] |
HTML5 Canvas to PNG File | To convert HTML5 canvas to PNG, follow the below-given steps −
You need to add the generated data URL to the href attribute of an <a> tag.
Dialog for base64 image −
<img src="data:image/png;base64,iOBVRw0KGgoAAAANSUhEUg...." class="image" />
Add a filename −
<a download="newimg.png" href="...">
Now define http headers −
headers=Content-Disposition: attachment; filename=newimg.png
To deal with the RAM of the web browser and make its utilization less −
// generated the data URL dynamically
function myCanvas() {
var d = canvas.toDataURL('image/png');
this.href = d;
};
d.addEventListener('click', myCanvas, false); | [
{
"code": null,
"e": 1125,
"s": 1062,
"text": "To convert HTML5 canvas to PNG, follow the below-given steps −"
},
{
"code": null,
"e": 1201,
"s": 1125,
"text": "You need to add the generated data URL to the href attribute of an <a> tag."
},
{
"code": null,
"e": 1227,
"s": 1201,
"text": "Dialog for base64 image −"
},
{
"code": null,
"e": 1304,
"s": 1227,
"text": "<img src=\"data:image/png;base64,iOBVRw0KGgoAAAANSUhEUg....\" class=\"image\" />"
},
{
"code": null,
"e": 1321,
"s": 1304,
"text": "Add a filename −"
},
{
"code": null,
"e": 1358,
"s": 1321,
"text": "<a download=\"newimg.png\" href=\"...\">"
},
{
"code": null,
"e": 1384,
"s": 1358,
"text": "Now define http headers −"
},
{
"code": null,
"e": 1445,
"s": 1384,
"text": "headers=Content-Disposition: attachment; filename=newimg.png"
},
{
"code": null,
"e": 1517,
"s": 1445,
"text": "To deal with the RAM of the web browser and make its utilization less −"
},
{
"code": null,
"e": 1686,
"s": 1517,
"text": "// generated the data URL dynamically\nfunction myCanvas() {\n var d = canvas.toDataURL('image/png');\n this.href = d;\n};\nd.addEventListener('click', myCanvas, false);"
}
] |
How to create Buttons in a game using PyGame? - GeeksforGeeks | 08 May, 2020
Pygame is a Python library that can be used specifically to design and build games. Pygame only supports 2D games that are build using different shapes/images called sprites. Pygame is not particularly best for designing games as it is very complex to use and lacks a proper GUI like unity gaming engine but it definitely builds logic for further larger projects.
Before initializing pygame library we need to install it. This library can be installed into the system by using pip tool that is provided by Python for its library installation. Pygame can be installed by writing these lines into the terminal.
pip install pygame
A game must have interactable buttons that can control different events in the game to make the game more controlled and to add a proper GUI in it. These can be created in pygame by creating a rectangle onto the screen and then superimposing the indicating text on it. For this, we will be using various functions like draw.rect(), screen.blit() etc. To add more liveliness to it we can change the color of the button as the mouse has hovered on it.
This can be done by using a function that updates the x and y position of the mouse pointer and storing it as a tuple in a variable. Then we can set the boundaries of the rectangle into respective variables and check if the mouse is in those boundaries if so the color of the block will be changed to lighter shade to indicate that the button is interactable.
Below is the implementation.
import pygameimport sys # initializing the constructorpygame.init() # screen resolutionres = (720,720) # opens up a windowscreen = pygame.display.set_mode(res) # white colorcolor = (255,255,255) # light shade of the buttoncolor_light = (170,170,170) # dark shade of the buttoncolor_dark = (100,100,100) # stores the width of the# screen into a variablewidth = screen.get_width() # stores the height of the# screen into a variableheight = screen.get_height() # defining a fontsmallfont = pygame.font.SysFont('Corbel',35) # rendering a text written in# this fonttext = smallfont.render('quit' , True , color) while True: for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() #checks if a mouse is clicked if ev.type == pygame.MOUSEBUTTONDOWN: #if the mouse is clicked on the # button the game is terminated if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.quit() # fills the screen with a color screen.fill((60,25,60)) # stores the (x,y) coordinates into # the variable as a tuple mouse = pygame.mouse.get_pos() # if mouse is hovered on a button it # changes to lighter shade if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.draw.rect(screen,color_light,[width/2,height/2,140,40]) else: pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40]) # superimposing the text onto our button screen.blit(text , (width/2+50,height/2)) # updates the frames of the game pygame.display.update()
Output:
Python-PyGame
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 24065,
"s": 24037,
"text": "\n08 May, 2020"
},
{
"code": null,
"e": 24429,
"s": 24065,
"text": "Pygame is a Python library that can be used specifically to design and build games. Pygame only supports 2D games that are build using different shapes/images called sprites. Pygame is not particularly best for designing games as it is very complex to use and lacks a proper GUI like unity gaming engine but it definitely builds logic for further larger projects."
},
{
"code": null,
"e": 24674,
"s": 24429,
"text": "Before initializing pygame library we need to install it. This library can be installed into the system by using pip tool that is provided by Python for its library installation. Pygame can be installed by writing these lines into the terminal."
},
{
"code": null,
"e": 24693,
"s": 24674,
"text": "pip install pygame"
},
{
"code": null,
"e": 25143,
"s": 24693,
"text": "A game must have interactable buttons that can control different events in the game to make the game more controlled and to add a proper GUI in it. These can be created in pygame by creating a rectangle onto the screen and then superimposing the indicating text on it. For this, we will be using various functions like draw.rect(), screen.blit() etc. To add more liveliness to it we can change the color of the button as the mouse has hovered on it."
},
{
"code": null,
"e": 25503,
"s": 25143,
"text": "This can be done by using a function that updates the x and y position of the mouse pointer and storing it as a tuple in a variable. Then we can set the boundaries of the rectangle into respective variables and check if the mouse is in those boundaries if so the color of the block will be changed to lighter shade to indicate that the button is interactable."
},
{
"code": null,
"e": 25532,
"s": 25503,
"text": "Below is the implementation."
},
{
"code": "import pygameimport sys # initializing the constructorpygame.init() # screen resolutionres = (720,720) # opens up a windowscreen = pygame.display.set_mode(res) # white colorcolor = (255,255,255) # light shade of the buttoncolor_light = (170,170,170) # dark shade of the buttoncolor_dark = (100,100,100) # stores the width of the# screen into a variablewidth = screen.get_width() # stores the height of the# screen into a variableheight = screen.get_height() # defining a fontsmallfont = pygame.font.SysFont('Corbel',35) # rendering a text written in# this fonttext = smallfont.render('quit' , True , color) while True: for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() #checks if a mouse is clicked if ev.type == pygame.MOUSEBUTTONDOWN: #if the mouse is clicked on the # button the game is terminated if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.quit() # fills the screen with a color screen.fill((60,25,60)) # stores the (x,y) coordinates into # the variable as a tuple mouse = pygame.mouse.get_pos() # if mouse is hovered on a button it # changes to lighter shade if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.draw.rect(screen,color_light,[width/2,height/2,140,40]) else: pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40]) # superimposing the text onto our button screen.blit(text , (width/2+50,height/2)) # updates the frames of the game pygame.display.update()",
"e": 27256,
"s": 25532,
"text": null
},
{
"code": null,
"e": 27264,
"s": 27256,
"text": "Output:"
},
{
"code": null,
"e": 27278,
"s": 27264,
"text": "Python-PyGame"
},
{
"code": null,
"e": 27285,
"s": 27278,
"text": "Python"
},
{
"code": null,
"e": 27301,
"s": 27285,
"text": "Write From Home"
},
{
"code": null,
"e": 27399,
"s": 27301,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27408,
"s": 27399,
"text": "Comments"
},
{
"code": null,
"e": 27421,
"s": 27408,
"text": "Old Comments"
},
{
"code": null,
"e": 27439,
"s": 27421,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27474,
"s": 27439,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27496,
"s": 27474,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27528,
"s": 27496,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27558,
"s": 27528,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27594,
"s": 27558,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27630,
"s": 27594,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 27646,
"s": 27630,
"text": "Python infinity"
},
{
"code": null,
"e": 27707,
"s": 27646,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
How to clear an entire Treeview with Tkinter? | Tkinter Treeview widgets are used to display the hierarchy of the items in the form of a list. It generally looks like the file explorer in Windows or Mac OS.
Let us suppose we have created a list of items using treeview widget and we want to clear the entire treeview, then we can use the delete() function. The function can be invoked while iterating over the treeview items.
In this example, we will create a treeview for the Programming Language and will clear the list of items using delete() operation.
#Import the required library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
win.title("Application to represent the Programming Languages ")
#Set the geometry
win.geometry("600x200")
#Create a label
ttk.Label(win, text ="Treeview(hierarchical)").pack()
#Treeview List Instantiation
treeview = ttk.Treeview(win)
treeview.pack()
treeview.insert('', '0', 'i1', text ='Language')
treeview.insert('', '1', 'i2', text ='FrontEnd')
treeview.insert('', '2', 'i3', text ='Backend')
treeview.insert('i2', 'end', 'HTML', text ='RUBY')
treeview.insert('i2', 'end', 'Python', text ='JavaScript')
treeview.insert('i3', 'end', 'C++', text ='Java')
treeview.insert('i3', 'end', 'RUST', text ='Python')
treeview.move('i2', 'i1', 'end')
treeview.move('i3', 'i1', 'end')
treeview.move('i2', 'i1', 'end')
win.mainloop()
Running the above code will display a window that contains a treeview hierarchy of Programming languages categorized for FrontEnd and Backend.
Now, adding the following code before the mainloop will remove and clear the whole treeview list.
#Clear the treeview list items
for item in treeview.get_children():
treeview.delete(item)
After invoking the function, it will clear the whole treeview list items from the window.
After clearing the treeview, it will display an empty treeview list. | [
{
"code": null,
"e": 1221,
"s": 1062,
"text": "Tkinter Treeview widgets are used to display the hierarchy of the items in the form of a list. It generally looks like the file explorer in Windows or Mac OS."
},
{
"code": null,
"e": 1440,
"s": 1221,
"text": "Let us suppose we have created a list of items using treeview widget and we want to clear the entire treeview, then we can use the delete() function. The function can be invoked while iterating over the treeview items."
},
{
"code": null,
"e": 1571,
"s": 1440,
"text": "In this example, we will create a treeview for the Programming Language and will clear the list of items using delete() operation."
},
{
"code": null,
"e": 2423,
"s": 1571,
"text": "#Import the required library\nfrom tkinter import *\nfrom tkinter import ttk\n\n#Create an instance of tkinter frame\nwin = Tk()\nwin.title(\"Application to represent the Programming Languages \")\n\n#Set the geometry\nwin.geometry(\"600x200\")\n\n#Create a label\nttk.Label(win, text =\"Treeview(hierarchical)\").pack()\n\n#Treeview List Instantiation\ntreeview = ttk.Treeview(win)\ntreeview.pack()\ntreeview.insert('', '0', 'i1', text ='Language')\ntreeview.insert('', '1', 'i2', text ='FrontEnd')\ntreeview.insert('', '2', 'i3', text ='Backend')\ntreeview.insert('i2', 'end', 'HTML', text ='RUBY')\ntreeview.insert('i2', 'end', 'Python', text ='JavaScript')\ntreeview.insert('i3', 'end', 'C++', text ='Java')\ntreeview.insert('i3', 'end', 'RUST', text ='Python')\ntreeview.move('i2', 'i1', 'end')\ntreeview.move('i3', 'i1', 'end')\ntreeview.move('i2', 'i1', 'end')\n\nwin.mainloop()"
},
{
"code": null,
"e": 2566,
"s": 2423,
"text": "Running the above code will display a window that contains a treeview hierarchy of Programming languages categorized for FrontEnd and Backend."
},
{
"code": null,
"e": 2664,
"s": 2566,
"text": "Now, adding the following code before the mainloop will remove and clear the whole treeview list."
},
{
"code": null,
"e": 2757,
"s": 2664,
"text": "#Clear the treeview list items\nfor item in treeview.get_children():\n treeview.delete(item)"
},
{
"code": null,
"e": 2847,
"s": 2757,
"text": "After invoking the function, it will clear the whole treeview list items from the window."
},
{
"code": null,
"e": 2916,
"s": 2847,
"text": "After clearing the treeview, it will display an empty treeview list."
}
] |
Doing and reporting your first ANOVA and ANCOVA in R | by Matthieu Renard | Towards Data Science | Analysis of Variance, or ANOVA, is a frequently-used and fundamental statistical test in many sciences. In its most common form, it analyzes how much of the variance of the dependent variable can be attributed to the independent variable(s) in the model. It is most often used to analyze the impact of a categorical independent variable (e.g., experimental conditions, dog breeds, flower species, etc.) on an interval dependent variable. At its core, an ANOVA will provide much of the same information provided in a simple linear regression (i.e., OLS). However, an ANOVA can be seen as an alternative interface through which this information can be accessed. Different scientific domains might have different preferences, which generally imply which test you should be using.
An Analysis of Covariance, or ANCOVA, denotes an ANOVA with more than one independent variable. Imagine you would like to analyze the impact of the dog’s breed on the dog’s weight, controlling for the dog’s age. Without controlling for the dog’s age, you might never be able to identify the true impact of the dog’s breed on its weight. You, therefore, need to run an ANCOVA to ‘filter out’ the effect of the dog’s age to see if the dog’s breed still influences the weight. Controlling for another covariate might strengthen or weaken the impact of your independent variable of interest.
For this exercise, I will use the iris dataset, which is available in core R and which we will load into the working environment under the name df using the following command:
df = iris
The iris dataset contains variables describing the shape and size of different species of Iris flowers.
A typical hypothesis that one could test using an ANOVA could be if the species of the Iris (the independent categorical variable) has any impact on other features of the flower. In our case, we are going to test whether the species of the Iris has any impact on the petal length (the dependent interval variable).
Before running the ANOVA, you must first confirm that a key assumption of the ANOVA is met in your dataset. Key assumptions are aspects, which are assumed in how your computer calculates your ANOVA results — if they are violated, your analysis might yield spurious results.
For an ANOVA, the assumption is the homogeneity of variance. This sounds complicated, but it basically checks that the variances in different groups created by the categorical independent variable are equal (i.e., the difference between the variances is zero). And we can test for the homogeneity of variance by running Levene’s test. Levene’s test is not available in base R, so we will use the car package for it.
Install the package.
install.packages("car")
Then load the package.
library(car)
Then run Levene’s test.
leveneTest(Petal.Length~Species,df)
This yields the following output:
As you can see, the test returned a significant outcome. Here it is important to know the hypotheses built into the test: Levene’s test’s null hypothesis, which we would accept if the test came back insignificantly, implies that the variance is homogenous, and we can proceed with our ANOVA. However, the test did come back significantly, which means that the variances between Petal.Length of the different species are significantly different.
What now?
Well... talk to your co-authors, colleagues, or supervisors at this point. Technically, you would have to do a robust ANOVA, which provides reliable results even in the face of inhomogeneous variances. However, not all academic disciplines follow this technical guidance... so talk to more senior colleagues in your field.
Anyhow, we will continue this tutorial as if Levene’s test came back insignificant.
We do this by specifying this model using the formula notation, the name of the data set, and the Anova command:
fit = aov(Petal.Length ~ Species, df)
In the command above, you can see that we tell R that we want to know if Species impacts Petal.Length in the dataset df using the aov command (which is the ANOVA command in R) and saving the result into the object fit. The two essential things about the above command are the syntax (i.e., the structure, the ~ symbol, the brackets, etc.) and the aov command. Everything else can be modified to fit your data: Petal.Length and Species are names specified by the iris dataset, and df and fit are just names I arbitrarily chose — they could be anything you would want to analyze.
As you might have noticed, R didn’t report any results yet. We need to tell R that we want to access the information saved into the object called fit using the following command:
summary(fit)
This command yields the following output:
This table gives you a lot of information. Still, the key parts we are interested in are the row Species, as this contains the information for the independent variable we specified and the columns F-value and Pr(>F). If our goal is to reject the null hypothesis (in this case, the null hypothesis is that the species of the Iris don’t have any impact on the petal length) and to accept our actual hypothesis (that the species do have an impact on the petal length), we are looking for high F-values and low p-values. In our case, the F-value is 1180 (which is very high), and the p-value is smaller than 0.0000000000000002 (2e-16 written out, and which is — you might have guessed it — very low). This finding supports our hypothesis that the species of the Iris has an impact on the petal length.
If we wanted to report this finding, it is good practice to report the means of the individual groups in the data (species in our case). We do this using the describeBy command from the psych package. Use the following command if you haven’t installed the psych package and want to use it for the first time:
install.packages("psych")
Otherwise, or after installing the psych package, run the following commands.
library(psych)describeBy(df$Petal.Length, df$Species)
For the describeBy function, you communicate the variable you want to see described (Petal.Length) and the grouping variable (Species). We need to specify df in front of the variable names as — differently to the formula notation used by the aov command used above — the describeBy command doesn’t allow us to specify the dataset separately. Running this command yields the following output:
In this output, we can see the three species Setosa, Versicolor, and Virginica, and in the 3rd column, we are presented with the mean of the values for Petal.Length for the three groups.
This finding could be reported in the following way:
We observed differences in petal lengths between the three species of Iris Setosa (M=1.46), Versicolor (M=4.26), and Virginica (M=5.55). An ANOVA showed that these differences between species were significant, i.e. there was a significant effect of the species on the petal length of the flower, F(2,147)=1180, p<.001.
One could also add a graph illustrating the differences using the package ggplot2. Run the below command to install the ggplot2 package if you haven’t already installed it.
install.packages("ggplot2")
Then load the package.
library(ggplot2)
And then run the command for the graph.
ggplot(df,aes(y=Petal.Length, x=Species, fill=Species))+ stat_summary(fun.y="mean", geom="bar",position="dodge")+ stat_summary(fun.data = mean_se, geom = "errorbar", position="dodge",width=.8)
This produces the graph below. The code is rather complex, and explaining the syntax of ggplot2 goes beyond this article's scope, but try to adapt it and use it for your purposes.
Now imagine you wanted to do the above analysis but while controlling for other features of the flower's size. After all, it might be that the species does not influence petal.length specifically, but more generally, the species influences the overall size of the plant. So the question is: Controlling for other plant size measures, does species still influence the length of the petal? In our analysis, the other metric that represents plant size will be the variable Sepal.Length, which is also available in the iris dataset. So, we specify our extended model just by adding this new covariate. This is the ANCOVA — we are analyzing the impact of a categorical independent variable on an interval dependent variable while controlling for one or more covariates.
fit2=aov(Petal.Length~Species+Sepal.Length,df)
However and unlike before, we cannot simply run the summary command on the fit2 object now. Because by default and very strangely, base R uses type I errors as default. Type I errors are not a problem when performing a simple ANOVA. However, if we are trying to run an ANCOVA, type I errors will lead to wrong results, and we need to use type III errors. If you are interested in what Type I vs. Type III errors are, I can recommend the Jane Superbrain section at the bottom of page 457 in Andy Field’s book “Discovering Statistics Using R.”
Therefore, we need to use another function from a different package to specify the exact type of errors we wish to use. We will be using the car package. Run the below command to install the car package if you haven’t already installed it. It is the same package as for Levene’s test above, so if you’ve been following the tutorial from the beginning, you might not have to install and load the package. If you’re unsure, just run the commands to be safe.
install.packages("car")
Then load the package.
library(car)
Then, run the car Anova command on our fit2 object, specifying that we wish to use Type III errors.
Anova(fit2, type="III")
This produces the following output:
As you can see in our row Species, column Pr(>F), which is the p-value, species still has a significant impact on the length of the petal, even when controlling for the length of the sepal. This could imply that the flowers really have different proportions and aren’t simply bigger or smaller because of the species.
Try running the summary command on the fit2 object to see that the summary command produces incorrect results; however, if you were to look at the fit2 object through the summary.lm command, which produces the output in the style of a linear model (i.e., OLS) and also uses type III errors, you would get the same correct information in the output as via the Anova command from the car package.
We could report this finding as shown below.
The covariate, sepal length, was significantly related to the flowers’ petal length, F(1,146)=194.95, p<.001. There was also a significant effect of the species of the plant on the petal length after controlling for the effect of the sepal length, F(2,146)=624.99, p<.001.
After completing either the ANOVA or ANCOVA, you should normally be running the appropriate post hoc tests to reveal more about the effects. After all, an ANOVA is merely an inferential test, i.e., it tests whether the data is distributed in a way that we would expect if the distribution were random. So far, we only know that there is a relationship between species and sepal length —we know that sepal length is non-randomly distributed when grouped by species. However, how exactly does species influence sepal length? One way of achieving this is by breaking down the variance explained by the independent variable of interest into its components . You can read more about this in my article on planned contrasts. | [
{
"code": null,
"e": 949,
"s": 172,
"text": "Analysis of Variance, or ANOVA, is a frequently-used and fundamental statistical test in many sciences. In its most common form, it analyzes how much of the variance of the dependent variable can be attributed to the independent variable(s) in the model. It is most often used to analyze the impact of a categorical independent variable (e.g., experimental conditions, dog breeds, flower species, etc.) on an interval dependent variable. At its core, an ANOVA will provide much of the same information provided in a simple linear regression (i.e., OLS). However, an ANOVA can be seen as an alternative interface through which this information can be accessed. Different scientific domains might have different preferences, which generally imply which test you should be using."
},
{
"code": null,
"e": 1537,
"s": 949,
"text": "An Analysis of Covariance, or ANCOVA, denotes an ANOVA with more than one independent variable. Imagine you would like to analyze the impact of the dog’s breed on the dog’s weight, controlling for the dog’s age. Without controlling for the dog’s age, you might never be able to identify the true impact of the dog’s breed on its weight. You, therefore, need to run an ANCOVA to ‘filter out’ the effect of the dog’s age to see if the dog’s breed still influences the weight. Controlling for another covariate might strengthen or weaken the impact of your independent variable of interest."
},
{
"code": null,
"e": 1713,
"s": 1537,
"text": "For this exercise, I will use the iris dataset, which is available in core R and which we will load into the working environment under the name df using the following command:"
},
{
"code": null,
"e": 1723,
"s": 1713,
"text": "df = iris"
},
{
"code": null,
"e": 1827,
"s": 1723,
"text": "The iris dataset contains variables describing the shape and size of different species of Iris flowers."
},
{
"code": null,
"e": 2142,
"s": 1827,
"text": "A typical hypothesis that one could test using an ANOVA could be if the species of the Iris (the independent categorical variable) has any impact on other features of the flower. In our case, we are going to test whether the species of the Iris has any impact on the petal length (the dependent interval variable)."
},
{
"code": null,
"e": 2416,
"s": 2142,
"text": "Before running the ANOVA, you must first confirm that a key assumption of the ANOVA is met in your dataset. Key assumptions are aspects, which are assumed in how your computer calculates your ANOVA results — if they are violated, your analysis might yield spurious results."
},
{
"code": null,
"e": 2832,
"s": 2416,
"text": "For an ANOVA, the assumption is the homogeneity of variance. This sounds complicated, but it basically checks that the variances in different groups created by the categorical independent variable are equal (i.e., the difference between the variances is zero). And we can test for the homogeneity of variance by running Levene’s test. Levene’s test is not available in base R, so we will use the car package for it."
},
{
"code": null,
"e": 2853,
"s": 2832,
"text": "Install the package."
},
{
"code": null,
"e": 2877,
"s": 2853,
"text": "install.packages(\"car\")"
},
{
"code": null,
"e": 2900,
"s": 2877,
"text": "Then load the package."
},
{
"code": null,
"e": 2913,
"s": 2900,
"text": "library(car)"
},
{
"code": null,
"e": 2937,
"s": 2913,
"text": "Then run Levene’s test."
},
{
"code": null,
"e": 2973,
"s": 2937,
"text": "leveneTest(Petal.Length~Species,df)"
},
{
"code": null,
"e": 3007,
"s": 2973,
"text": "This yields the following output:"
},
{
"code": null,
"e": 3452,
"s": 3007,
"text": "As you can see, the test returned a significant outcome. Here it is important to know the hypotheses built into the test: Levene’s test’s null hypothesis, which we would accept if the test came back insignificantly, implies that the variance is homogenous, and we can proceed with our ANOVA. However, the test did come back significantly, which means that the variances between Petal.Length of the different species are significantly different."
},
{
"code": null,
"e": 3462,
"s": 3452,
"text": "What now?"
},
{
"code": null,
"e": 3785,
"s": 3462,
"text": "Well... talk to your co-authors, colleagues, or supervisors at this point. Technically, you would have to do a robust ANOVA, which provides reliable results even in the face of inhomogeneous variances. However, not all academic disciplines follow this technical guidance... so talk to more senior colleagues in your field."
},
{
"code": null,
"e": 3869,
"s": 3785,
"text": "Anyhow, we will continue this tutorial as if Levene’s test came back insignificant."
},
{
"code": null,
"e": 3982,
"s": 3869,
"text": "We do this by specifying this model using the formula notation, the name of the data set, and the Anova command:"
},
{
"code": null,
"e": 4020,
"s": 3982,
"text": "fit = aov(Petal.Length ~ Species, df)"
},
{
"code": null,
"e": 4598,
"s": 4020,
"text": "In the command above, you can see that we tell R that we want to know if Species impacts Petal.Length in the dataset df using the aov command (which is the ANOVA command in R) and saving the result into the object fit. The two essential things about the above command are the syntax (i.e., the structure, the ~ symbol, the brackets, etc.) and the aov command. Everything else can be modified to fit your data: Petal.Length and Species are names specified by the iris dataset, and df and fit are just names I arbitrarily chose — they could be anything you would want to analyze."
},
{
"code": null,
"e": 4777,
"s": 4598,
"text": "As you might have noticed, R didn’t report any results yet. We need to tell R that we want to access the information saved into the object called fit using the following command:"
},
{
"code": null,
"e": 4790,
"s": 4777,
"text": "summary(fit)"
},
{
"code": null,
"e": 4832,
"s": 4790,
"text": "This command yields the following output:"
},
{
"code": null,
"e": 5630,
"s": 4832,
"text": "This table gives you a lot of information. Still, the key parts we are interested in are the row Species, as this contains the information for the independent variable we specified and the columns F-value and Pr(>F). If our goal is to reject the null hypothesis (in this case, the null hypothesis is that the species of the Iris don’t have any impact on the petal length) and to accept our actual hypothesis (that the species do have an impact on the petal length), we are looking for high F-values and low p-values. In our case, the F-value is 1180 (which is very high), and the p-value is smaller than 0.0000000000000002 (2e-16 written out, and which is — you might have guessed it — very low). This finding supports our hypothesis that the species of the Iris has an impact on the petal length."
},
{
"code": null,
"e": 5939,
"s": 5630,
"text": "If we wanted to report this finding, it is good practice to report the means of the individual groups in the data (species in our case). We do this using the describeBy command from the psych package. Use the following command if you haven’t installed the psych package and want to use it for the first time:"
},
{
"code": null,
"e": 5965,
"s": 5939,
"text": "install.packages(\"psych\")"
},
{
"code": null,
"e": 6043,
"s": 5965,
"text": "Otherwise, or after installing the psych package, run the following commands."
},
{
"code": null,
"e": 6097,
"s": 6043,
"text": "library(psych)describeBy(df$Petal.Length, df$Species)"
},
{
"code": null,
"e": 6489,
"s": 6097,
"text": "For the describeBy function, you communicate the variable you want to see described (Petal.Length) and the grouping variable (Species). We need to specify df in front of the variable names as — differently to the formula notation used by the aov command used above — the describeBy command doesn’t allow us to specify the dataset separately. Running this command yields the following output:"
},
{
"code": null,
"e": 6676,
"s": 6489,
"text": "In this output, we can see the three species Setosa, Versicolor, and Virginica, and in the 3rd column, we are presented with the mean of the values for Petal.Length for the three groups."
},
{
"code": null,
"e": 6729,
"s": 6676,
"text": "This finding could be reported in the following way:"
},
{
"code": null,
"e": 7048,
"s": 6729,
"text": "We observed differences in petal lengths between the three species of Iris Setosa (M=1.46), Versicolor (M=4.26), and Virginica (M=5.55). An ANOVA showed that these differences between species were significant, i.e. there was a significant effect of the species on the petal length of the flower, F(2,147)=1180, p<.001."
},
{
"code": null,
"e": 7221,
"s": 7048,
"text": "One could also add a graph illustrating the differences using the package ggplot2. Run the below command to install the ggplot2 package if you haven’t already installed it."
},
{
"code": null,
"e": 7249,
"s": 7221,
"text": "install.packages(\"ggplot2\")"
},
{
"code": null,
"e": 7272,
"s": 7249,
"text": "Then load the package."
},
{
"code": null,
"e": 7289,
"s": 7272,
"text": "library(ggplot2)"
},
{
"code": null,
"e": 7329,
"s": 7289,
"text": "And then run the command for the graph."
},
{
"code": null,
"e": 7524,
"s": 7329,
"text": "ggplot(df,aes(y=Petal.Length, x=Species, fill=Species))+ stat_summary(fun.y=\"mean\", geom=\"bar\",position=\"dodge\")+ stat_summary(fun.data = mean_se, geom = \"errorbar\", position=\"dodge\",width=.8)"
},
{
"code": null,
"e": 7704,
"s": 7524,
"text": "This produces the graph below. The code is rather complex, and explaining the syntax of ggplot2 goes beyond this article's scope, but try to adapt it and use it for your purposes."
},
{
"code": null,
"e": 8469,
"s": 7704,
"text": "Now imagine you wanted to do the above analysis but while controlling for other features of the flower's size. After all, it might be that the species does not influence petal.length specifically, but more generally, the species influences the overall size of the plant. So the question is: Controlling for other plant size measures, does species still influence the length of the petal? In our analysis, the other metric that represents plant size will be the variable Sepal.Length, which is also available in the iris dataset. So, we specify our extended model just by adding this new covariate. This is the ANCOVA — we are analyzing the impact of a categorical independent variable on an interval dependent variable while controlling for one or more covariates."
},
{
"code": null,
"e": 8516,
"s": 8469,
"text": "fit2=aov(Petal.Length~Species+Sepal.Length,df)"
},
{
"code": null,
"e": 9058,
"s": 8516,
"text": "However and unlike before, we cannot simply run the summary command on the fit2 object now. Because by default and very strangely, base R uses type I errors as default. Type I errors are not a problem when performing a simple ANOVA. However, if we are trying to run an ANCOVA, type I errors will lead to wrong results, and we need to use type III errors. If you are interested in what Type I vs. Type III errors are, I can recommend the Jane Superbrain section at the bottom of page 457 in Andy Field’s book “Discovering Statistics Using R.”"
},
{
"code": null,
"e": 9514,
"s": 9058,
"text": "Therefore, we need to use another function from a different package to specify the exact type of errors we wish to use. We will be using the car package. Run the below command to install the car package if you haven’t already installed it. It is the same package as for Levene’s test above, so if you’ve been following the tutorial from the beginning, you might not have to install and load the package. If you’re unsure, just run the commands to be safe."
},
{
"code": null,
"e": 9538,
"s": 9514,
"text": "install.packages(\"car\")"
},
{
"code": null,
"e": 9561,
"s": 9538,
"text": "Then load the package."
},
{
"code": null,
"e": 9574,
"s": 9561,
"text": "library(car)"
},
{
"code": null,
"e": 9674,
"s": 9574,
"text": "Then, run the car Anova command on our fit2 object, specifying that we wish to use Type III errors."
},
{
"code": null,
"e": 9698,
"s": 9674,
"text": "Anova(fit2, type=\"III\")"
},
{
"code": null,
"e": 9734,
"s": 9698,
"text": "This produces the following output:"
},
{
"code": null,
"e": 10052,
"s": 9734,
"text": "As you can see in our row Species, column Pr(>F), which is the p-value, species still has a significant impact on the length of the petal, even when controlling for the length of the sepal. This could imply that the flowers really have different proportions and aren’t simply bigger or smaller because of the species."
},
{
"code": null,
"e": 10447,
"s": 10052,
"text": "Try running the summary command on the fit2 object to see that the summary command produces incorrect results; however, if you were to look at the fit2 object through the summary.lm command, which produces the output in the style of a linear model (i.e., OLS) and also uses type III errors, you would get the same correct information in the output as via the Anova command from the car package."
},
{
"code": null,
"e": 10492,
"s": 10447,
"text": "We could report this finding as shown below."
},
{
"code": null,
"e": 10765,
"s": 10492,
"text": "The covariate, sepal length, was significantly related to the flowers’ petal length, F(1,146)=194.95, p<.001. There was also a significant effect of the species of the plant on the petal length after controlling for the effect of the sepal length, F(2,146)=624.99, p<.001."
}
] |
Play sound in Python - GeeksforGeeks | 13 Jan, 2021
In this article, we will see how to play sound in Python using some of the most popular audio libraries. We will learn about the various methods for playing sound.
Method 1: Using playsound module
Run the following command to install the packages:
pip install playsound
The playsound module contains only a single function named playsound().
It requires one argument: the path to the file with the sound we have to play. It can be a local file, or a URL.
There’s an optional second argument, block, which is set to True by default. We can set it to False for making the function run asynchronously.
It works with both WAV and MP3 files.
Example: For WAV format
Python3
# import required modulefrom playsound import playsound # for playing note.wav fileplaysound('/path/note.wav')print('playing sound using playsound')
Output:
Example: For mp3 format
Python3
# import required modulefrom playsound import playsound # for playing note.mp3 fileplaysound('/path/note.mp3')print('playing sound using playsound')
Output:
Method 2: Using pydub module
Run the following commands to install the packages:
sudo apt-get install ffmpeg libavcodec-extra
pip install pydub
Note: You can open WAV files with python. For opening mp3, you’ll need ffmpeg or libav.
This module uses the from_wav() method for playing wav file and from_mp3() method for playing an mp3 file. The play() method is used to play the wav and mp3 file:
Example 1: For WAV format
Python3
# import required modulesfrom pydub import AudioSegmentfrom pydub.playback import play # for playing wav filesong = AudioSegment.from_wav("note.wav")print('playing sound using pydub')play(song)
Output:
Example 2: For mp3 format
Python3
# import required modulefrom pydub import AudioSegmentfrom pydub.playback import play # for playing mp3 filesong = AudioSegment.from_mp3("note.mp3")print('playing sound using pydub')play(song)
Output:
Method 3: Using tksnack module
The tksnack module depends upon a module named tkinter to activate a tk object in the python script. You must install tkinker and tksnack packages for Python. Run the following commands to install the packages:
sudo apt-get install python3-tk
sudo apt-get install python3-tksnack
The play() method is used to play the audio files. The blocking argument states that the sound will play asynchronously.
Example:
Python3
# import required modulesfrom Tkinter import *import tkSnack # initialize tk object to use tksnackroot = Tk()tkSnack.initializeSnack(root) # play soundsnd = tkSnack.Sound()snd.read('note.wav')print('playing sound using tkSnack')snd.play(blocking=1)
Output:
Method 4: Using Native Player
In this method, we play sounds natively on our system. This method plays the audio file with an external player installed on your terminal.
Example 1: For Mac OS X
Python3
# import required moduleimport os # play soundfile = "note.wav"print('playing sound using native player')os.system("afplay " + file)
Output:
Example 2: For Linux
Python3
# import required moduleimport os # play soundfile = "note.mp3"print('playing sound using native player')os.system("mpg123 " + file)
Output:
Method 5: Using simpleaudio module
This is mainly designed to play WAV files and NumPy arrays. Run the following command to install the packages:
$ sudo apt-get install libasound2-dev
$ pip3 install simpleaudio
The play() method is used to play the audio files.
Example:
Python3
# import required moduleimport simpleaudio as sa # define an object to playwave_object = sa.WaveObject.from_wave_file('note.wav)print('playing sound using simpleaudio') # define an object to control the playplay_object = wave_object.play()play_object.wait_done()
Output:
Picked
python-utility
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()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python | [
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 24091,
"s": 23927,
"text": "In this article, we will see how to play sound in Python using some of the most popular audio libraries. We will learn about the various methods for playing sound."
},
{
"code": null,
"e": 24124,
"s": 24091,
"text": "Method 1: Using playsound module"
},
{
"code": null,
"e": 24175,
"s": 24124,
"text": "Run the following command to install the packages:"
},
{
"code": null,
"e": 24197,
"s": 24175,
"text": "pip install playsound"
},
{
"code": null,
"e": 24269,
"s": 24197,
"text": "The playsound module contains only a single function named playsound()."
},
{
"code": null,
"e": 24382,
"s": 24269,
"text": "It requires one argument: the path to the file with the sound we have to play. It can be a local file, or a URL."
},
{
"code": null,
"e": 24526,
"s": 24382,
"text": "There’s an optional second argument, block, which is set to True by default. We can set it to False for making the function run asynchronously."
},
{
"code": null,
"e": 24564,
"s": 24526,
"text": "It works with both WAV and MP3 files."
},
{
"code": null,
"e": 24588,
"s": 24564,
"text": "Example: For WAV format"
},
{
"code": null,
"e": 24596,
"s": 24588,
"text": "Python3"
},
{
"code": "# import required modulefrom playsound import playsound # for playing note.wav fileplaysound('/path/note.wav')print('playing sound using playsound')",
"e": 24747,
"s": 24596,
"text": null
},
{
"code": null,
"e": 24755,
"s": 24747,
"text": "Output:"
},
{
"code": null,
"e": 24779,
"s": 24755,
"text": "Example: For mp3 format"
},
{
"code": null,
"e": 24787,
"s": 24779,
"text": "Python3"
},
{
"code": "# import required modulefrom playsound import playsound # for playing note.mp3 fileplaysound('/path/note.mp3')print('playing sound using playsound')",
"e": 24938,
"s": 24787,
"text": null
},
{
"code": null,
"e": 24946,
"s": 24938,
"text": "Output:"
},
{
"code": null,
"e": 24975,
"s": 24946,
"text": "Method 2: Using pydub module"
},
{
"code": null,
"e": 25027,
"s": 24975,
"text": "Run the following commands to install the packages:"
},
{
"code": null,
"e": 25090,
"s": 25027,
"text": "sudo apt-get install ffmpeg libavcodec-extra\npip install pydub"
},
{
"code": null,
"e": 25178,
"s": 25090,
"text": "Note: You can open WAV files with python. For opening mp3, you’ll need ffmpeg or libav."
},
{
"code": null,
"e": 25342,
"s": 25178,
"text": "This module uses the from_wav() method for playing wav file and from_mp3() method for playing an mp3 file. The play() method is used to play the wav and mp3 file:"
},
{
"code": null,
"e": 25368,
"s": 25342,
"text": "Example 1: For WAV format"
},
{
"code": null,
"e": 25376,
"s": 25368,
"text": "Python3"
},
{
"code": "# import required modulesfrom pydub import AudioSegmentfrom pydub.playback import play # for playing wav filesong = AudioSegment.from_wav(\"note.wav\")print('playing sound using pydub')play(song)",
"e": 25572,
"s": 25376,
"text": null
},
{
"code": null,
"e": 25580,
"s": 25572,
"text": "Output:"
},
{
"code": null,
"e": 25606,
"s": 25580,
"text": "Example 2: For mp3 format"
},
{
"code": null,
"e": 25614,
"s": 25606,
"text": "Python3"
},
{
"code": "# import required modulefrom pydub import AudioSegmentfrom pydub.playback import play # for playing mp3 filesong = AudioSegment.from_mp3(\"note.mp3\")print('playing sound using pydub')play(song)",
"e": 25809,
"s": 25614,
"text": null
},
{
"code": null,
"e": 25817,
"s": 25809,
"text": "Output:"
},
{
"code": null,
"e": 25848,
"s": 25817,
"text": "Method 3: Using tksnack module"
},
{
"code": null,
"e": 26059,
"s": 25848,
"text": "The tksnack module depends upon a module named tkinter to activate a tk object in the python script. You must install tkinker and tksnack packages for Python. Run the following commands to install the packages:"
},
{
"code": null,
"e": 26128,
"s": 26059,
"text": "sudo apt-get install python3-tk\nsudo apt-get install python3-tksnack"
},
{
"code": null,
"e": 26249,
"s": 26128,
"text": "The play() method is used to play the audio files. The blocking argument states that the sound will play asynchronously."
},
{
"code": null,
"e": 26259,
"s": 26249,
"text": "Example: "
},
{
"code": null,
"e": 26267,
"s": 26259,
"text": "Python3"
},
{
"code": "# import required modulesfrom Tkinter import *import tkSnack # initialize tk object to use tksnackroot = Tk()tkSnack.initializeSnack(root) # play soundsnd = tkSnack.Sound()snd.read('note.wav')print('playing sound using tkSnack')snd.play(blocking=1)",
"e": 26518,
"s": 26267,
"text": null
},
{
"code": null,
"e": 26526,
"s": 26518,
"text": "Output:"
},
{
"code": null,
"e": 26556,
"s": 26526,
"text": "Method 4: Using Native Player"
},
{
"code": null,
"e": 26696,
"s": 26556,
"text": "In this method, we play sounds natively on our system. This method plays the audio file with an external player installed on your terminal."
},
{
"code": null,
"e": 26720,
"s": 26696,
"text": "Example 1: For Mac OS X"
},
{
"code": null,
"e": 26728,
"s": 26720,
"text": "Python3"
},
{
"code": "# import required moduleimport os # play soundfile = \"note.wav\"print('playing sound using native player')os.system(\"afplay \" + file)",
"e": 26862,
"s": 26728,
"text": null
},
{
"code": null,
"e": 26870,
"s": 26862,
"text": "Output:"
},
{
"code": null,
"e": 26891,
"s": 26870,
"text": "Example 2: For Linux"
},
{
"code": null,
"e": 26899,
"s": 26891,
"text": "Python3"
},
{
"code": "# import required moduleimport os # play soundfile = \"note.mp3\"print('playing sound using native player')os.system(\"mpg123 \" + file)",
"e": 27033,
"s": 26899,
"text": null
},
{
"code": null,
"e": 27041,
"s": 27033,
"text": "Output:"
},
{
"code": null,
"e": 27076,
"s": 27041,
"text": "Method 5: Using simpleaudio module"
},
{
"code": null,
"e": 27187,
"s": 27076,
"text": "This is mainly designed to play WAV files and NumPy arrays. Run the following command to install the packages:"
},
{
"code": null,
"e": 27252,
"s": 27187,
"text": "$ sudo apt-get install libasound2-dev\n$ pip3 install simpleaudio"
},
{
"code": null,
"e": 27303,
"s": 27252,
"text": "The play() method is used to play the audio files."
},
{
"code": null,
"e": 27312,
"s": 27303,
"text": "Example:"
},
{
"code": null,
"e": 27320,
"s": 27312,
"text": "Python3"
},
{
"code": "# import required moduleimport simpleaudio as sa # define an object to playwave_object = sa.WaveObject.from_wave_file('note.wav)print('playing sound using simpleaudio') # define an object to control the playplay_object = wave_object.play()play_object.wait_done()",
"e": 27585,
"s": 27320,
"text": null
},
{
"code": null,
"e": 27593,
"s": 27585,
"text": "Output:"
},
{
"code": null,
"e": 27600,
"s": 27593,
"text": "Picked"
},
{
"code": null,
"e": 27615,
"s": 27600,
"text": "python-utility"
},
{
"code": null,
"e": 27622,
"s": 27615,
"text": "Python"
},
{
"code": null,
"e": 27720,
"s": 27622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27729,
"s": 27720,
"text": "Comments"
},
{
"code": null,
"e": 27742,
"s": 27729,
"text": "Old Comments"
},
{
"code": null,
"e": 27774,
"s": 27742,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27830,
"s": 27774,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27872,
"s": 27830,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27914,
"s": 27872,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27950,
"s": 27914,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27989,
"s": 27950,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28011,
"s": 27989,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28042,
"s": 28011,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28069,
"s": 28042,
"text": "Python Classes and Objects"
}
] |
Deploy Nodejs microservices to a Docker Swarm Cluster [Docker from zero to hero] | by Cristian Ramirez | Towards Data Science | This is the 🖐🏽 fifth article from the series “Build a NodeJS cinema microservice”. This series of articles demonstrates how to design, build, and deploy microservices with expressjs using ES6, ¿ES7 ...8?, connected to a MongoDB Replica Set, and deploying it into a docker containers to simulate the power of a cloud environment.
The first article introduces the Microservices Architecture pattern and discusses the benefits and drawbacks of using microservices. The second article we talked about microservices security with the HTTP/2 protocol and we saw how to implement it. The third article in the series we describe different aspects of communication within a microservices architecture, and we explain about design patterns in NodeJS like Dependency Injection, Inversion of Control and SOLID principles. In the fourth article we talked about what is an API Gateway, we see what is a network proxy and an ES6 Proxy Object. We have developed 5 services and we have dockerize them, also we have made a lot of type of testing, because we are curious and good developers.
if you haven’t read the previous chapters, you’re missing some great stuff 👍🏽, so i will put the links below, so you can give it a look 👀.
medium.com
medium.com
medium.com
medium.com
We have been developing, coding, programming, 👩🏻💻👨🏻💻 in the last episodes, we were very excited in how to create a nodejs microservice, that we haven’t had time to talk about the architecture of our system, we haven’t talked about something we have been using since chapter 1, and that is Docker.
Well the moment has come folks to see the power 💪🏽 of containerization 🗄. If you are looking to get your hands 🙌🏽 dirty and learn all the fuss about Docker, then grab your seat, put on your seat belt, because our journey is going to get amusing.
Until know we have created 3 docker-machines , we created a mongo database replica set cluster where we put a replica in each docker-machine, then we have created our microservices, but we have been creating and deploying it manually only in the manager1 docker-machine, so we have been wasting computing resources in the other two docker-machines, but we are not longer doing that, because we are going to start to configure Docker, in the correct way and from scratch :D.
What we are going to use for this article:
NodeJS version 7.5.0 (for our microservices)
MongoDB 3.4.2 (for our database)
Docker for Mac 1.13.0 or equivalent (installed, version 1.13.1 incompatible with dockerode)
Prerequisites to following up the article:
Basic knowledge in bash scripting.
Have completed the examples from the last chapter.
If you haven’t, i have uploaded a github repository, so you can be up to date, at the repo link at the branch step-5.
Docker is an open source project to pack, ship and run any application as a lightweight container.
Docker containers are both hardware-agnostic and platform-agnostic. This means they can run anywhere, from your laptop to the largest cloud compute instance and everything in between — and they don’t require you to use a particular language, framework or packaging system. That makes them great building blocks for deploying and scaling web apps, databases, and backend services without depending on a particular stack or provider. — @Docker
So in other words, docker let us build templates (if we can call it templates, this templates are docker images) for creating containers that holds a virtual machine (if we can call it virtual machine, because is they’re not) where we can include our application and install all of its dependencies, and run it as an isolated process, sharing the kernel with other containers in the host operating system or in any IaaS platform.
Virtual machines includes the application, the necessary binaries, libraries and an entire guest operating system, which can amount to tens of GB — @Docker
Docker Machine let us create Docker hosts on our computers, on cloud providers, and inside data centers. It creates servers, installs Docker on them, then configures the Docker client to talk to them. — @Docker
Docker Machine is a tool that let us install Docker Engine on virtual hosts, and manage the hosts with docker-machine commands. You can use Machine to create Docker hosts on your local Mac or Windows box, on your company network, in data centers, or on cloud providers like AWS or Digital Ocean. Docker Engine runs natively on Linux systems. If you have a Linux box as your primary system, and want to run docker commands, all you need to do is download and install Docker Engine.
We need it if we want to manage efficiently our Docker host on a network, in the cloud or even locally, and because if we make tests locally, Docker-Machine can help us to simulate a cloud environment.
Docker Swarm is native clustering for Docker. It turns a pool of Docker hosts into a single, virtual host using an API proxy system.
A cluster is a set of tightly coupled computers that function like a single machine. The individual machines, called nodes, communicate with each other over a very fast network, and they’re physically very close together, perhaps in the same cabinet. Usually they have identical or nearly identical hardware and software. All the nodes can handle the same types of request. Sometimes one node takes requests and dispatches them to the others. — Phil Dougherty
Ok so now let’s see what we can accomplish creating a Docker Swarm Cluster:
Multi-host networking
Scalling
Load Balancing
Security by default
Cluster management
and many more things, so now that we have gain some vocabulary and knowledge about the Docker Ecosystem, its time to see how we can create our architecture and deploy our cinema microservice to a Docker Swarm Cluster, that handles hundreds or thousands or millions of user requests, like booking 🎟, shopping 🕹, watching 🎥, or whatever action that a users 👥 does in our cinema system.
When you run Docker without using swarm mode, you execute container commands. When you run the Docker in swarm mode, you orchestrate services. You can run swarm services and standalone containers on the same Docker instances. — @Docker
We are going to start builiding our cinema microservice architecture from scratch, so let’s begin with talking in how to create our docker machines and how to init a docker swarm cluster.
First we need to create a new folder in the root of our cinemas project called _docker_setup before we start creating and modifying files, so our project needs to look like the following:
. |-- _docker_setup | `-- ... here we are going to put our bash files |-- api-gateway| `-- ... more files|-- booking-service| `-- ... more files|-- cinema-catalog-service| `-- ... more files|-- movies-service| `-- ... more files|-- notification-service| `-- ... more files|-- payment-service| `-- ... more files
So let’s create a bash file in our _docker_setup folder called setup-swarm.sh this will create and setup our docker swarm cluster. Why a bash file, because a good developer can automate so much things like this:
Ok so it’s a little bit lengthy script, but i want to put it all, because it give us a better picture on what is going on and how we can accomplish the docker swarm cluster set-up automation.
So let’s split the script and talk about what is happing there.
# So first the basics, how do we create a docker-machine.$ docker-machine create -d $DRIVER $ADDITIONAL_PARAMS $MACHINE_NAME
This is basically how we can create the machines it doesn’t care if they will be a manager node or a worker node, it is the same command for both. The driver could be virtualbox, parallels, digital-ocean, AWS, etc.
Once we create our machines, its time to init the swarm cluster, like the following:
$ docker-machine ssh manager1 docker swarm init --advertise-addr $(getIP manager1)
Its a simple docker command, easy as that, docker swarm init, initialize the swarm manager configuration. We can do this in two ways, setting our environment like the following eval `docker-machine env manager1` and execute the docker swarm init command or we can ssh to the machine like the following docker-machine ssh manager1 {and here we pass the docker commands}, to init the swarm we need the docker-machine ip the ip could vary by the driver provider, so to get the ip, i made a bash function that will retrieve the ip of a given docker-machine.
Once the swarm manager has been initiated, we are ready to add the worker nodes, and to do that we call the function join_node_manager that does the following:
$ docker-machine ssh {name of worker} docker swarm join --token $(get_worker_token) $(getIP manager1):2377
Again we are going to loop this command with the given number of workers variable in our script, and what this command is doing is first calling the function get_worker_token and this will get the token from the manager node, this is the token need it to register the worker node to the swarm cluster, next it will call again the function that retrieves the ip of a give docker-machine, and will complete the docker swarm cluster configuration, and we are ready to go, to deploy our cinema microservices.
To take advantage of swarm mode’s fault-tolerance features, Docker recommends you to implement an odd number of nodes according to your organization’s high-availability requirements. — @Docker
Containers are the best way to deploy Node.js applications to production. Containers provide a wide variety of benefits, from having the same environment in production and development to streamlining deploys for speed and size. — Tierney Cyren
Currently we have 5 microservices and 1 api-gateway service, which we can run on a dev box, as long as it has a compatible version of Node.js installed. What we’d like to do is to create a Docker Service (we will see what is this later on the chapter) but for that we need to create a Docker Image for every microservice that we have.
Once created the Docker image we are able to deploy our service anywhere which supports docker.
The way we create a Docker image is by creating first a Dockerfile(the template). A Dockerfile is a recipe that tells the Docker engine how to build our images.
As we are developing only nodejs apps we can use the same Dockerfile specifications in all our microservices in our project, but are we doing everything to make the process as reliable and vigorous as possible?
So this is the next file we are going to review, and also we are going to apply good practices on it.
Now we can modify all our microservices Dockerfiles, that we have created before with this specifications.
Let’s talk a little bit of what is going on and if this process is reliable.
By default, the applications process inside a Docker container runs as a root user. This can pose a potentially serious security risk when running in production. A simple solution to this problem is to create a new user inside of a Docker image and use that user to execute our application. The first process inside of a Docker container will be PID 1. The Linux kernel gives PID 1 special treatment, and many applications were not designed to handle the extra responsibilities that come with being PID 1. When running Node.js as PID 1, there will be several manifestations of the process failing to handle those responsibilities, the most painful of which is the process ignoring SIGTERM commands. dumb-init was designed to be a super simple process that handles the responsibilities of running as PID 1 for whatever process it is told to start.
To build our Docker Images, we need to run the following command:
# This command will create a new docker image$ docker build -t movies-service .
Let’s look at the build command.
docker build tell the engine we want to create a new image.-t flag tag this image with the tag movies-service. We can refer to this image by tag from now on.. use the current directory to find the Dockerfile.
docker build tell the engine we want to create a new image.
-t flag tag this image with the tag movies-service. We can refer to this image by tag from now on.
. use the current directory to find the Dockerfile.
Now we are ready to run a container with our new docker image, and to do that we need the following command:
$ docker run --name movies-service -l=apiRoute='/movies' -p 3000:3000 -d movies-service
Let’s look at the run command.
docker run tell the engine we want to start a new container.--name flag sets a name to the container. We can refer to this container by the name from now on.-l flag sets metadata to the container.-p flag sets the port binding from {host}:{container}-d flag run the container in detached mode, this maintains the container running in the background.
docker run tell the engine we want to start a new container.
--name flag sets a name to the container. We can refer to this container by the name from now on.
-l flag sets metadata to the container.
-p flag sets the port binding from {host}:{container}
-d flag run the container in detached mode, this maintains the container running in the background.
So now let’s create a bash file in our _docker_setup foleder called create-images.sh to automate the creation of all our microservices docker images.
Before we execute this script, we need to modify our start-service.sh that we have on each microservice and rename it to create-image.sh, so it can look like the following:
#!/usr/bin/env bashdocker rm -f {name of the service}docker rmi {name of the service}docker image prunedocker volume prune# the previous commands are for removing existing containers, # and image, then we clean our environment and finally # we creat or re-build our imagedocker build -t {name of the service} .
Publish our docker image ¿ 🤔 ? , Docker maintains a vast repository of images, called the Docker Hub, which you can use as starting points or as free storage for our own images. This is where we are pulling our node:7.5.0-alpine image to create our microservices images. ¿ But why do we need to publish our images ?
Well because, later on the chapter we are going to create Docker Services, and this services will be deploy and replicate all over our Docker Swarm Cluster, and to start our services, the cluster nodes needs the image of the servcice to start the containers and if the image is not present locally it will search it in the docker hub and then will pull it to the host to have the image locally and be able to stat our services.
But first we need to create an account at the Docker Hub website, then we need to login in our shell doing the following command:
$ docker login Username: ***** Password: ***** Login Succeeded
Next we need to tag our images, to be able to reference them by name and push them to the docker hub.
Now that we have logged in, and we now the structure on how to tag our docker images, its time to modify our create-images.sh, so it can create our images, tag our images and push our images to the docker hub, all automatically for us, our bash file needs to look like the following.
This is a little bit of topic to docker steps, but we need a database to persist our data that our microservices uses, and in this step i won’t spent time to describe how to do it, i have already wrote an article on how to deploy a mongodb replica set cluster to docker, and i highly suggest you, to give it a look to my article if you haven’t.
medium.com
Or skip this step and wait until you read step-7 .(and make some thug life 😎)
Doing step 5 is highly important because if we haven’t our database up and running our docker services wont start correctly.
So now let’s create another file in our _docker_setup folder called start-services.sh this bash script will start all our microservices in the type of Docker Services, so that this services can scale up or scale down, as needed.
Now that our services is going to scale up and down, we are getting into trouble to call those services, but there is nothing the be afraid of, my dear readers, because, i said before that one of the benefits of creating a Docker swarm cluster, is that it setup for us behind the scenes a load balancer and docker is the responsible to handle which service to call when is requested. So let’s review our next file.
As you can see this file is very similar to our create-images.sh but this time we are calling the start-service.sh from every service, and now let’s see how is composed the start-service.sh file.
#!/usr/bin/env bashdocker service create --replicas 3 --name {service name} -l=apiRoute='{our api route}' -p {port binding} --env-file env {microservice image}
Let’s look at the the service command:
The docker service create command creates the service.
The --name flag names the service e.g. movies-service.
The --replicas flag specifies the desired state of 3 running instances.
The -l flag species that we can attach metadata e.g.apiRoute="/movies".
The -p flag specifies the port binding on the host and the container.
The -e flag specifies the can set to the service environment variables.
Well well well, its time to do the magic 🔮✨ folks.
To execute all our automated files that we have created, let’s create the final script that will do everything for us, because developers are lazy 🤓.
So we need to create this file at the root of the cinemas microservice project and we are going to call it the kraken.sh 🦑 just for fun and because is very powerful 😎.
Well it doesn’t have fancy programming inside, but what it does, is calling all our automated scripts for us and do our job.
Finally let’s execute it like the following.
$ bash < kraken.sh
As simple as that, we have been doing so much modularity to simplify the process of creating a Docker Swarm Cluster, and start our Docker Services automatically.
“Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.” — Steve Jobs
I have uploaded a video demonstration to see what happens when we execute the kraken.sh i speed it up the video a little bit, but the kraken process may take like 10 min more less depending on the host power to finish.
Finally we can check the status of our docker environment executing the following commands that appears on the image below.
As you can see some services are already replicated in our cluster, others doesn’t have even started, thats because the machines are pulling our images to start our services, and once our images are downloaded and our services are started we should se something like the following image.
So now our architecture looks like the following diagram, where all our microservices are created dinamically, replicated through all the cluster, and can be scale as needed, the only services that are created manually are our mongo containers and the api-gateways, why because they are attached to specifications of our host servers, mongo needs a persistent storage and our api needs to discover the host docker services.
Now let’s verify that our services are currently up and running, so we need to execute the commands like the image below.
And If we run a Docker Swarm visualizer, that are available on github, we can see how our services (containers) are distributed on our Docker swarm cluster, like the following image.
And if we scale down some services e.g. docker-machine ssh manager1 docker service scale movies-service=1, we can se how our services are redistributed on our Docker swarm cluster, like the image below.
We are almost done with our cinemas microservice configurations, and also with our cinemas microservice system.
It has been a very large article, but we have learned to much on how docker can fit with our development and also how can docker complement our system to be more robust.
There is a couple of things we still need to do, to get correctly set and ready to run our cinema microservice:
we need to update the api-gateway, so that can discover now the docker services that are running to be able to do proxy.
we need to populate our database and for that you can go and check the commands at the github repository readme here.
In our API Gateway, we just need to change a few lines in our docker.js instead of calling the listContainers() function, we will call the listServices() function and set our routes with the provided services.
To not make this article more longer, you are welcome to check the complete code changes to the API Gateway, at the github repository, and if you have any question, as always you are welcome to send me a tweet or just put a comment below 😃📝.
Because our article wouldn’t be complete without making some testing to our system. Tests are fundamentally important because we can look to the system from different angles, with different perspectives and testing it with different expectations, the ultimate purpose of software testing is not to find bugs but to make the product qualitative. As a good testers, we are contributing in improvements of the product quality.
# we need to locate at the api-gateway folder and execute the test$ npm run int-test
And we will have an output like the following.
Here we are calling our api-gateway services as you can see we are calling to different docker-machine ip and our api-gateway proxies our requests to our Docker Services, and finally our test passes correctly 😎.
Also i have recorded a jmeter stress test to our cinema microservice system deployed in our docker swarm cluster, so you can see what are the expected results.
What we have done...
We’ve seen a lot of docker 🐋. We talked about what it is this whale, Docker, Docker-Machine, Docker-Swarm, Docker-Images, Docker-Hub, Docker-Services and how to make their appropriate configurations, how to set it up with an automation process and how does it fit with our cinemas system.
With docker we made our cinemas microservices and system more dynamically, fault tolerant, scalable and secure. But there is so much interesting things to see yet with docker, for example, Docker Network, Docker Compose, Docker plugins, etc... docker is an expanding devops world.
We’ve seen a lot of development in microservices with NodeJS, and we have seen how to implement this microservices with the Docker Ecosystem but there’s a lot more that we can do and learn, this is just a sneak peak for a little bit of more advance docker playground. I hope this has shown some of the interesting and useful things that you can use for Docker and NodeJS in your workflow.
I know that this article has become very large, but i think that its worth it to see an extra step, that will show us how to monitor our docker swarm cluster.
So to start monitoring our cluster we need to execute the following command in our manager1 docker-machine
$ docker-machine ssh manager1 docker run --name rancher --restart=unless-stopped -p 9000:8080 -d rancher/server
Then when the container is ready we need to visit the following url http://192.168.99.100:9000 in our browser.
Then the rancher gui, will give you through the setup, and finally we will be able to monitor our cluster.
And if we click in one of the hosts, we can see something like following.
Finally a have a recorded the super duper stress integration test so you can be able to see the results in video the result of all this configurations and how we can monitor our cluster via either graphic interface or console logs 😎 the console log rocks🤘🏽.
So we have seen the super power 💪🏽 that the blue whale 🐋 has to offer to us.
Ok so there is our cinemas microservice system almost complete, there is something missing, our cinemas microservice system wouldn’t be useful if we don’t develop that missing master piece, and that my friends, is the front end service that our final users will be interacting with our system 😎, and that web UI is the missing piece to complete our system.
Thanks for reading! I hope you find value in the article! If you did, punch that Recommend Button, recommend it to a friend, share it or read it again .
In case you have questions on any aspect of this series or need my help in understanding something, feel free to tweet me or leave a comment below.
Let me remember you, this article is part of “Build a NodeJS cinema microservice” series so, next week i will publish another chapter.
So in the meantime, stay tuned, stay curious ✌🏼👨🏻💻👩🏻💻
¡ Hasta la próxima ! 😁
You can follow me at twitter @cramirez_92https://twitter.com/cramirez_92
You can check the complete code of the article at the following link.
github.com
How does docker services work
Docker Swarm overview
Docker GitHub
Definitions From a Developer: What Is A Cluster?
8 Protips to Start Killing It When Dockerizing Node.js | [
{
"code": null,
"e": 501,
"s": 172,
"text": "This is the 🖐🏽 fifth article from the series “Build a NodeJS cinema microservice”. This series of articles demonstrates how to design, build, and deploy microservices with expressjs using ES6, ¿ES7 ...8?, connected to a MongoDB Replica Set, and deploying it into a docker containers to simulate the power of a cloud environment."
},
{
"code": null,
"e": 1245,
"s": 501,
"text": "The first article introduces the Microservices Architecture pattern and discusses the benefits and drawbacks of using microservices. The second article we talked about microservices security with the HTTP/2 protocol and we saw how to implement it. The third article in the series we describe different aspects of communication within a microservices architecture, and we explain about design patterns in NodeJS like Dependency Injection, Inversion of Control and SOLID principles. In the fourth article we talked about what is an API Gateway, we see what is a network proxy and an ES6 Proxy Object. We have developed 5 services and we have dockerize them, also we have made a lot of type of testing, because we are curious and good developers."
},
{
"code": null,
"e": 1384,
"s": 1245,
"text": "if you haven’t read the previous chapters, you’re missing some great stuff 👍🏽, so i will put the links below, so you can give it a look 👀."
},
{
"code": null,
"e": 1395,
"s": 1384,
"text": "medium.com"
},
{
"code": null,
"e": 1406,
"s": 1395,
"text": "medium.com"
},
{
"code": null,
"e": 1417,
"s": 1406,
"text": "medium.com"
},
{
"code": null,
"e": 1428,
"s": 1417,
"text": "medium.com"
},
{
"code": null,
"e": 1727,
"s": 1428,
"text": "We have been developing, coding, programming, 👩🏻💻👨🏻💻 in the last episodes, we were very excited in how to create a nodejs microservice, that we haven’t had time to talk about the architecture of our system, we haven’t talked about something we have been using since chapter 1, and that is Docker."
},
{
"code": null,
"e": 1973,
"s": 1727,
"text": "Well the moment has come folks to see the power 💪🏽 of containerization 🗄. If you are looking to get your hands 🙌🏽 dirty and learn all the fuss about Docker, then grab your seat, put on your seat belt, because our journey is going to get amusing."
},
{
"code": null,
"e": 2447,
"s": 1973,
"text": "Until know we have created 3 docker-machines , we created a mongo database replica set cluster where we put a replica in each docker-machine, then we have created our microservices, but we have been creating and deploying it manually only in the manager1 docker-machine, so we have been wasting computing resources in the other two docker-machines, but we are not longer doing that, because we are going to start to configure Docker, in the correct way and from scratch :D."
},
{
"code": null,
"e": 2490,
"s": 2447,
"text": "What we are going to use for this article:"
},
{
"code": null,
"e": 2535,
"s": 2490,
"text": "NodeJS version 7.5.0 (for our microservices)"
},
{
"code": null,
"e": 2568,
"s": 2535,
"text": "MongoDB 3.4.2 (for our database)"
},
{
"code": null,
"e": 2660,
"s": 2568,
"text": "Docker for Mac 1.13.0 or equivalent (installed, version 1.13.1 incompatible with dockerode)"
},
{
"code": null,
"e": 2703,
"s": 2660,
"text": "Prerequisites to following up the article:"
},
{
"code": null,
"e": 2738,
"s": 2703,
"text": "Basic knowledge in bash scripting."
},
{
"code": null,
"e": 2789,
"s": 2738,
"text": "Have completed the examples from the last chapter."
},
{
"code": null,
"e": 2907,
"s": 2789,
"text": "If you haven’t, i have uploaded a github repository, so you can be up to date, at the repo link at the branch step-5."
},
{
"code": null,
"e": 3006,
"s": 2907,
"text": "Docker is an open source project to pack, ship and run any application as a lightweight container."
},
{
"code": null,
"e": 3448,
"s": 3006,
"text": "Docker containers are both hardware-agnostic and platform-agnostic. This means they can run anywhere, from your laptop to the largest cloud compute instance and everything in between — and they don’t require you to use a particular language, framework or packaging system. That makes them great building blocks for deploying and scaling web apps, databases, and backend services without depending on a particular stack or provider. — @Docker"
},
{
"code": null,
"e": 3878,
"s": 3448,
"text": "So in other words, docker let us build templates (if we can call it templates, this templates are docker images) for creating containers that holds a virtual machine (if we can call it virtual machine, because is they’re not) where we can include our application and install all of its dependencies, and run it as an isolated process, sharing the kernel with other containers in the host operating system or in any IaaS platform."
},
{
"code": null,
"e": 4034,
"s": 3878,
"text": "Virtual machines includes the application, the necessary binaries, libraries and an entire guest operating system, which can amount to tens of GB — @Docker"
},
{
"code": null,
"e": 4245,
"s": 4034,
"text": "Docker Machine let us create Docker hosts on our computers, on cloud providers, and inside data centers. It creates servers, installs Docker on them, then configures the Docker client to talk to them. — @Docker"
},
{
"code": null,
"e": 4726,
"s": 4245,
"text": "Docker Machine is a tool that let us install Docker Engine on virtual hosts, and manage the hosts with docker-machine commands. You can use Machine to create Docker hosts on your local Mac or Windows box, on your company network, in data centers, or on cloud providers like AWS or Digital Ocean. Docker Engine runs natively on Linux systems. If you have a Linux box as your primary system, and want to run docker commands, all you need to do is download and install Docker Engine."
},
{
"code": null,
"e": 4928,
"s": 4726,
"text": "We need it if we want to manage efficiently our Docker host on a network, in the cloud or even locally, and because if we make tests locally, Docker-Machine can help us to simulate a cloud environment."
},
{
"code": null,
"e": 5061,
"s": 4928,
"text": "Docker Swarm is native clustering for Docker. It turns a pool of Docker hosts into a single, virtual host using an API proxy system."
},
{
"code": null,
"e": 5521,
"s": 5061,
"text": "A cluster is a set of tightly coupled computers that function like a single machine. The individual machines, called nodes, communicate with each other over a very fast network, and they’re physically very close together, perhaps in the same cabinet. Usually they have identical or nearly identical hardware and software. All the nodes can handle the same types of request. Sometimes one node takes requests and dispatches them to the others. — Phil Dougherty"
},
{
"code": null,
"e": 5597,
"s": 5521,
"text": "Ok so now let’s see what we can accomplish creating a Docker Swarm Cluster:"
},
{
"code": null,
"e": 5619,
"s": 5597,
"text": "Multi-host networking"
},
{
"code": null,
"e": 5628,
"s": 5619,
"text": "Scalling"
},
{
"code": null,
"e": 5643,
"s": 5628,
"text": "Load Balancing"
},
{
"code": null,
"e": 5663,
"s": 5643,
"text": "Security by default"
},
{
"code": null,
"e": 5682,
"s": 5663,
"text": "Cluster management"
},
{
"code": null,
"e": 6066,
"s": 5682,
"text": "and many more things, so now that we have gain some vocabulary and knowledge about the Docker Ecosystem, its time to see how we can create our architecture and deploy our cinema microservice to a Docker Swarm Cluster, that handles hundreds or thousands or millions of user requests, like booking 🎟, shopping 🕹, watching 🎥, or whatever action that a users 👥 does in our cinema system."
},
{
"code": null,
"e": 6302,
"s": 6066,
"text": "When you run Docker without using swarm mode, you execute container commands. When you run the Docker in swarm mode, you orchestrate services. You can run swarm services and standalone containers on the same Docker instances. — @Docker"
},
{
"code": null,
"e": 6490,
"s": 6302,
"text": "We are going to start builiding our cinema microservice architecture from scratch, so let’s begin with talking in how to create our docker machines and how to init a docker swarm cluster."
},
{
"code": null,
"e": 6678,
"s": 6490,
"text": "First we need to create a new folder in the root of our cinemas project called _docker_setup before we start creating and modifying files, so our project needs to look like the following:"
},
{
"code": null,
"e": 7004,
"s": 6678,
"text": ". |-- _docker_setup | `-- ... here we are going to put our bash files |-- api-gateway| `-- ... more files|-- booking-service| `-- ... more files|-- cinema-catalog-service| `-- ... more files|-- movies-service| `-- ... more files|-- notification-service| `-- ... more files|-- payment-service| `-- ... more files"
},
{
"code": null,
"e": 7216,
"s": 7004,
"text": "So let’s create a bash file in our _docker_setup folder called setup-swarm.sh this will create and setup our docker swarm cluster. Why a bash file, because a good developer can automate so much things like this:"
},
{
"code": null,
"e": 7408,
"s": 7216,
"text": "Ok so it’s a little bit lengthy script, but i want to put it all, because it give us a better picture on what is going on and how we can accomplish the docker swarm cluster set-up automation."
},
{
"code": null,
"e": 7472,
"s": 7408,
"text": "So let’s split the script and talk about what is happing there."
},
{
"code": null,
"e": 7597,
"s": 7472,
"text": "# So first the basics, how do we create a docker-machine.$ docker-machine create -d $DRIVER $ADDITIONAL_PARAMS $MACHINE_NAME"
},
{
"code": null,
"e": 7812,
"s": 7597,
"text": "This is basically how we can create the machines it doesn’t care if they will be a manager node or a worker node, it is the same command for both. The driver could be virtualbox, parallels, digital-ocean, AWS, etc."
},
{
"code": null,
"e": 7897,
"s": 7812,
"text": "Once we create our machines, its time to init the swarm cluster, like the following:"
},
{
"code": null,
"e": 7980,
"s": 7897,
"text": "$ docker-machine ssh manager1 docker swarm init --advertise-addr $(getIP manager1)"
},
{
"code": null,
"e": 8534,
"s": 7980,
"text": "Its a simple docker command, easy as that, docker swarm init, initialize the swarm manager configuration. We can do this in two ways, setting our environment like the following eval `docker-machine env manager1` and execute the docker swarm init command or we can ssh to the machine like the following docker-machine ssh manager1 {and here we pass the docker commands}, to init the swarm we need the docker-machine ip the ip could vary by the driver provider, so to get the ip, i made a bash function that will retrieve the ip of a given docker-machine."
},
{
"code": null,
"e": 8694,
"s": 8534,
"text": "Once the swarm manager has been initiated, we are ready to add the worker nodes, and to do that we call the function join_node_manager that does the following:"
},
{
"code": null,
"e": 8801,
"s": 8694,
"text": "$ docker-machine ssh {name of worker} docker swarm join --token $(get_worker_token) $(getIP manager1):2377"
},
{
"code": null,
"e": 9306,
"s": 8801,
"text": "Again we are going to loop this command with the given number of workers variable in our script, and what this command is doing is first calling the function get_worker_token and this will get the token from the manager node, this is the token need it to register the worker node to the swarm cluster, next it will call again the function that retrieves the ip of a give docker-machine, and will complete the docker swarm cluster configuration, and we are ready to go, to deploy our cinema microservices."
},
{
"code": null,
"e": 9499,
"s": 9306,
"text": "To take advantage of swarm mode’s fault-tolerance features, Docker recommends you to implement an odd number of nodes according to your organization’s high-availability requirements. — @Docker"
},
{
"code": null,
"e": 9743,
"s": 9499,
"text": "Containers are the best way to deploy Node.js applications to production. Containers provide a wide variety of benefits, from having the same environment in production and development to streamlining deploys for speed and size. — Tierney Cyren"
},
{
"code": null,
"e": 10078,
"s": 9743,
"text": "Currently we have 5 microservices and 1 api-gateway service, which we can run on a dev box, as long as it has a compatible version of Node.js installed. What we’d like to do is to create a Docker Service (we will see what is this later on the chapter) but for that we need to create a Docker Image for every microservice that we have."
},
{
"code": null,
"e": 10174,
"s": 10078,
"text": "Once created the Docker image we are able to deploy our service anywhere which supports docker."
},
{
"code": null,
"e": 10335,
"s": 10174,
"text": "The way we create a Docker image is by creating first a Dockerfile(the template). A Dockerfile is a recipe that tells the Docker engine how to build our images."
},
{
"code": null,
"e": 10546,
"s": 10335,
"text": "As we are developing only nodejs apps we can use the same Dockerfile specifications in all our microservices in our project, but are we doing everything to make the process as reliable and vigorous as possible?"
},
{
"code": null,
"e": 10648,
"s": 10546,
"text": "So this is the next file we are going to review, and also we are going to apply good practices on it."
},
{
"code": null,
"e": 10755,
"s": 10648,
"text": "Now we can modify all our microservices Dockerfiles, that we have created before with this specifications."
},
{
"code": null,
"e": 10832,
"s": 10755,
"text": "Let’s talk a little bit of what is going on and if this process is reliable."
},
{
"code": null,
"e": 11679,
"s": 10832,
"text": "By default, the applications process inside a Docker container runs as a root user. This can pose a potentially serious security risk when running in production. A simple solution to this problem is to create a new user inside of a Docker image and use that user to execute our application. The first process inside of a Docker container will be PID 1. The Linux kernel gives PID 1 special treatment, and many applications were not designed to handle the extra responsibilities that come with being PID 1. When running Node.js as PID 1, there will be several manifestations of the process failing to handle those responsibilities, the most painful of which is the process ignoring SIGTERM commands. dumb-init was designed to be a super simple process that handles the responsibilities of running as PID 1 for whatever process it is told to start."
},
{
"code": null,
"e": 11745,
"s": 11679,
"text": "To build our Docker Images, we need to run the following command:"
},
{
"code": null,
"e": 11825,
"s": 11745,
"text": "# This command will create a new docker image$ docker build -t movies-service ."
},
{
"code": null,
"e": 11858,
"s": 11825,
"text": "Let’s look at the build command."
},
{
"code": null,
"e": 12067,
"s": 11858,
"text": "docker build tell the engine we want to create a new image.-t flag tag this image with the tag movies-service. We can refer to this image by tag from now on.. use the current directory to find the Dockerfile."
},
{
"code": null,
"e": 12127,
"s": 12067,
"text": "docker build tell the engine we want to create a new image."
},
{
"code": null,
"e": 12226,
"s": 12127,
"text": "-t flag tag this image with the tag movies-service. We can refer to this image by tag from now on."
},
{
"code": null,
"e": 12278,
"s": 12226,
"text": ". use the current directory to find the Dockerfile."
},
{
"code": null,
"e": 12387,
"s": 12278,
"text": "Now we are ready to run a container with our new docker image, and to do that we need the following command:"
},
{
"code": null,
"e": 12475,
"s": 12387,
"text": "$ docker run --name movies-service -l=apiRoute='/movies' -p 3000:3000 -d movies-service"
},
{
"code": null,
"e": 12506,
"s": 12475,
"text": "Let’s look at the run command."
},
{
"code": null,
"e": 12855,
"s": 12506,
"text": "docker run tell the engine we want to start a new container.--name flag sets a name to the container. We can refer to this container by the name from now on.-l flag sets metadata to the container.-p flag sets the port binding from {host}:{container}-d flag run the container in detached mode, this maintains the container running in the background."
},
{
"code": null,
"e": 12916,
"s": 12855,
"text": "docker run tell the engine we want to start a new container."
},
{
"code": null,
"e": 13014,
"s": 12916,
"text": "--name flag sets a name to the container. We can refer to this container by the name from now on."
},
{
"code": null,
"e": 13054,
"s": 13014,
"text": "-l flag sets metadata to the container."
},
{
"code": null,
"e": 13108,
"s": 13054,
"text": "-p flag sets the port binding from {host}:{container}"
},
{
"code": null,
"e": 13208,
"s": 13108,
"text": "-d flag run the container in detached mode, this maintains the container running in the background."
},
{
"code": null,
"e": 13358,
"s": 13208,
"text": "So now let’s create a bash file in our _docker_setup foleder called create-images.sh to automate the creation of all our microservices docker images."
},
{
"code": null,
"e": 13531,
"s": 13358,
"text": "Before we execute this script, we need to modify our start-service.sh that we have on each microservice and rename it to create-image.sh, so it can look like the following:"
},
{
"code": null,
"e": 13842,
"s": 13531,
"text": "#!/usr/bin/env bashdocker rm -f {name of the service}docker rmi {name of the service}docker image prunedocker volume prune# the previous commands are for removing existing containers, # and image, then we clean our environment and finally # we creat or re-build our imagedocker build -t {name of the service} ."
},
{
"code": null,
"e": 14158,
"s": 13842,
"text": "Publish our docker image ¿ 🤔 ? , Docker maintains a vast repository of images, called the Docker Hub, which you can use as starting points or as free storage for our own images. This is where we are pulling our node:7.5.0-alpine image to create our microservices images. ¿ But why do we need to publish our images ?"
},
{
"code": null,
"e": 14586,
"s": 14158,
"text": "Well because, later on the chapter we are going to create Docker Services, and this services will be deploy and replicate all over our Docker Swarm Cluster, and to start our services, the cluster nodes needs the image of the servcice to start the containers and if the image is not present locally it will search it in the docker hub and then will pull it to the host to have the image locally and be able to stat our services."
},
{
"code": null,
"e": 14716,
"s": 14586,
"text": "But first we need to create an account at the Docker Hub website, then we need to login in our shell doing the following command:"
},
{
"code": null,
"e": 14802,
"s": 14716,
"text": "$ docker login Username: ***** Password: ***** Login Succeeded"
},
{
"code": null,
"e": 14904,
"s": 14802,
"text": "Next we need to tag our images, to be able to reference them by name and push them to the docker hub."
},
{
"code": null,
"e": 15188,
"s": 14904,
"text": "Now that we have logged in, and we now the structure on how to tag our docker images, its time to modify our create-images.sh, so it can create our images, tag our images and push our images to the docker hub, all automatically for us, our bash file needs to look like the following."
},
{
"code": null,
"e": 15533,
"s": 15188,
"text": "This is a little bit of topic to docker steps, but we need a database to persist our data that our microservices uses, and in this step i won’t spent time to describe how to do it, i have already wrote an article on how to deploy a mongodb replica set cluster to docker, and i highly suggest you, to give it a look to my article if you haven’t."
},
{
"code": null,
"e": 15544,
"s": 15533,
"text": "medium.com"
},
{
"code": null,
"e": 15622,
"s": 15544,
"text": "Or skip this step and wait until you read step-7 .(and make some thug life 😎)"
},
{
"code": null,
"e": 15747,
"s": 15622,
"text": "Doing step 5 is highly important because if we haven’t our database up and running our docker services wont start correctly."
},
{
"code": null,
"e": 15976,
"s": 15747,
"text": "So now let’s create another file in our _docker_setup folder called start-services.sh this bash script will start all our microservices in the type of Docker Services, so that this services can scale up or scale down, as needed."
},
{
"code": null,
"e": 16391,
"s": 15976,
"text": "Now that our services is going to scale up and down, we are getting into trouble to call those services, but there is nothing the be afraid of, my dear readers, because, i said before that one of the benefits of creating a Docker swarm cluster, is that it setup for us behind the scenes a load balancer and docker is the responsible to handle which service to call when is requested. So let’s review our next file."
},
{
"code": null,
"e": 16587,
"s": 16391,
"text": "As you can see this file is very similar to our create-images.sh but this time we are calling the start-service.sh from every service, and now let’s see how is composed the start-service.sh file."
},
{
"code": null,
"e": 16747,
"s": 16587,
"text": "#!/usr/bin/env bashdocker service create --replicas 3 --name {service name} -l=apiRoute='{our api route}' -p {port binding} --env-file env {microservice image}"
},
{
"code": null,
"e": 16786,
"s": 16747,
"text": "Let’s look at the the service command:"
},
{
"code": null,
"e": 16841,
"s": 16786,
"text": "The docker service create command creates the service."
},
{
"code": null,
"e": 16896,
"s": 16841,
"text": "The --name flag names the service e.g. movies-service."
},
{
"code": null,
"e": 16968,
"s": 16896,
"text": "The --replicas flag specifies the desired state of 3 running instances."
},
{
"code": null,
"e": 17040,
"s": 16968,
"text": "The -l flag species that we can attach metadata e.g.apiRoute=\"/movies\"."
},
{
"code": null,
"e": 17110,
"s": 17040,
"text": "The -p flag specifies the port binding on the host and the container."
},
{
"code": null,
"e": 17182,
"s": 17110,
"text": "The -e flag specifies the can set to the service environment variables."
},
{
"code": null,
"e": 17233,
"s": 17182,
"text": "Well well well, its time to do the magic 🔮✨ folks."
},
{
"code": null,
"e": 17383,
"s": 17233,
"text": "To execute all our automated files that we have created, let’s create the final script that will do everything for us, because developers are lazy 🤓."
},
{
"code": null,
"e": 17551,
"s": 17383,
"text": "So we need to create this file at the root of the cinemas microservice project and we are going to call it the kraken.sh 🦑 just for fun and because is very powerful 😎."
},
{
"code": null,
"e": 17676,
"s": 17551,
"text": "Well it doesn’t have fancy programming inside, but what it does, is calling all our automated scripts for us and do our job."
},
{
"code": null,
"e": 17721,
"s": 17676,
"text": "Finally let’s execute it like the following."
},
{
"code": null,
"e": 17740,
"s": 17721,
"text": "$ bash < kraken.sh"
},
{
"code": null,
"e": 17902,
"s": 17740,
"text": "As simple as that, we have been doing so much modularity to simplify the process of creating a Docker Swarm Cluster, and start our Docker Services automatically."
},
{
"code": null,
"e": 18101,
"s": 17902,
"text": "“Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.” — Steve Jobs"
},
{
"code": null,
"e": 18320,
"s": 18101,
"text": "I have uploaded a video demonstration to see what happens when we execute the kraken.sh i speed it up the video a little bit, but the kraken process may take like 10 min more less depending on the host power to finish."
},
{
"code": null,
"e": 18444,
"s": 18320,
"text": "Finally we can check the status of our docker environment executing the following commands that appears on the image below."
},
{
"code": null,
"e": 18732,
"s": 18444,
"text": "As you can see some services are already replicated in our cluster, others doesn’t have even started, thats because the machines are pulling our images to start our services, and once our images are downloaded and our services are started we should se something like the following image."
},
{
"code": null,
"e": 19156,
"s": 18732,
"text": "So now our architecture looks like the following diagram, where all our microservices are created dinamically, replicated through all the cluster, and can be scale as needed, the only services that are created manually are our mongo containers and the api-gateways, why because they are attached to specifications of our host servers, mongo needs a persistent storage and our api needs to discover the host docker services."
},
{
"code": null,
"e": 19278,
"s": 19156,
"text": "Now let’s verify that our services are currently up and running, so we need to execute the commands like the image below."
},
{
"code": null,
"e": 19461,
"s": 19278,
"text": "And If we run a Docker Swarm visualizer, that are available on github, we can see how our services (containers) are distributed on our Docker swarm cluster, like the following image."
},
{
"code": null,
"e": 19664,
"s": 19461,
"text": "And if we scale down some services e.g. docker-machine ssh manager1 docker service scale movies-service=1, we can se how our services are redistributed on our Docker swarm cluster, like the image below."
},
{
"code": null,
"e": 19776,
"s": 19664,
"text": "We are almost done with our cinemas microservice configurations, and also with our cinemas microservice system."
},
{
"code": null,
"e": 19946,
"s": 19776,
"text": "It has been a very large article, but we have learned to much on how docker can fit with our development and also how can docker complement our system to be more robust."
},
{
"code": null,
"e": 20058,
"s": 19946,
"text": "There is a couple of things we still need to do, to get correctly set and ready to run our cinema microservice:"
},
{
"code": null,
"e": 20179,
"s": 20058,
"text": "we need to update the api-gateway, so that can discover now the docker services that are running to be able to do proxy."
},
{
"code": null,
"e": 20297,
"s": 20179,
"text": "we need to populate our database and for that you can go and check the commands at the github repository readme here."
},
{
"code": null,
"e": 20507,
"s": 20297,
"text": "In our API Gateway, we just need to change a few lines in our docker.js instead of calling the listContainers() function, we will call the listServices() function and set our routes with the provided services."
},
{
"code": null,
"e": 20749,
"s": 20507,
"text": "To not make this article more longer, you are welcome to check the complete code changes to the API Gateway, at the github repository, and if you have any question, as always you are welcome to send me a tweet or just put a comment below 😃📝."
},
{
"code": null,
"e": 21173,
"s": 20749,
"text": "Because our article wouldn’t be complete without making some testing to our system. Tests are fundamentally important because we can look to the system from different angles, with different perspectives and testing it with different expectations, the ultimate purpose of software testing is not to find bugs but to make the product qualitative. As a good testers, we are contributing in improvements of the product quality."
},
{
"code": null,
"e": 21258,
"s": 21173,
"text": "# we need to locate at the api-gateway folder and execute the test$ npm run int-test"
},
{
"code": null,
"e": 21305,
"s": 21258,
"text": "And we will have an output like the following."
},
{
"code": null,
"e": 21517,
"s": 21305,
"text": "Here we are calling our api-gateway services as you can see we are calling to different docker-machine ip and our api-gateway proxies our requests to our Docker Services, and finally our test passes correctly 😎."
},
{
"code": null,
"e": 21677,
"s": 21517,
"text": "Also i have recorded a jmeter stress test to our cinema microservice system deployed in our docker swarm cluster, so you can see what are the expected results."
},
{
"code": null,
"e": 21698,
"s": 21677,
"text": "What we have done..."
},
{
"code": null,
"e": 21987,
"s": 21698,
"text": "We’ve seen a lot of docker 🐋. We talked about what it is this whale, Docker, Docker-Machine, Docker-Swarm, Docker-Images, Docker-Hub, Docker-Services and how to make their appropriate configurations, how to set it up with an automation process and how does it fit with our cinemas system."
},
{
"code": null,
"e": 22268,
"s": 21987,
"text": "With docker we made our cinemas microservices and system more dynamically, fault tolerant, scalable and secure. But there is so much interesting things to see yet with docker, for example, Docker Network, Docker Compose, Docker plugins, etc... docker is an expanding devops world."
},
{
"code": null,
"e": 22657,
"s": 22268,
"text": "We’ve seen a lot of development in microservices with NodeJS, and we have seen how to implement this microservices with the Docker Ecosystem but there’s a lot more that we can do and learn, this is just a sneak peak for a little bit of more advance docker playground. I hope this has shown some of the interesting and useful things that you can use for Docker and NodeJS in your workflow."
},
{
"code": null,
"e": 22816,
"s": 22657,
"text": "I know that this article has become very large, but i think that its worth it to see an extra step, that will show us how to monitor our docker swarm cluster."
},
{
"code": null,
"e": 22923,
"s": 22816,
"text": "So to start monitoring our cluster we need to execute the following command in our manager1 docker-machine"
},
{
"code": null,
"e": 23035,
"s": 22923,
"text": "$ docker-machine ssh manager1 docker run --name rancher --restart=unless-stopped -p 9000:8080 -d rancher/server"
},
{
"code": null,
"e": 23146,
"s": 23035,
"text": "Then when the container is ready we need to visit the following url http://192.168.99.100:9000 in our browser."
},
{
"code": null,
"e": 23253,
"s": 23146,
"text": "Then the rancher gui, will give you through the setup, and finally we will be able to monitor our cluster."
},
{
"code": null,
"e": 23327,
"s": 23253,
"text": "And if we click in one of the hosts, we can see something like following."
},
{
"code": null,
"e": 23585,
"s": 23327,
"text": "Finally a have a recorded the super duper stress integration test so you can be able to see the results in video the result of all this configurations and how we can monitor our cluster via either graphic interface or console logs 😎 the console log rocks🤘🏽."
},
{
"code": null,
"e": 23662,
"s": 23585,
"text": "So we have seen the super power 💪🏽 that the blue whale 🐋 has to offer to us."
},
{
"code": null,
"e": 24019,
"s": 23662,
"text": "Ok so there is our cinemas microservice system almost complete, there is something missing, our cinemas microservice system wouldn’t be useful if we don’t develop that missing master piece, and that my friends, is the front end service that our final users will be interacting with our system 😎, and that web UI is the missing piece to complete our system."
},
{
"code": null,
"e": 24172,
"s": 24019,
"text": "Thanks for reading! I hope you find value in the article! If you did, punch that Recommend Button, recommend it to a friend, share it or read it again ."
},
{
"code": null,
"e": 24320,
"s": 24172,
"text": "In case you have questions on any aspect of this series or need my help in understanding something, feel free to tweet me or leave a comment below."
},
{
"code": null,
"e": 24455,
"s": 24320,
"text": "Let me remember you, this article is part of “Build a NodeJS cinema microservice” series so, next week i will publish another chapter."
},
{
"code": null,
"e": 24511,
"s": 24455,
"text": "So in the meantime, stay tuned, stay curious ✌🏼👨🏻💻👩🏻💻"
},
{
"code": null,
"e": 24535,
"s": 24511,
"text": "¡ Hasta la próxima ! 😁"
},
{
"code": null,
"e": 24608,
"s": 24535,
"text": "You can follow me at twitter @cramirez_92https://twitter.com/cramirez_92"
},
{
"code": null,
"e": 24678,
"s": 24608,
"text": "You can check the complete code of the article at the following link."
},
{
"code": null,
"e": 24689,
"s": 24678,
"text": "github.com"
},
{
"code": null,
"e": 24719,
"s": 24689,
"text": "How does docker services work"
},
{
"code": null,
"e": 24741,
"s": 24719,
"text": "Docker Swarm overview"
},
{
"code": null,
"e": 24755,
"s": 24741,
"text": "Docker GitHub"
},
{
"code": null,
"e": 24804,
"s": 24755,
"text": "Definitions From a Developer: What Is A Cluster?"
}
] |
Deep Learning With Weighted Cross Entropy Loss On Imbalanced Tabular Data Using FastAI | by Faiyaz Hasan | Towards Data Science | FastAI is an incredibly convenient and powerful machine learning library bringing Deep Learning (DL) to the masses. I was motivated to write this article while troubleshooting some issues related to training a model for a binary classification task. My objective is to walk you through the steps required to a build a simple and effective DL model using FastAI for a tabular, imbalanced dataset while avoiding the mistakes that I had made. The discussion in this article is organized according to the sections listed below.
DatasetSample CodeCode BreakdownComparison Of FastAI to PySpark ML & Scikit-LearnConclusion
Dataset
Sample Code
Code Breakdown
Comparison Of FastAI to PySpark ML & Scikit-Learn
Conclusion
The dataset comes from the context of ad conversions where the binary target variables 1 and 0 correspond to conversion success and failure. This proprietary dataset (no, I don’t own the rights) has some particularly interesting attributes due to its dimensions, class imbalance and rather weak relationship between the features and the target variable.
First, the dimensions of the data: this tabular dataset contains a fairly large number of records and categorical features that have a very high cardinality.
Note: In FastAI, categorical features are represented using embeddings which can improve classification performance on high cardinality features.
Second, the binary class labels are highly imbalanced since successful ad conversions are relatively rare. In this article we adapt to this constraint via an algorithm-level approach (weighted cross entropy loss functions) as opposed to a data-level approach (resampling).
Third, the relationship between the features and the target variable is rather weak. For example, a Logistic Regression model had a validation area under ROC curve of 0.74 after significant model tuning.
Dimensions: 17 features, 1 target variable, 3738937 rows
Binary target classes
Class imbalance ratio of 1:87
6 numerical features
8 categorical features
Categorical features have a combined cardinality of 44,000
This code was ran on a Jupyter Lab notebook on Google Cloud — AI Platform with the specs listed below.
4 N1-standard vCPUs, 15 GB RAM
1 NVIDIA Tesla P4 GPU
Environment: PyTorch 1.4
Operating System: Debian 9
The model training pipeline, which will be explained in the next section, is shown below.
Install both fastai and fastbook via the command terminal. For more details on the setup, checkout this link.
conda install -c fastai -c pytorch fastaigit clone https://github.com/fastai/fastbook.gitpip install -Uqq fastbook
Import the FastAI library and pandas into the notebook.
import pandas as pd from fastai.tabular.all import *
The column names had to be anonymized due to privacy reasons.
df = pd.read_csv('data/training.csv')# Categorical FeaturesCAT_NAMES = ['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7', 'col_8'] # Continuous FeaturesCONT_NAMES = ['col_9', 'col_10', 'col_11', 'col_12', 'col_13', 'col_14'] # Target VariableTARGET = 'target'
Change the data type of the binary target variable to category.
df[TARGET] = df[TARGET].astype('category')
Pitfall #1: If the target variable data type is left as a numeric value, FastAI/PyTorch will treat it as such and yield a runtime error.
Next, list the data preprocessors, training/validation set split and create the tabular dataloader.
# Data Processorsprocs = [Categorify, FillMissing, Normalize] # Training/Validation Dataset 80:20 Split splits = RandomSplitter(valid_pct=0.2)(range_of(df)) dls = TabularDataLoaders.from_df(df, y_names=TARGET, cat_names=CAT_NAMES, cont_names=CONT_NAMES, procs=procs, splits=splits)
Use dls.xs to see the transformed training data.
Construct Loss Function Weights
The class imbalances are used to create the weights for the cross entropy loss function ensuring that the majority class is down-weighted accordingly. The formula for the weights used here is the same as in scikit-learn and PySPark ML.
class_count_df = df.groupby(TARGET).count() n_0, n_1 = class_count_df.iloc[0, 0], class_count_df.iloc[1, 0] w_0 = (n_0 + n_1) / (2.0 * n_0)w_1 = (n_0 + n_1) / (2.0 * n_1) class_weights=torch.FloatTensor([w_0, w_1]).cuda()
Pitfall #2: Ensure that the class weights are converted to a float tensor and that cuda operations are enabled via .cuda(). Otherwise, you will get a type error.
TypeError: cannot assign 'list' object to buffer 'weight' (torch Tensor or None required)
Instantiate Area Under ROC Metric
roc_auc = RocAucBinary()
Pitfall #3: For binary class labels, use RocAucBinary() and NOT RocAuc() in order to avoid a value error.
ValueError: y should be a 1d array, got an array of shape (2000, 2) instead.
Instantiate Loss Function
loss_func = CrossEntropyLossFlat(weight=class_weights)
Pitfall #5: Use the FastAI cross entropy loss function as opposed to the PyTorch equivalent of torch.nn.CrossEntropyLoss() in order to avoid errors. The FastAI loss functions are listed here. Using the PyTorch cross entropy loss gave me the following runtime error.
RuntimeError: Expected object of scalar type Long but got scalar type Char for argument #2 'target' in call to _thnn_nll_loss_forward
Instantiate Learner
Use tabular_learner in FastAI to easily instantiate an architecture.
learn = tabular_learner(dls, layers=[500, 250], loss_func=loss_func, metrics=roc_auc)
Double check that learn is using the correct loss function:
learn.loss_func Out [1]: FlattenedLoss of CrossEntropyLoss()
Train the model over the desired number of epochs.
learn.fit_one_cycle(3)
The performance metric and the loss function values for the training and validation set is shown below.
That’s great! With minimal tuning, the FastAI model is performing better than the models built painstakingly using PySpark and Scikit-Learn.
In this section , we compare model performance and computation time of these three ML libraries.
Note: While the neural network performed well without extensive hyper-parameter tuning, PySpark ML and Scikit-Learn did not. As a result, I have added those times since they were relevant to training a descent model.
Model Training Time
FastAI — 6 minutesPySpark ML — 0.7 seconds + 38 minutes for hyper-parameter tuningScikit-Learn — 36 seconds + 8 minutes for hyper-parameter tuning (on a subsample of the data)
FastAI — 6 minutes
PySpark ML — 0.7 seconds + 38 minutes for hyper-parameter tuning
Scikit-Learn — 36 seconds + 8 minutes for hyper-parameter tuning (on a subsample of the data)
Area Under ROC Curve
FastAI — 0.75PySpark ML — 0.74Scikit-Learn — 0.73
FastAI — 0.75
PySpark ML — 0.74
Scikit-Learn — 0.73
For more details, check out my Github repo.
In this article, we saw the power of FastAI when it comes to quickly building DL models. Before playing around with FastAI, I would put off using neural networks until I had already tried Logistic Regression, Random Forests etc. because of the stigma that neural networks are difficult to tune and computationally expensive. However, with increased accessibility to GPUs via Google AI Platform Notebooks and the layered FastAI approach to deep learning, now it will surely be one of the first tools I reach for when it comes to classification tasks on large, complex datasets. | [
{
"code": null,
"e": 696,
"s": 172,
"text": "FastAI is an incredibly convenient and powerful machine learning library bringing Deep Learning (DL) to the masses. I was motivated to write this article while troubleshooting some issues related to training a model for a binary classification task. My objective is to walk you through the steps required to a build a simple and effective DL model using FastAI for a tabular, imbalanced dataset while avoiding the mistakes that I had made. The discussion in this article is organized according to the sections listed below."
},
{
"code": null,
"e": 788,
"s": 696,
"text": "DatasetSample CodeCode BreakdownComparison Of FastAI to PySpark ML & Scikit-LearnConclusion"
},
{
"code": null,
"e": 796,
"s": 788,
"text": "Dataset"
},
{
"code": null,
"e": 808,
"s": 796,
"text": "Sample Code"
},
{
"code": null,
"e": 823,
"s": 808,
"text": "Code Breakdown"
},
{
"code": null,
"e": 873,
"s": 823,
"text": "Comparison Of FastAI to PySpark ML & Scikit-Learn"
},
{
"code": null,
"e": 884,
"s": 873,
"text": "Conclusion"
},
{
"code": null,
"e": 1238,
"s": 884,
"text": "The dataset comes from the context of ad conversions where the binary target variables 1 and 0 correspond to conversion success and failure. This proprietary dataset (no, I don’t own the rights) has some particularly interesting attributes due to its dimensions, class imbalance and rather weak relationship between the features and the target variable."
},
{
"code": null,
"e": 1396,
"s": 1238,
"text": "First, the dimensions of the data: this tabular dataset contains a fairly large number of records and categorical features that have a very high cardinality."
},
{
"code": null,
"e": 1542,
"s": 1396,
"text": "Note: In FastAI, categorical features are represented using embeddings which can improve classification performance on high cardinality features."
},
{
"code": null,
"e": 1815,
"s": 1542,
"text": "Second, the binary class labels are highly imbalanced since successful ad conversions are relatively rare. In this article we adapt to this constraint via an algorithm-level approach (weighted cross entropy loss functions) as opposed to a data-level approach (resampling)."
},
{
"code": null,
"e": 2019,
"s": 1815,
"text": "Third, the relationship between the features and the target variable is rather weak. For example, a Logistic Regression model had a validation area under ROC curve of 0.74 after significant model tuning."
},
{
"code": null,
"e": 2076,
"s": 2019,
"text": "Dimensions: 17 features, 1 target variable, 3738937 rows"
},
{
"code": null,
"e": 2098,
"s": 2076,
"text": "Binary target classes"
},
{
"code": null,
"e": 2128,
"s": 2098,
"text": "Class imbalance ratio of 1:87"
},
{
"code": null,
"e": 2149,
"s": 2128,
"text": "6 numerical features"
},
{
"code": null,
"e": 2172,
"s": 2149,
"text": "8 categorical features"
},
{
"code": null,
"e": 2231,
"s": 2172,
"text": "Categorical features have a combined cardinality of 44,000"
},
{
"code": null,
"e": 2334,
"s": 2231,
"text": "This code was ran on a Jupyter Lab notebook on Google Cloud — AI Platform with the specs listed below."
},
{
"code": null,
"e": 2365,
"s": 2334,
"text": "4 N1-standard vCPUs, 15 GB RAM"
},
{
"code": null,
"e": 2387,
"s": 2365,
"text": "1 NVIDIA Tesla P4 GPU"
},
{
"code": null,
"e": 2412,
"s": 2387,
"text": "Environment: PyTorch 1.4"
},
{
"code": null,
"e": 2439,
"s": 2412,
"text": "Operating System: Debian 9"
},
{
"code": null,
"e": 2529,
"s": 2439,
"text": "The model training pipeline, which will be explained in the next section, is shown below."
},
{
"code": null,
"e": 2639,
"s": 2529,
"text": "Install both fastai and fastbook via the command terminal. For more details on the setup, checkout this link."
},
{
"code": null,
"e": 2754,
"s": 2639,
"text": "conda install -c fastai -c pytorch fastaigit clone https://github.com/fastai/fastbook.gitpip install -Uqq fastbook"
},
{
"code": null,
"e": 2810,
"s": 2754,
"text": "Import the FastAI library and pandas into the notebook."
},
{
"code": null,
"e": 2863,
"s": 2810,
"text": "import pandas as pd from fastai.tabular.all import *"
},
{
"code": null,
"e": 2925,
"s": 2863,
"text": "The column names had to be anonymized due to privacy reasons."
},
{
"code": null,
"e": 3225,
"s": 2925,
"text": "df = pd.read_csv('data/training.csv')# Categorical FeaturesCAT_NAMES = ['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7', 'col_8'] # Continuous FeaturesCONT_NAMES = ['col_9', 'col_10', 'col_11', 'col_12', 'col_13', 'col_14'] # Target VariableTARGET = 'target'"
},
{
"code": null,
"e": 3289,
"s": 3225,
"text": "Change the data type of the binary target variable to category."
},
{
"code": null,
"e": 3332,
"s": 3289,
"text": "df[TARGET] = df[TARGET].astype('category')"
},
{
"code": null,
"e": 3469,
"s": 3332,
"text": "Pitfall #1: If the target variable data type is left as a numeric value, FastAI/PyTorch will treat it as such and yield a runtime error."
},
{
"code": null,
"e": 3569,
"s": 3469,
"text": "Next, list the data preprocessors, training/validation set split and create the tabular dataloader."
},
{
"code": null,
"e": 4185,
"s": 3569,
"text": "# Data Processorsprocs = [Categorify, FillMissing, Normalize] # Training/Validation Dataset 80:20 Split splits = RandomSplitter(valid_pct=0.2)(range_of(df)) dls = TabularDataLoaders.from_df(df, y_names=TARGET, cat_names=CAT_NAMES, cont_names=CONT_NAMES, procs=procs, splits=splits)"
},
{
"code": null,
"e": 4234,
"s": 4185,
"text": "Use dls.xs to see the transformed training data."
},
{
"code": null,
"e": 4266,
"s": 4234,
"text": "Construct Loss Function Weights"
},
{
"code": null,
"e": 4502,
"s": 4266,
"text": "The class imbalances are used to create the weights for the cross entropy loss function ensuring that the majority class is down-weighted accordingly. The formula for the weights used here is the same as in scikit-learn and PySPark ML."
},
{
"code": null,
"e": 4724,
"s": 4502,
"text": "class_count_df = df.groupby(TARGET).count() n_0, n_1 = class_count_df.iloc[0, 0], class_count_df.iloc[1, 0] w_0 = (n_0 + n_1) / (2.0 * n_0)w_1 = (n_0 + n_1) / (2.0 * n_1) class_weights=torch.FloatTensor([w_0, w_1]).cuda()"
},
{
"code": null,
"e": 4886,
"s": 4724,
"text": "Pitfall #2: Ensure that the class weights are converted to a float tensor and that cuda operations are enabled via .cuda(). Otherwise, you will get a type error."
},
{
"code": null,
"e": 4976,
"s": 4886,
"text": "TypeError: cannot assign 'list' object to buffer 'weight' (torch Tensor or None required)"
},
{
"code": null,
"e": 5010,
"s": 4976,
"text": "Instantiate Area Under ROC Metric"
},
{
"code": null,
"e": 5035,
"s": 5010,
"text": "roc_auc = RocAucBinary()"
},
{
"code": null,
"e": 5141,
"s": 5035,
"text": "Pitfall #3: For binary class labels, use RocAucBinary() and NOT RocAuc() in order to avoid a value error."
},
{
"code": null,
"e": 5218,
"s": 5141,
"text": "ValueError: y should be a 1d array, got an array of shape (2000, 2) instead."
},
{
"code": null,
"e": 5244,
"s": 5218,
"text": "Instantiate Loss Function"
},
{
"code": null,
"e": 5299,
"s": 5244,
"text": "loss_func = CrossEntropyLossFlat(weight=class_weights)"
},
{
"code": null,
"e": 5565,
"s": 5299,
"text": "Pitfall #5: Use the FastAI cross entropy loss function as opposed to the PyTorch equivalent of torch.nn.CrossEntropyLoss() in order to avoid errors. The FastAI loss functions are listed here. Using the PyTorch cross entropy loss gave me the following runtime error."
},
{
"code": null,
"e": 5699,
"s": 5565,
"text": "RuntimeError: Expected object of scalar type Long but got scalar type Char for argument #2 'target' in call to _thnn_nll_loss_forward"
},
{
"code": null,
"e": 5719,
"s": 5699,
"text": "Instantiate Learner"
},
{
"code": null,
"e": 5788,
"s": 5719,
"text": "Use tabular_learner in FastAI to easily instantiate an architecture."
},
{
"code": null,
"e": 5949,
"s": 5788,
"text": "learn = tabular_learner(dls, layers=[500, 250], loss_func=loss_func, metrics=roc_auc)"
},
{
"code": null,
"e": 6009,
"s": 5949,
"text": "Double check that learn is using the correct loss function:"
},
{
"code": null,
"e": 6070,
"s": 6009,
"text": "learn.loss_func Out [1]: FlattenedLoss of CrossEntropyLoss()"
},
{
"code": null,
"e": 6121,
"s": 6070,
"text": "Train the model over the desired number of epochs."
},
{
"code": null,
"e": 6144,
"s": 6121,
"text": "learn.fit_one_cycle(3)"
},
{
"code": null,
"e": 6248,
"s": 6144,
"text": "The performance metric and the loss function values for the training and validation set is shown below."
},
{
"code": null,
"e": 6389,
"s": 6248,
"text": "That’s great! With minimal tuning, the FastAI model is performing better than the models built painstakingly using PySpark and Scikit-Learn."
},
{
"code": null,
"e": 6486,
"s": 6389,
"text": "In this section , we compare model performance and computation time of these three ML libraries."
},
{
"code": null,
"e": 6703,
"s": 6486,
"text": "Note: While the neural network performed well without extensive hyper-parameter tuning, PySpark ML and Scikit-Learn did not. As a result, I have added those times since they were relevant to training a descent model."
},
{
"code": null,
"e": 6723,
"s": 6703,
"text": "Model Training Time"
},
{
"code": null,
"e": 6899,
"s": 6723,
"text": "FastAI — 6 minutesPySpark ML — 0.7 seconds + 38 minutes for hyper-parameter tuningScikit-Learn — 36 seconds + 8 minutes for hyper-parameter tuning (on a subsample of the data)"
},
{
"code": null,
"e": 6918,
"s": 6899,
"text": "FastAI — 6 minutes"
},
{
"code": null,
"e": 6983,
"s": 6918,
"text": "PySpark ML — 0.7 seconds + 38 minutes for hyper-parameter tuning"
},
{
"code": null,
"e": 7077,
"s": 6983,
"text": "Scikit-Learn — 36 seconds + 8 minutes for hyper-parameter tuning (on a subsample of the data)"
},
{
"code": null,
"e": 7098,
"s": 7077,
"text": "Area Under ROC Curve"
},
{
"code": null,
"e": 7148,
"s": 7098,
"text": "FastAI — 0.75PySpark ML — 0.74Scikit-Learn — 0.73"
},
{
"code": null,
"e": 7162,
"s": 7148,
"text": "FastAI — 0.75"
},
{
"code": null,
"e": 7180,
"s": 7162,
"text": "PySpark ML — 0.74"
},
{
"code": null,
"e": 7200,
"s": 7180,
"text": "Scikit-Learn — 0.73"
},
{
"code": null,
"e": 7244,
"s": 7200,
"text": "For more details, check out my Github repo."
}
] |
C# Program for Activity Selection Problem | Greedy Algo-1 - GeeksforGeeks | 22 Aug, 2019
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.Example:
Example 1 : Consider the following 3 activities sorted
by finish time.
start[] = {10, 12, 20};
finish[] = {20, 25, 30};
A person can perform at most two activities. The
maximum set of activities that can be executed
is {0, 2} [ These are indexes in start[] and
finish[] ]
Example 2 : Consider the following 6 activities
sorted by by finish time.
start[] = {1, 3, 0, 5, 8, 5};
finish[] = {2, 4, 6, 7, 9, 9};
A person can perform at most four activities. The
maximum set of activities that can be executed
is {0, 1, 3, 4} [ These are indexes in start[] and
finish[] ]
C#
// The following implementation assumes// that the activities are already sorted// according to their finish timeusing System; class GFG { // Prints a maximum set of activities // that can be done by a single // person, one at a time. // n --> Total number of activities // s[] --> An array that contains start // time of all activities // f[] --> An array that contains finish // time of all activities public static void printMaxActivities(int[] s, int[] f, int n) { int i, j; Console.Write("Following activities are selected : "); // The first activity always gets selected i = 0; Console.Write(i + " "); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { Console.Write(j + " "); i = j; } } } // Driver Code public static void Main() { int[] s = { 1, 3, 0, 5, 8, 5 }; int[] f = { 2, 4, 6, 7, 9, 9 }; int n = s.Length; printMaxActivities(s, f, n); }} // This code is contributed// by ChitraNayal
Following activities are selected : 0 1 3 4
Please refer complete article on Activity Selection Problem | Greedy Algo-1 for more details!
nidhi_biet
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Program to Demonstrate the IList Interface
How to Remove Duplicate Values From an Array in C#?
C# Program to Read and Write a Byte Array to File using FileStream Class
How to Calculate the Code Execution Time in C#?
C# Program to Check a Specified Type is an Enum or Not
How to Sort Object Array By Specific Property in C#?
C# Program to Sort a List of Integers Using the LINQ OrderBy() Method
C# Program to Sort a List of String Names Using the LINQ OrderBy() Method
C# Program to Delete an Empty and a Non-Empty Directory
C# Program to Calculate the Sum of Array Elements using the LINQ Aggregate() Method | [
{
"code": null,
"e": 24893,
"s": 24865,
"text": "\n22 Aug, 2019"
},
{
"code": null,
"e": 25114,
"s": 24893,
"text": "You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.Example:"
},
{
"code": null,
"e": 25715,
"s": 25114,
"text": "Example 1 : Consider the following 3 activities sorted\nby finish time.\n start[] = {10, 12, 20};\n finish[] = {20, 25, 30};\nA person can perform at most two activities. The \nmaximum set of activities that can be executed \nis {0, 2} [ These are indexes in start[] and \nfinish[] ]\n\nExample 2 : Consider the following 6 activities \nsorted by by finish time.\n start[] = {1, 3, 0, 5, 8, 5};\n finish[] = {2, 4, 6, 7, 9, 9};\nA person can perform at most four activities. The \nmaximum set of activities that can be executed \nis {0, 1, 3, 4} [ These are indexes in start[] and \nfinish[] ]\n"
},
{
"code": null,
"e": 25718,
"s": 25715,
"text": "C#"
},
{
"code": "// The following implementation assumes// that the activities are already sorted// according to their finish timeusing System; class GFG { // Prints a maximum set of activities // that can be done by a single // person, one at a time. // n --> Total number of activities // s[] --> An array that contains start // time of all activities // f[] --> An array that contains finish // time of all activities public static void printMaxActivities(int[] s, int[] f, int n) { int i, j; Console.Write(\"Following activities are selected : \"); // The first activity always gets selected i = 0; Console.Write(i + \" \"); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { Console.Write(j + \" \"); i = j; } } } // Driver Code public static void Main() { int[] s = { 1, 3, 0, 5, 8, 5 }; int[] f = { 2, 4, 6, 7, 9, 9 }; int n = s.Length; printMaxActivities(s, f, n); }} // This code is contributed// by ChitraNayal",
"e": 27043,
"s": 25718,
"text": null
},
{
"code": null,
"e": 27088,
"s": 27043,
"text": "Following activities are selected : 0 1 3 4\n"
},
{
"code": null,
"e": 27182,
"s": 27088,
"text": "Please refer complete article on Activity Selection Problem | Greedy Algo-1 for more details!"
},
{
"code": null,
"e": 27193,
"s": 27182,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27205,
"s": 27193,
"text": "C# Programs"
},
{
"code": null,
"e": 27303,
"s": 27205,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27312,
"s": 27303,
"text": "Comments"
},
{
"code": null,
"e": 27325,
"s": 27312,
"text": "Old Comments"
},
{
"code": null,
"e": 27371,
"s": 27325,
"text": "C# Program to Demonstrate the IList Interface"
},
{
"code": null,
"e": 27423,
"s": 27371,
"text": "How to Remove Duplicate Values From an Array in C#?"
},
{
"code": null,
"e": 27496,
"s": 27423,
"text": "C# Program to Read and Write a Byte Array to File using FileStream Class"
},
{
"code": null,
"e": 27544,
"s": 27496,
"text": "How to Calculate the Code Execution Time in C#?"
},
{
"code": null,
"e": 27599,
"s": 27544,
"text": "C# Program to Check a Specified Type is an Enum or Not"
},
{
"code": null,
"e": 27652,
"s": 27599,
"text": "How to Sort Object Array By Specific Property in C#?"
},
{
"code": null,
"e": 27722,
"s": 27652,
"text": "C# Program to Sort a List of Integers Using the LINQ OrderBy() Method"
},
{
"code": null,
"e": 27796,
"s": 27722,
"text": "C# Program to Sort a List of String Names Using the LINQ OrderBy() Method"
},
{
"code": null,
"e": 27852,
"s": 27796,
"text": "C# Program to Delete an Empty and a Non-Empty Directory"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.