title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Create Distinct Color Palette in R - GeeksforGeeks
|
23 May, 2021
In this article, we will discuss how to create a distinct color palette in R Programming Language. There are a number of ways to create color palettes in R programming, all such methods are discussed below.
We’ll be using a package named grDevices, stands for graphics Devices, for making distinct color palettes in the first method. Here we’ll be using the colors function from the grDevices to make our palette.
Using colors() function:
In this example we will make a pie chart using this very package. So, first we’ll be mentioning the number of colors, which we want in the palette. Then we’ll use the colors() function of this package, which contains a wide range of HCL(hue-chroma-luminance) based colors.
Example:
R
# number of colors in the paletteno_of_colors <- 10 # applying the colors function from # grDevices packagecolor_palette <- grDevices::colors() # optional, for printing the hex # color codescolor_palette # pie function for drawing a pie chartpie(rep(1, no_of_colors), radius = 0.8, col = color_palette, main = "Color Palette using colors function")
Output:
Now, let’s say we wish to create a coloraturas’ palette of only Green color and its shades. We shall be following the above steps as usual for making this palette too, but the only change is that, we’ll be using the grep command here. grep is used to search or matches to argument pattern within each element of a character vector: they differ in the format of and amount of detail in the results.
Syntax:
grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE)
Example:
R
# number of colors in the paletteno_of_colors <- 20 # applying the colors functioncolor_palette <- grDevices::colors() # prints all hex color codescolor_palette # grep command for matching the # pattern(character string --> green), palette <- color_palette[grep( "green", grDevices::colors())] # sample coloursgreen_palette <- sample(palette, no_of_colors) # the list of the colours, which will # show up in the palettegreen_palette # shows the created palettepie(rep(1, no_of_colors), col = green_palette, main = "Green and its shades")
Output:
Using rainbow()
Here we’ll be making the color palette using the rainbow() function from grDevices package. rainbow() function is an in-built color palette which can be used in order to instantly generate some color vectors of desired length as per the parameter, and it returns the hexadecimal code of the colo available.
Syntax:
rainbow(variable name which stores the number of colors)
The entire process is just the same as before, only that we are using rainbow function over here.
Example:
R
# no. of colours in the paletteno_of_colors <- 15 # applying the rainbow functioncolorful_palette <- rainbow(no_of_colors) # prints the hex color codescolorful_palette # creates a pie chart of rainbow colourspie(rep(1, no_of_colors), col = colorful_palette, main = "Rainbow Palette")
Output
Viridis package is a default color maps. It’s a series of color maps that are specially designed to improve graph readability for someone with common forms of color vision deficiency or color blindness.
This particular package consists of 8 color scales: “viridis”, being the topic name, and other such options with similar properties, which are listed below.
-> “magma”, –> option A
->“inferno”, –> option B
->“plasma”, –> option C
-> “viridis” –> default option D
->“cividis”, –> option E
-> “rocket”, –> option F
-> “mako”, –> option G
-> “turbo” –> option H
This viridis scale is for better understanding the color types, mentioned with their options.
Syntax:
viridis_pal(option = “option”)(variable storing the number of colors)
Example:
R
# installation of the viridis packageinstall.packages("viridis") # loading of the librarylibrary("viridis") # it may happen that the above 2 # lines of code pops out an error# saying viridisLite has to loaded# so to avoid that do load that # package toolibrary("viridisLite") # number of colors in the paletteno_of_colors <- 10 # options represent the color types, # there are altogether 8 options.palette <- viridis_pal(option = "D")(no_of_colors) # hex color codespalette # represents colors in a pie chart mannerpie(rep(1, no_of_colors), col = palette, main = "viridis palette")
Output:
Also, if we wish to change the color pattern type of this palette, then we need to change the option(anything within A to H). Every part of the above code will remain the same except the option.
Example:
R
# loading of the librarylibrary("viridis") # it may happen that the above# 2 lines of code pops out an# error saying viridisLite has # to loaded so to avoid that do# load that package toolibrary("viridisLite") # number of colors in the paletteno_of_colors <- 10 # option A --> magmapalette <- viridis_pal(option = "A")(no_of_colors) # hex color codespalette # represents colors in a pie chart mannerpie(rep(1, no_of_colors), col = palette, main = "magma palette")
Output:
randomcoloR is an R language package for generating attractive and distinctive colors. The function distictColorPalette() generates optimally recognizable colors.
Syntax:
distictColorPalette(variable having the number of colors stored)
Example:
R
# installationinstall.packages("randomcoloR")library("randomcoloR") # no. of colours in the paletteno_of_colors <- 15 # sample colorspalette <- distinctColorPalette(no_of_colors) # hex color codespalette # colors in the pie chartpie(rep(1, no_of_colors), col = palette, main = "palette using randomcoloR package")
Output:
This package creates nice looking color palettes, especially for thematic maps.
brewer.pal() makes the color palettes from ColorBrewer available as R palettes.
Syntax:
brewer.pal(n, name)
Parameter:
n: Number of different colors in the palette, minimum 3, maximum depending on palette.
name: A palette name from the lists below.
display.brewer.pal() displays the selected palette in a graphics window.
Syntax:
display.brewer.pal(n, name)
Parameter:
n: Number of different colors in the palette, minimum 3, maximum depending on palette.
name: A palette name from the lists below.
display.brewer.all() displays a few palettes simultaneously in a graphics window.
Syntax:
display.brewer.all(n=NULL, type=”all”, select=NULL, exact.n=TRUE, colorblindFriendly=FALSE)
Parameter:
n: Number of different colors in the palette, minimum 3, maximum depending on palette.
name: A palette name from the lists below.
type: One of the string “div”, “qual”, “seq”, or “all”.
select: A list of names of existing palettes
exact.n: If TRUE, only display palettes with a color number given by n.
colorblindFriendly: if TRUE, display only colorblind friendly palettes.
brewer.pal.info returns information about the available palettes as a dataframe. brewer.pal.info is not a function, it is a variable. This might change in the future.
rownames Retrieve or set the row or column names of a matrix-like object.
Syntax:
rownames(x) <- value
There are 3 types of palettes namely: sequential, diverging, and qualitative.
Sequential palettes are suited to ordered data that progress from low to high. Lightness steps dominate the look of these schemes, with light colors for low data values to dark colors for high data values.
R
display.brewer.all(type="seq")
Output:
Diverging palettes put equal emphasis on mid-range critical values and extremes at both ends of the data range. The critical class or break in the middle of the legend is emphasized with light colors and low and high extremes are emphasized with dark colors that have contrasting hues.
R
display.brewer.all(type="div")
Output:
Qualitative palettes do not imply magnitude differences between legend classes, and hues are used to create the primary visual differences between classes. Qualitative schemes are best suited to representing nominal or categorical data.
R
display.brewer.all(type="qual")
Output:
Example:
R
# installation of the package RColorBrewerinstall.packages("RColorBrewer") # loading of the packagelibrary("RColorBrewer") # extraction of color info# qual --> Qualitative color palettepalette5 <- brewer.pal.info[brewer.pal.info$category == "qual",] # create vector with all colorspalette <- unlist(mapply(brewer.pal, palette5$maxcolors, rownames(palette5)))palette # sample colorspalette_palette <- sample(palette, no_of_colors) # colors with their hex codespalette_palette # prints the pie chartpie(rep(1, no_of_colors), col = palette_palette, main = "RColorBrewer Palette")
Output:
.
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 25059,
"s": 24851,
"text": "In this article, we will discuss how to create a distinct color palette in R Programming Language. There are a number of ways to create color palettes in R programming, all such methods are discussed below. "
},
{
"code": null,
"e": 25266,
"s": 25059,
"text": "We’ll be using a package named grDevices, stands for graphics Devices, for making distinct color palettes in the first method. Here we’ll be using the colors function from the grDevices to make our palette."
},
{
"code": null,
"e": 25292,
"s": 25266,
"text": "Using colors() function: "
},
{
"code": null,
"e": 25565,
"s": 25292,
"text": "In this example we will make a pie chart using this very package. So, first we’ll be mentioning the number of colors, which we want in the palette. Then we’ll use the colors() function of this package, which contains a wide range of HCL(hue-chroma-luminance) based colors."
},
{
"code": null,
"e": 25574,
"s": 25565,
"text": "Example:"
},
{
"code": null,
"e": 25576,
"s": 25574,
"text": "R"
},
{
"code": "# number of colors in the paletteno_of_colors <- 10 # applying the colors function from # grDevices packagecolor_palette <- grDevices::colors() # optional, for printing the hex # color codescolor_palette # pie function for drawing a pie chartpie(rep(1, no_of_colors), radius = 0.8, col = color_palette, main = \"Color Palette using colors function\")",
"e": 25964,
"s": 25576,
"text": null
},
{
"code": null,
"e": 25972,
"s": 25964,
"text": "Output:"
},
{
"code": null,
"e": 26370,
"s": 25972,
"text": "Now, let’s say we wish to create a coloraturas’ palette of only Green color and its shades. We shall be following the above steps as usual for making this palette too, but the only change is that, we’ll be using the grep command here. grep is used to search or matches to argument pattern within each element of a character vector: they differ in the format of and amount of detail in the results."
},
{
"code": null,
"e": 26378,
"s": 26370,
"text": "Syntax:"
},
{
"code": null,
"e": 26496,
"s": 26378,
"text": "grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE)"
},
{
"code": null,
"e": 26505,
"s": 26496,
"text": "Example:"
},
{
"code": null,
"e": 26507,
"s": 26505,
"text": "R"
},
{
"code": "# number of colors in the paletteno_of_colors <- 20 # applying the colors functioncolor_palette <- grDevices::colors() # prints all hex color codescolor_palette # grep command for matching the # pattern(character string --> green), palette <- color_palette[grep( \"green\", grDevices::colors())] # sample coloursgreen_palette <- sample(palette, no_of_colors) # the list of the colours, which will # show up in the palettegreen_palette # shows the created palettepie(rep(1, no_of_colors), col = green_palette, main = \"Green and its shades\")",
"e": 27137,
"s": 26507,
"text": null
},
{
"code": null,
"e": 27145,
"s": 27137,
"text": "Output:"
},
{
"code": null,
"e": 27161,
"s": 27145,
"text": "Using rainbow()"
},
{
"code": null,
"e": 27468,
"s": 27161,
"text": "Here we’ll be making the color palette using the rainbow() function from grDevices package. rainbow() function is an in-built color palette which can be used in order to instantly generate some color vectors of desired length as per the parameter, and it returns the hexadecimal code of the colo available."
},
{
"code": null,
"e": 27476,
"s": 27468,
"text": "Syntax:"
},
{
"code": null,
"e": 27533,
"s": 27476,
"text": "rainbow(variable name which stores the number of colors)"
},
{
"code": null,
"e": 27631,
"s": 27533,
"text": "The entire process is just the same as before, only that we are using rainbow function over here."
},
{
"code": null,
"e": 27640,
"s": 27631,
"text": "Example:"
},
{
"code": null,
"e": 27642,
"s": 27640,
"text": "R"
},
{
"code": "# no. of colours in the paletteno_of_colors <- 15 # applying the rainbow functioncolorful_palette <- rainbow(no_of_colors) # prints the hex color codescolorful_palette # creates a pie chart of rainbow colourspie(rep(1, no_of_colors), col = colorful_palette, main = \"Rainbow Palette\")",
"e": 27933,
"s": 27642,
"text": null
},
{
"code": null,
"e": 27940,
"s": 27933,
"text": "Output"
},
{
"code": null,
"e": 28143,
"s": 27940,
"text": "Viridis package is a default color maps. It’s a series of color maps that are specially designed to improve graph readability for someone with common forms of color vision deficiency or color blindness."
},
{
"code": null,
"e": 28300,
"s": 28143,
"text": "This particular package consists of 8 color scales: “viridis”, being the topic name, and other such options with similar properties, which are listed below."
},
{
"code": null,
"e": 28324,
"s": 28300,
"text": "-> “magma”, –> option A"
},
{
"code": null,
"e": 28349,
"s": 28324,
"text": "->“inferno”, –> option B"
},
{
"code": null,
"e": 28373,
"s": 28349,
"text": "->“plasma”, –> option C"
},
{
"code": null,
"e": 28406,
"s": 28373,
"text": "-> “viridis” –> default option D"
},
{
"code": null,
"e": 28431,
"s": 28406,
"text": "->“cividis”, –> option E"
},
{
"code": null,
"e": 28456,
"s": 28431,
"text": "-> “rocket”, –> option F"
},
{
"code": null,
"e": 28479,
"s": 28456,
"text": "-> “mako”, –> option G"
},
{
"code": null,
"e": 28502,
"s": 28479,
"text": "-> “turbo” –> option H"
},
{
"code": null,
"e": 28596,
"s": 28502,
"text": "This viridis scale is for better understanding the color types, mentioned with their options."
},
{
"code": null,
"e": 28604,
"s": 28596,
"text": "Syntax:"
},
{
"code": null,
"e": 28674,
"s": 28604,
"text": "viridis_pal(option = “option”)(variable storing the number of colors)"
},
{
"code": null,
"e": 28683,
"s": 28674,
"text": "Example:"
},
{
"code": null,
"e": 28685,
"s": 28683,
"text": "R"
},
{
"code": "# installation of the viridis packageinstall.packages(\"viridis\") # loading of the librarylibrary(\"viridis\") # it may happen that the above 2 # lines of code pops out an error# saying viridisLite has to loaded# so to avoid that do load that # package toolibrary(\"viridisLite\") # number of colors in the paletteno_of_colors <- 10 # options represent the color types, # there are altogether 8 options.palette <- viridis_pal(option = \"D\")(no_of_colors) # hex color codespalette # represents colors in a pie chart mannerpie(rep(1, no_of_colors), col = palette, main = \"viridis palette\")",
"e": 29273,
"s": 28685,
"text": null
},
{
"code": null,
"e": 29281,
"s": 29273,
"text": "Output:"
},
{
"code": null,
"e": 29476,
"s": 29281,
"text": "Also, if we wish to change the color pattern type of this palette, then we need to change the option(anything within A to H). Every part of the above code will remain the same except the option."
},
{
"code": null,
"e": 29485,
"s": 29476,
"text": "Example:"
},
{
"code": null,
"e": 29487,
"s": 29485,
"text": "R"
},
{
"code": "# loading of the librarylibrary(\"viridis\") # it may happen that the above# 2 lines of code pops out an# error saying viridisLite has # to loaded so to avoid that do# load that package toolibrary(\"viridisLite\") # number of colors in the paletteno_of_colors <- 10 # option A --> magmapalette <- viridis_pal(option = \"A\")(no_of_colors) # hex color codespalette # represents colors in a pie chart mannerpie(rep(1, no_of_colors), col = palette, main = \"magma palette\")",
"e": 29956,
"s": 29487,
"text": null
},
{
"code": null,
"e": 29964,
"s": 29956,
"text": "Output:"
},
{
"code": null,
"e": 30127,
"s": 29964,
"text": "randomcoloR is an R language package for generating attractive and distinctive colors. The function distictColorPalette() generates optimally recognizable colors."
},
{
"code": null,
"e": 30135,
"s": 30127,
"text": "Syntax:"
},
{
"code": null,
"e": 30200,
"s": 30135,
"text": "distictColorPalette(variable having the number of colors stored)"
},
{
"code": null,
"e": 30209,
"s": 30200,
"text": "Example:"
},
{
"code": null,
"e": 30211,
"s": 30209,
"text": "R"
},
{
"code": "# installationinstall.packages(\"randomcoloR\")library(\"randomcoloR\") # no. of colours in the paletteno_of_colors <- 15 # sample colorspalette <- distinctColorPalette(no_of_colors) # hex color codespalette # colors in the pie chartpie(rep(1, no_of_colors), col = palette, main = \"palette using randomcoloR package\")",
"e": 30538,
"s": 30211,
"text": null
},
{
"code": null,
"e": 30546,
"s": 30538,
"text": "Output:"
},
{
"code": null,
"e": 30627,
"s": 30546,
"text": "This package creates nice looking color palettes, especially for thematic maps. "
},
{
"code": null,
"e": 30707,
"s": 30627,
"text": "brewer.pal() makes the color palettes from ColorBrewer available as R palettes."
},
{
"code": null,
"e": 30715,
"s": 30707,
"text": "Syntax:"
},
{
"code": null,
"e": 30735,
"s": 30715,
"text": "brewer.pal(n, name)"
},
{
"code": null,
"e": 30746,
"s": 30735,
"text": "Parameter:"
},
{
"code": null,
"e": 30833,
"s": 30746,
"text": "n: Number of different colors in the palette, minimum 3, maximum depending on palette."
},
{
"code": null,
"e": 30876,
"s": 30833,
"text": "name: A palette name from the lists below."
},
{
"code": null,
"e": 30949,
"s": 30876,
"text": "display.brewer.pal() displays the selected palette in a graphics window."
},
{
"code": null,
"e": 30957,
"s": 30949,
"text": "Syntax:"
},
{
"code": null,
"e": 30985,
"s": 30957,
"text": "display.brewer.pal(n, name)"
},
{
"code": null,
"e": 30996,
"s": 30985,
"text": "Parameter:"
},
{
"code": null,
"e": 31083,
"s": 30996,
"text": "n: Number of different colors in the palette, minimum 3, maximum depending on palette."
},
{
"code": null,
"e": 31126,
"s": 31083,
"text": "name: A palette name from the lists below."
},
{
"code": null,
"e": 31208,
"s": 31126,
"text": "display.brewer.all() displays a few palettes simultaneously in a graphics window."
},
{
"code": null,
"e": 31216,
"s": 31208,
"text": "Syntax:"
},
{
"code": null,
"e": 31308,
"s": 31216,
"text": "display.brewer.all(n=NULL, type=”all”, select=NULL, exact.n=TRUE, colorblindFriendly=FALSE)"
},
{
"code": null,
"e": 31319,
"s": 31308,
"text": "Parameter:"
},
{
"code": null,
"e": 31406,
"s": 31319,
"text": "n: Number of different colors in the palette, minimum 3, maximum depending on palette."
},
{
"code": null,
"e": 31449,
"s": 31406,
"text": "name: A palette name from the lists below."
},
{
"code": null,
"e": 31505,
"s": 31449,
"text": "type: One of the string “div”, “qual”, “seq”, or “all”."
},
{
"code": null,
"e": 31550,
"s": 31505,
"text": "select: A list of names of existing palettes"
},
{
"code": null,
"e": 31622,
"s": 31550,
"text": "exact.n: If TRUE, only display palettes with a color number given by n."
},
{
"code": null,
"e": 31694,
"s": 31622,
"text": "colorblindFriendly: if TRUE, display only colorblind friendly palettes."
},
{
"code": null,
"e": 31861,
"s": 31694,
"text": "brewer.pal.info returns information about the available palettes as a dataframe. brewer.pal.info is not a function, it is a variable. This might change in the future."
},
{
"code": null,
"e": 31936,
"s": 31861,
"text": " rownames Retrieve or set the row or column names of a matrix-like object."
},
{
"code": null,
"e": 31944,
"s": 31936,
"text": "Syntax:"
},
{
"code": null,
"e": 31965,
"s": 31944,
"text": "rownames(x) <- value"
},
{
"code": null,
"e": 32043,
"s": 31965,
"text": "There are 3 types of palettes namely: sequential, diverging, and qualitative."
},
{
"code": null,
"e": 32249,
"s": 32043,
"text": "Sequential palettes are suited to ordered data that progress from low to high. Lightness steps dominate the look of these schemes, with light colors for low data values to dark colors for high data values."
},
{
"code": null,
"e": 32251,
"s": 32249,
"text": "R"
},
{
"code": "display.brewer.all(type=\"seq\")",
"e": 32282,
"s": 32251,
"text": null
},
{
"code": null,
"e": 32290,
"s": 32282,
"text": "Output:"
},
{
"code": null,
"e": 32577,
"s": 32290,
"text": "Diverging palettes put equal emphasis on mid-range critical values and extremes at both ends of the data range. The critical class or break in the middle of the legend is emphasized with light colors and low and high extremes are emphasized with dark colors that have contrasting hues. "
},
{
"code": null,
"e": 32579,
"s": 32577,
"text": "R"
},
{
"code": "display.brewer.all(type=\"div\")",
"e": 32610,
"s": 32579,
"text": null
},
{
"code": null,
"e": 32618,
"s": 32610,
"text": "Output:"
},
{
"code": null,
"e": 32855,
"s": 32618,
"text": "Qualitative palettes do not imply magnitude differences between legend classes, and hues are used to create the primary visual differences between classes. Qualitative schemes are best suited to representing nominal or categorical data."
},
{
"code": null,
"e": 32857,
"s": 32855,
"text": "R"
},
{
"code": "display.brewer.all(type=\"qual\")",
"e": 32889,
"s": 32857,
"text": null
},
{
"code": null,
"e": 32897,
"s": 32889,
"text": "Output:"
},
{
"code": null,
"e": 32906,
"s": 32897,
"text": "Example:"
},
{
"code": null,
"e": 32908,
"s": 32906,
"text": "R"
},
{
"code": "# installation of the package RColorBrewerinstall.packages(\"RColorBrewer\") # loading of the packagelibrary(\"RColorBrewer\") # extraction of color info# qual --> Qualitative color palettepalette5 <- brewer.pal.info[brewer.pal.info$category == \"qual\",] # create vector with all colorspalette <- unlist(mapply(brewer.pal, palette5$maxcolors, rownames(palette5)))palette # sample colorspalette_palette <- sample(palette, no_of_colors) # colors with their hex codespalette_palette # prints the pie chartpie(rep(1, no_of_colors), col = palette_palette, main = \"RColorBrewer Palette\")",
"e": 33520,
"s": 32908,
"text": null
},
{
"code": null,
"e": 33528,
"s": 33520,
"text": "Output:"
},
{
"code": null,
"e": 33530,
"s": 33528,
"text": "."
},
{
"code": null,
"e": 33537,
"s": 33530,
"text": "Picked"
},
{
"code": null,
"e": 33546,
"s": 33537,
"text": "R-Charts"
},
{
"code": null,
"e": 33555,
"s": 33546,
"text": "R-Graphs"
},
{
"code": null,
"e": 33563,
"s": 33555,
"text": "R-plots"
},
{
"code": null,
"e": 33574,
"s": 33563,
"text": "R Language"
},
{
"code": null,
"e": 33672,
"s": 33574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33681,
"s": 33672,
"text": "Comments"
},
{
"code": null,
"e": 33694,
"s": 33681,
"text": "Old Comments"
},
{
"code": null,
"e": 33746,
"s": 33694,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 33784,
"s": 33746,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 33819,
"s": 33784,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 33877,
"s": 33819,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 33920,
"s": 33877,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 33969,
"s": 33920,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 34019,
"s": 33969,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 34036,
"s": 34019,
"text": "R - if statement"
},
{
"code": null,
"e": 34073,
"s": 34036,
"text": "How to import an Excel File into R ?"
}
] |
Java final Keyword
|
❮ Java Keywords
Set a variable to final, to prevent it from being overridden/modified:
public class Main {
final int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
Try it Yourself »
The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override).
The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...).
The final keyword is called a "modifier". You will learn more about these in the Java Modifiers Chapter.
Read more about attributes our Java Class Attributes Tutorial.
❮ Java Keywords
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 18,
"s": 0,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 89,
"s": 18,
"text": "Set a variable to final, to prevent it from being overridden/modified:"
},
{
"code": null,
"e": 329,
"s": 89,
"text": "public class Main {\n final int x = 10;\n\n public static void main(String[] args) {\n Main myObj = new Main();\n myObj.x = 25; // will generate an error: cannot assign a value to a final variable\n System.out.println(myObj.x);\n }\n}\n"
},
{
"code": null,
"e": 349,
"s": 329,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 503,
"s": 349,
"text": "The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override)."
},
{
"code": null,
"e": 610,
"s": 503,
"text": "The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...)."
},
{
"code": null,
"e": 715,
"s": 610,
"text": "The final keyword is called a \"modifier\". You will learn more about these in the Java Modifiers Chapter."
},
{
"code": null,
"e": 778,
"s": 715,
"text": "Read more about attributes our Java Class Attributes Tutorial."
},
{
"code": null,
"e": 796,
"s": 778,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 829,
"s": 796,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 871,
"s": 829,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 978,
"s": 871,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 997,
"s": 978,
"text": "help@w3schools.com"
}
] |
JqueryUI - Spinner
|
Spinner widget adds a up/down arrow to the left of a input box thus allowing a user to increment/decrement a value in the input box. It allows users to type a value directly, or modify an existing value by spinning with the keyboard, mouse or scrollwheel. It also has a step feature to skip values. In addition to the basic numeric features, it also enables globalized formatting options (ie currency, thousand separator, decimals, etc.) thus providing a convenient internationalized masked entry box.
The following example depends on Globalize. You can get the Globalize files from https://github.com/jquery/globalize. Click the releases link, select the version you want, and download the .zip or tar.gz file. Extract the files and copy the following files to the folder where your example is located.
lib/globalize.js : This file contains the Javascript code for dealing with localizations
lib/globalize.js : This file contains the Javascript code for dealing with localizations
lib/globalize.culture.js : This file contains a complete set of the locales that the Globalize library comes with.
lib/globalize.culture.js : This file contains a complete set of the locales that the Globalize library comes with.
These files are also present in the external folder of your jquery-ui library.
jQueryUI provides spinner() method which creates a spinner.
The spinner() method can be used in two forms −
$(selector, context).spinner (options) Method
$(selector, context).spinner (options) Method
$(selector, context).spinner ("action", params) Method
$(selector, context).spinner ("action", params) Method
The spinner (options) method declares that an HTML element and its contents should be treated and managed as spinner. The options parameter is an object that specifies the appearance and behavior of the spinner elements involved.
$(selector, context).spinner (options);
You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows −
$(selector, context).spinner({option1: value1, option2: value2..... });
The following table lists the different options that can be used with this method −
This option sets the culture to use for parsing and formatting the value. By default its value is null which means the currently set culture in Globalize is used.
Option - culture
This option sets the culture to use for parsing and formatting the value. By default its value is null which means the currently set culture in Globalize is used. Only relevant if the numberFormat option is set. Requires Globalize to be included.
Syntax
$( ".selector" ).spinner(
{ culture: "fr" }
);
This option if set to true disables spinner. By default its value is false.
Option - disabled
This option if set to true disables spinner. By default its value is false.
Syntax
$( ".selector" ).spinner(
{ disabled: true }
);
This option sets icons to use for buttons, matching an icon provided by the jQuery UI CSS Framework. By default its value is { down: "ui-icon-triangle-1-s", up: "ui-icon-triangle-1-n" }.
Option - icons
This option sets icons to use for buttons, matching an icon provided by the jQuery UI CSS Framework. By default its value is { down: "ui-icon-triangle-1-s", up: "ui-icon-triangle-1-n" }.
Syntax
$( ".selector" ).spinner(
{ icons: { down: "custom-down-icon", up: "custom-up-icon" } }
);
This option controls the number of steps taken when holding down a spin button. By default its value is true.
Option - incremental
This option controls the number of steps taken when holding down a spin button. By default its value is true.
This can be of type −
Boolean − If set to false all steps are equal. If set to true, the stepping delta will increase when spun incessantly.
Boolean − If set to false all steps are equal. If set to true, the stepping delta will increase when spun incessantly.
Function − This must return the number of steps that should occur for the current spin.
Function − This must return the number of steps that should occur for the current spin.
Syntax
$( ".selector" ).spinner(
{ incremental: false }
);
This option indicates the maximum allowed value. By default its value is null which means there is no maximum enforced.
Option - max
This option indicates the maximum allowed value. By default its value is null which means there is no maximum enforced.
This can be of type −
Number − The maximum value.
Number − The maximum value.
String − If Globalize is included, the max option can be passed as a string which will be parsed based on the numberFormat and culture options
String − If Globalize is included, the max option can be passed as a string which will be parsed based on the numberFormat and culture options
Syntax
$( ".selector" ).spinner(
{ max: 50 }
);
This option indicates the minimum allowed value. By default its value is null which means there is no minimum enforced.
Option - min
This option indicates the minimum allowed value. By default its value is null which means there is no minimum enforced.
This can be of type −
Number − The minimum value.
Number − The minimum value.
String − If Globalize is included, the min option can be passed as a string which will be parsed based on the numberFormat and culture options.
String − If Globalize is included, the min option can be passed as a string which will be parsed based on the numberFormat and culture options
Syntax
$( ".selector" ).spinner(
{ min: 0 }
);
This option indicates format of numbers passed to Globalize, if available. Most common are "n" for a decimal number and "C" for a currency value. By default its value is null.
Option - numberFormat
This option indicates format of numbers passed to Globalize, if available. Most common are "n" for a decimal number and "C" for a currency value. By default its value is null.
Syntax
$( ".selector" ).spinner(
{ numberFormat: "n" }
);
This option indicates the number of steps to take when paging via the pageUp/pageDown methods. By default its value is 10.
Option - page
This option indicates the number of steps to take when paging via the pageUp/pageDown methods. By default its value is 10.
Syntax
$( ".selector" ).spinner(
{ page: 5 }
);
This option indicates size of the step to take when spinning via buttons or via the stepUp()/stepDown() methods. The element's step attribute is used if it exists and the option is not explicitly set.
Option - step
This option indicates size of the step to take when spinning via buttons or via the stepUp()/stepDown() methods. The element's step attribute is used if it exists and the option is not explicitly set.
This can be of type −
Number − The size of step.
Number − The size of step.
String − If Globalize is included, the step option can be passed as a string which will be parsed based on the numberFormat and culture options, otherwise it will fall back to the native parseFloat.
String − If Globalize is included, the step option can be passed as a string which will be parsed based on the numberFormat and culture options, otherwise it will fall back to the native parseFloat.
Syntax
$( ".selector" ).spinner(
{ step: 2 }
);
The following section will show you a few working examples of spinner widget functionality.
The following example demonstrates a simple example of spinner widget functionality, passing no parameters to the spinner() method.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Spinner functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style type = "text/css">
#spinner-1 input {width: 100px}
</style>
<!-- Javascript -->
<script>
$(function() {
$( "#spinner-1" ).spinner();
});
</script>
</head>
<body>
<!-- HTML -->
<div id = "example">
<input type = "text" id = "spinner-1" value = "0" />
</div>
</body>
</html>
Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
The following example demonstrates the usage of three options min, max and step in the spinner widget of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Spinner functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style type = "text/css">
#spinner-2,#spinner-3 input {width: 100px}
</style>
<!-- Javascript -->
<script>
$(function() {
$( "#spinner-2" ).spinner({
min: -10,
max: 10
});
$('#spinner-3').spinner({
step: 100,
min: -1000000,
max: 1000000
});
});
</script>
</head>
<body>
<!-- HTML -->
<div id = "example">
Spinner Min, Max value set:
<input type = "text" id = "spinner-2" value = "0" /><br><br>
Spinner increments/decrements in step of of 100:
<input type = "text" id = "spinner-3" value = "0" />
</div>
</body>
</html>
Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
In the above example, you can see in the first spinner the max and min values are set to 10 and -10 respectively. Hence crossing these values, the spinner will stop incrementing/decrementing. In the second spinner the spinner value increments/decrements in steps of 100.
The following example demonstrates the usage of option icons in the spinner widget of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Spinner functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style type = "text/css">
#spinner-5 input {width: 100px}
</style>
<!-- Javascript -->
<script>
$(function() {
$( "#spinner-5" ).spinner({
icons: {
down: "custom-down-icon", up: "custom-up-icon"
}
});
});
</script>
</head>
<body>
<!-- HTML -->
<div id = "example">
<input type = "text" id = "spinner-5" value = "0" />
</div>
</body>
</html>
Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
In the above example, you can notice the images spinner are changed.
The following example demonstrates the usage of three options culture, numberFormat and page in the spinner widget of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Spinner functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src = "/jqueryui/jquery-ui-1.10.4/external/jquery.mousewheel.js"></script>
<script src = "/jqueryui/jquery-ui-1.10.4/external/globalize.js"></script>
<script src = "/jqueryui/jquery-ui-1.10.4/external/globalize.culture.de-DE.js"></script>
<script>
$(function() {
$( "#spinner-4" ).spinner({
culture:"de-DE",
numberFormat:"C",
step:2,
page:10
});
});
</script>
</head>
<body>
<p>
<label for = "spinner-4">Amount to donate:</label>
<input id = "spinner-4" name = "spinner" value = "5">
</p>
</body>
</html>
Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Amount to donate:
▲▼
In the above example, you can see the spinner displays the number in currency format as the numberFormat is set to "C" and culture is set to "de-DE". Here we have used the Globalize files from the jquery-ui library.
The spinner ("action", params) method can perform an action on spinner elements, such as enabling/disabling the spinner. The action is specified as a string in the first argument (e.g., "disable" disables the spinner). Check out the actions that can be passed, in the following table.
$(selector, context).spinner ("action", params);;
The following table lists the different actions that can be used with this method −
This action destroys the spinner functionality of an element completely. The elements return to their pre-init state. This method does not accept any arguments.
Action - destroy
This action destroys the spinner functionality of an element completely. The elements return to their pre-init state. This method does not accept any arguments.
Syntax
$(".selector").spinner("destroy");
This action disables the spinner functionality. This method does not accept any arguments.
Action - disable
This action disables the spinner functionality. This method does not accept any arguments.
Syntax
$(".selector").spinner("disable");
This action enables the spinner functionality. This method does not accept any arguments.
Action - enable
This action enables the spinner functionality. This method does not accept any arguments.
Syntax
$(".selector").spinner("enable");
This action gets the value currently associated with the specified optionName. Where optionName is the name of the option to get.
Action - option( optionName )
This action gets the value currently associated with the specified optionName. Where optionName is the name of the option to get.
Syntax
var isDisabled = $( ".selector" ).spinner( "option", "disabled" );
This action gets an object containing key/value pairs representing the current spinner options hash. This method does not accept any arguments.
Action - option
This action gets an object containing key/value pairs representing the current spinner options hash. This method does not accept any arguments.
Syntax
var options = $( ".selector" ).spinner( "option" );
This action sets the value of the spinner option associated with the specified optionName.
Action - optionName
This action sets the value of the spinner option associated with the specified optionName.
Syntax
$( ".selector" ).spinner( "option", "disabled", true );
This action sets one or more options for the spinner.
Action - option( options )
This action sets one or more options for the spinner.
Syntax
$(".selector").spinner("option", { disabled: true });
This action decrements the value by the specified number of pages, as defined by the page option.
Action - pageDown( [pages ] )
This action decrements the value by the specified number of pages, as defined by the page option. Invoking pageDown() will cause start, spin, and stop events to be triggered.
Syntax
$(".selector").spinner("pageDown");
This action increments the value by the specified number of pages, as defined by the page option.
Action - pageUp( [pages ] )
This action increments the value by the specified number of pages, as defined by the page option. Invoking pageUp() will cause start, spin, and stop events to be triggered.
Syntax
$(".selector").spinner("pageUp");
This action decrements the value by the specified number of steps.
Action - stepDown( [steps ] )
This action decrements the value by the specified number of steps. Invoking stepDown() will cause start, spin, and stop events to be triggered.
Syntax
$(".selector").spinner("stepDown");
This action increments the value by the specified number of steps.
Action - stepUp( [steps ] )
This action increments the value by the specified number of steps. Invoking stepUp() will cause start, spin, and stop events to be triggered.
Syntax
$(".selector").spinner("stepUp");
This action gets the current value as a number. The value is parsed based on the numberFormat and culture options. This method does not accept any arguments.
Action - value
This action gets the current value as a number. The value is parsed based on the numberFormat and culture options. This method does not accept any arguments.
Syntax
var value = $( ".selector" ).spinner( "value" );
This action sets the value. if value is passed value is parsed based on the numberFormat and culture options.
Action - value( value )
This action sets the value. if value is passed value is parsed based on the numberFormat and culture options.
Syntax
$( ".selector" ).spinner( "value", 50 );
This action returns the spinner widget element; the one annotated with the ui-spinner class name.
Action - widget
This action returns the spinner widget element; the one annotated with the ui-spinner class name.
Syntax
$( ".selector" ).spinner( "widget");
The following examples demonstrate how to use the actions given in the above table.
The following example demonstrates the use of stepUp, stepDown, pageUp and pageDown methods.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Spinner functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style type = "text/css">
#spinner-6 input {width: 100px}
</style>
<!-- Javascript -->
<script>
$(function() {
$("#spinner-6").spinner();
$('button').button();
$('#stepUp-2').click(function () {
$("#spinner-6").spinner("stepUp");
});
$('#stepDown-2').click(function () {
$("#spinner-6").spinner("stepDown");
});
$('#pageUp-2').click(function () {
$("#spinner-6").spinner("pageUp");
});
$('#pageDown-2').click(function () {
$("#spinner-6").spinner("pageDown");
});
});
</script>
</head>
<body>
<!-- HTML -->
<input id = "spinner-6" />
<br/>
<button id = "stepUp-2">Increment</button>
<button id = "stepDown-2">Decrement</button>
<button id = "pageUp-2">Increment Page</button>
<button id = "pageDown-2">Decrement Page</button>
</body>
</html>
Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you also must see the following output −
In the above example, use the respective buttons to increment/decrement the spinner.
The following example demonstrates the use of enable and disable methods.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Spinner functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style type = "text/css">
#spinner-7 input {width: 100px}
</style>
<!-- Javascript -->
<script>
$(function() {
$("#spinner-7").spinner();
$('button').button();
$('#stepUp-3').click(function () {
$("#spinner-7").spinner("enable");
});
$('#stepDown-3').click(function () {
$("#spinner-7").spinner("disable");
});
});
</script>
</head>
<body>
<!-- HTML -->
<input id = "spinner-7" />
<br/>
<button id = "stepUp-3">Enable</button>
<button id = "stepDown-3">Disable</button>
</body>
</html>
Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output −
In the above example, use the Enable/Disable buttons to enable or disable the spinner.
In addition to the spinner (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below −
This event is triggered when the value of the spinner has changed and the input is no longer focused.
Event - change(event, ui)
This event is triggered when the value of the spinner has changed and the input is no longer focused. Where event is of type Event, and ui is of type Object.
Syntax
$( ".selector" ).spinner({
change: function( event, ui ) {}
});
This event is triggered when the spinner is created.
Event - create(event, ui)
This event is triggered when the spinner is created. Where event is of type Event, and ui is of type Object.
Syntax
$( ".selector" ).spinner({
create: function( event, ui ) {}
});
This event is triggered during increment/decrement.
Event - spin(event, ui)
This event is triggered during increment/decrement. Where event is of type Event, and ui is of type Object.
Syntax
$( ".selector" ).spinner({
spin: function( event, ui ) {}
});
This event is triggered before a spin. Can be canceled, preventing the spin from occurring.
Event - start(event, ui)
This event is triggered before a spin. Can be canceled, preventing the spin from occurring. Where event is of type Event, and ui is of type Object.
Syntax
$( ".selector" ).spinner({
start: function( event, ui ) {}
});
This event is triggered after a spin.
Event - stop(event, ui)
This event is triggered after a spin. Where event is of type Event, and ui is of type Object.
Syntax
$( ".selector" ).spinner({
stop: function( event, ui ) {}
});
The following example demonstrates the event method usage in spinner widgets. This example demonstrates the use of events spin, change and stop.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Spinner functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style type = "text/css">
#spinner-8 input {width: 100px}
</style>
<!-- Javascript -->
<script>
$(function() {
$( "#spinner-8" ).spinner({
spin: function( event, ui ) {
var result = $( "#result-2" );
result.append( "Spin Value: "+$( "#spinner-8" ).spinner("value") );
},
change: function( event, ui ) {
var result = $( "#result-2" );
result.append( "Change value: "+$( "#spinner-8" ).spinner("value") );
},
stop: function( event, ui ) {
var result = $( "#result-2" );
result.append( "Stop value: "+$( "#spinner-8" ).spinner("value") );
}
});
});
</script>
</head>
<body>
<!-- HTML -->
<div id = "example">
<input type = "text" id = "spinner-8" value = "0" />
</div>
<span id = "result-2"></span>
</body>
</html>
Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output −
In the above example change the value of the spinner and see, the messages being displayed below for spin and stop events. Now change the focus of the spinner and you see a message being displayed on change event.
The spinner widget is built with the widget factory and can be extended. To extend widgets, we can either override or add to the behavior of existing methods. Following method provides as extension point with the same API stability as the spinner methods. Listed in the above table.
This method return a String which is an HTML. This HTML can be used for the spinner's increment and decrement buttons. Each button must be given a ui-spinner-button class name for the associated events to work. This method does not accept any arguments.
Extension Point - _buttonHtml(event, ui)
This method return a String which is an HTML. This HTML can be used for the spinner's increment and decrement buttons. Each button must be given a ui-spinner-button class name for the associated events to work. This method does not accept any arguments.
Code Example
_buttonHtml: function() {
return "" +
"" +
"▲" +
"" +
"" +
"▼" +
"";
}
This method determine the HTML to use to wrap the spinner's <input> element. This method does not accept any arguments.
Extension Point - _uiSpinnerHtml(event, ui)
This method determine the HTML to use to wrap the spinner's <input> element. This method does not accept any arguments.
Code Example
_uiSpinnerHtml: function() {
return "";
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2767,
"s": 2264,
"text": "Spinner widget adds a up/down arrow to the left of a input box thus allowing a user to increment/decrement a value in the input box. It allows users to type a value directly, or modify an existing value by spinning with the keyboard, mouse or scrollwheel. It also has a step feature to skip values. In addition to the basic numeric features, it also enables globalized formatting options (ie currency, thousand separator, decimals, etc.) thus providing a convenient internationalized masked entry box."
},
{
"code": null,
"e": 3069,
"s": 2767,
"text": "The following example depends on Globalize. You can get the Globalize files from https://github.com/jquery/globalize. Click the releases link, select the version you want, and download the .zip or tar.gz file. Extract the files and copy the following files to the folder where your example is located."
},
{
"code": null,
"e": 3158,
"s": 3069,
"text": "lib/globalize.js : This file contains the Javascript code for dealing with localizations"
},
{
"code": null,
"e": 3247,
"s": 3158,
"text": "lib/globalize.js : This file contains the Javascript code for dealing with localizations"
},
{
"code": null,
"e": 3362,
"s": 3247,
"text": "lib/globalize.culture.js : This file contains a complete set of the locales that the Globalize library comes with."
},
{
"code": null,
"e": 3477,
"s": 3362,
"text": "lib/globalize.culture.js : This file contains a complete set of the locales that the Globalize library comes with."
},
{
"code": null,
"e": 3556,
"s": 3477,
"text": "These files are also present in the external folder of your jquery-ui library."
},
{
"code": null,
"e": 3616,
"s": 3556,
"text": "jQueryUI provides spinner() method which creates a spinner."
},
{
"code": null,
"e": 3664,
"s": 3616,
"text": "The spinner() method can be used in two forms −"
},
{
"code": null,
"e": 3710,
"s": 3664,
"text": "$(selector, context).spinner (options) Method"
},
{
"code": null,
"e": 3756,
"s": 3710,
"text": "$(selector, context).spinner (options) Method"
},
{
"code": null,
"e": 3811,
"s": 3756,
"text": "$(selector, context).spinner (\"action\", params) Method"
},
{
"code": null,
"e": 3866,
"s": 3811,
"text": "$(selector, context).spinner (\"action\", params) Method"
},
{
"code": null,
"e": 4096,
"s": 3866,
"text": "The spinner (options) method declares that an HTML element and its contents should be treated and managed as spinner. The options parameter is an object that specifies the appearance and behavior of the spinner elements involved."
},
{
"code": null,
"e": 4137,
"s": 4096,
"text": "$(selector, context).spinner (options);\n"
},
{
"code": null,
"e": 4313,
"s": 4137,
"text": "You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows −"
},
{
"code": null,
"e": 4385,
"s": 4313,
"text": "$(selector, context).spinner({option1: value1, option2: value2..... });"
},
{
"code": null,
"e": 4469,
"s": 4385,
"text": "The following table lists the different options that can be used with this method −"
},
{
"code": null,
"e": 4632,
"s": 4469,
"text": "This option sets the culture to use for parsing and formatting the value. By default its value is null which means the currently set culture in Globalize is used."
},
{
"code": null,
"e": 4649,
"s": 4632,
"text": "Option - culture"
},
{
"code": null,
"e": 4896,
"s": 4649,
"text": "This option sets the culture to use for parsing and formatting the value. By default its value is null which means the currently set culture in Globalize is used. Only relevant if the numberFormat option is set. Requires Globalize to be included."
},
{
"code": null,
"e": 4903,
"s": 4896,
"text": "Syntax"
},
{
"code": null,
"e": 4954,
"s": 4903,
"text": "$( \".selector\" ).spinner(\n { culture: \"fr\" }\n);\n"
},
{
"code": null,
"e": 5030,
"s": 4954,
"text": "This option if set to true disables spinner. By default its value is false."
},
{
"code": null,
"e": 5048,
"s": 5030,
"text": "Option - disabled"
},
{
"code": null,
"e": 5124,
"s": 5048,
"text": "This option if set to true disables spinner. By default its value is false."
},
{
"code": null,
"e": 5131,
"s": 5124,
"text": "Syntax"
},
{
"code": null,
"e": 5183,
"s": 5131,
"text": "$( \".selector\" ).spinner(\n { disabled: true }\n);\n"
},
{
"code": null,
"e": 5370,
"s": 5183,
"text": "This option sets icons to use for buttons, matching an icon provided by the jQuery UI CSS Framework. By default its value is { down: \"ui-icon-triangle-1-s\", up: \"ui-icon-triangle-1-n\" }."
},
{
"code": null,
"e": 5385,
"s": 5370,
"text": "Option - icons"
},
{
"code": null,
"e": 5572,
"s": 5385,
"text": "This option sets icons to use for buttons, matching an icon provided by the jQuery UI CSS Framework. By default its value is { down: \"ui-icon-triangle-1-s\", up: \"ui-icon-triangle-1-n\" }."
},
{
"code": null,
"e": 5579,
"s": 5572,
"text": "Syntax"
},
{
"code": null,
"e": 5674,
"s": 5579,
"text": "$( \".selector\" ).spinner(\n { icons: { down: \"custom-down-icon\", up: \"custom-up-icon\" } }\n);\n"
},
{
"code": null,
"e": 5784,
"s": 5674,
"text": "This option controls the number of steps taken when holding down a spin button. By default its value is true."
},
{
"code": null,
"e": 5805,
"s": 5784,
"text": "Option - incremental"
},
{
"code": null,
"e": 5915,
"s": 5805,
"text": "This option controls the number of steps taken when holding down a spin button. By default its value is true."
},
{
"code": null,
"e": 5937,
"s": 5915,
"text": "This can be of type −"
},
{
"code": null,
"e": 6056,
"s": 5937,
"text": "Boolean − If set to false all steps are equal. If set to true, the stepping delta will increase when spun incessantly."
},
{
"code": null,
"e": 6175,
"s": 6056,
"text": "Boolean − If set to false all steps are equal. If set to true, the stepping delta will increase when spun incessantly."
},
{
"code": null,
"e": 6263,
"s": 6175,
"text": "Function − This must return the number of steps that should occur for the current spin."
},
{
"code": null,
"e": 6351,
"s": 6263,
"text": "Function − This must return the number of steps that should occur for the current spin."
},
{
"code": null,
"e": 6358,
"s": 6351,
"text": "Syntax"
},
{
"code": null,
"e": 6414,
"s": 6358,
"text": "$( \".selector\" ).spinner(\n { incremental: false }\n);\n"
},
{
"code": null,
"e": 6534,
"s": 6414,
"text": "This option indicates the maximum allowed value. By default its value is null which means there is no maximum enforced."
},
{
"code": null,
"e": 6547,
"s": 6534,
"text": "Option - max"
},
{
"code": null,
"e": 6667,
"s": 6547,
"text": "This option indicates the maximum allowed value. By default its value is null which means there is no maximum enforced."
},
{
"code": null,
"e": 6689,
"s": 6667,
"text": "This can be of type −"
},
{
"code": null,
"e": 6717,
"s": 6689,
"text": "Number − The maximum value."
},
{
"code": null,
"e": 6745,
"s": 6717,
"text": "Number − The maximum value."
},
{
"code": null,
"e": 6888,
"s": 6745,
"text": "String − If Globalize is included, the max option can be passed as a string which will be parsed based on the numberFormat and culture options"
},
{
"code": null,
"e": 7031,
"s": 6888,
"text": "String − If Globalize is included, the max option can be passed as a string which will be parsed based on the numberFormat and culture options"
},
{
"code": null,
"e": 7038,
"s": 7031,
"text": "Syntax"
},
{
"code": null,
"e": 7083,
"s": 7038,
"text": "$( \".selector\" ).spinner(\n { max: 50 }\n);\n"
},
{
"code": null,
"e": 7203,
"s": 7083,
"text": "This option indicates the minimum allowed value. By default its value is null which means there is no minimum enforced."
},
{
"code": null,
"e": 7216,
"s": 7203,
"text": "Option - min"
},
{
"code": null,
"e": 7336,
"s": 7216,
"text": "This option indicates the minimum allowed value. By default its value is null which means there is no minimum enforced."
},
{
"code": null,
"e": 7358,
"s": 7336,
"text": "This can be of type −"
},
{
"code": null,
"e": 7386,
"s": 7358,
"text": "Number − The minimum value."
},
{
"code": null,
"e": 7414,
"s": 7386,
"text": "Number − The minimum value."
},
{
"code": null,
"e": 7558,
"s": 7414,
"text": "String − If Globalize is included, the min option can be passed as a string which will be parsed based on the numberFormat and culture options."
},
{
"code": null,
"e": 7701,
"s": 7558,
"text": "String − If Globalize is included, the min option can be passed as a string which will be parsed based on the numberFormat and culture options"
},
{
"code": null,
"e": 7708,
"s": 7701,
"text": "Syntax"
},
{
"code": null,
"e": 7752,
"s": 7708,
"text": "$( \".selector\" ).spinner(\n { min: 0 }\n);\n"
},
{
"code": null,
"e": 7929,
"s": 7752,
"text": "This option indicates format of numbers passed to Globalize, if available. Most common are \"n\" for a decimal number and \"C\" for a currency value. By default its value is null."
},
{
"code": null,
"e": 7951,
"s": 7929,
"text": "Option - numberFormat"
},
{
"code": null,
"e": 8128,
"s": 7951,
"text": "This option indicates format of numbers passed to Globalize, if available. Most common are \"n\" for a decimal number and \"C\" for a currency value. By default its value is null."
},
{
"code": null,
"e": 8135,
"s": 8128,
"text": "Syntax"
},
{
"code": null,
"e": 8190,
"s": 8135,
"text": "$( \".selector\" ).spinner(\n { numberFormat: \"n\" }\n);\n"
},
{
"code": null,
"e": 8313,
"s": 8190,
"text": "This option indicates the number of steps to take when paging via the pageUp/pageDown methods. By default its value is 10."
},
{
"code": null,
"e": 8327,
"s": 8313,
"text": "Option - page"
},
{
"code": null,
"e": 8450,
"s": 8327,
"text": "This option indicates the number of steps to take when paging via the pageUp/pageDown methods. By default its value is 10."
},
{
"code": null,
"e": 8457,
"s": 8450,
"text": "Syntax"
},
{
"code": null,
"e": 8502,
"s": 8457,
"text": "$( \".selector\" ).spinner(\n { page: 5 }\n);\n"
},
{
"code": null,
"e": 8703,
"s": 8502,
"text": "This option indicates size of the step to take when spinning via buttons or via the stepUp()/stepDown() methods. The element's step attribute is used if it exists and the option is not explicitly set."
},
{
"code": null,
"e": 8717,
"s": 8703,
"text": "Option - step"
},
{
"code": null,
"e": 8918,
"s": 8717,
"text": "This option indicates size of the step to take when spinning via buttons or via the stepUp()/stepDown() methods. The element's step attribute is used if it exists and the option is not explicitly set."
},
{
"code": null,
"e": 8940,
"s": 8918,
"text": "This can be of type −"
},
{
"code": null,
"e": 8967,
"s": 8940,
"text": "Number − The size of step."
},
{
"code": null,
"e": 8994,
"s": 8967,
"text": "Number − The size of step."
},
{
"code": null,
"e": 9193,
"s": 8994,
"text": "String − If Globalize is included, the step option can be passed as a string which will be parsed based on the numberFormat and culture options, otherwise it will fall back to the native parseFloat."
},
{
"code": null,
"e": 9392,
"s": 9193,
"text": "String − If Globalize is included, the step option can be passed as a string which will be parsed based on the numberFormat and culture options, otherwise it will fall back to the native parseFloat."
},
{
"code": null,
"e": 9399,
"s": 9392,
"text": "Syntax"
},
{
"code": null,
"e": 9444,
"s": 9399,
"text": "$( \".selector\" ).spinner(\n { step: 2 }\n);\n"
},
{
"code": null,
"e": 9536,
"s": 9444,
"text": "The following section will show you a few working examples of spinner widget functionality."
},
{
"code": null,
"e": 9668,
"s": 9536,
"text": "The following example demonstrates a simple example of spinner widget functionality, passing no parameters to the spinner() method."
},
{
"code": null,
"e": 10483,
"s": 9668,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Spinner functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style type = \"text/css\">\n #spinner-1 input {width: 100px}\n </style>\n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#spinner-1\" ).spinner();\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"example\">\n <input type = \"text\" id = \"spinner-1\" value = \"0\" />\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 10682,
"s": 10483,
"text": "Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 10797,
"s": 10682,
"text": "The following example demonstrates the usage of three options min, max and step in the spinner widget of JqueryUI."
},
{
"code": null,
"e": 11992,
"s": 10797,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Spinner functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style type = \"text/css\">\n #spinner-2,#spinner-3 input {width: 100px}\n </style>\n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#spinner-2\" ).spinner({\n min: -10, \n max: 10\n });\n $('#spinner-3').spinner({\n step: 100, \n min: -1000000, \n max: 1000000\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"example\">\n Spinner Min, Max value set:\n <input type = \"text\" id = \"spinner-2\" value = \"0\" /><br><br>\n Spinner increments/decrements in step of of 100:\n <input type = \"text\" id = \"spinner-3\" value = \"0\" />\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 12191,
"s": 11992,
"text": "Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 12462,
"s": 12191,
"text": "In the above example, you can see in the first spinner the max and min values are set to 10 and -10 respectively. Hence crossing these values, the spinner will stop incrementing/decrementing. In the second spinner the spinner value increments/decrements in steps of 100."
},
{
"code": null,
"e": 12558,
"s": 12462,
"text": "The following example demonstrates the usage of option icons in the spinner widget of JqueryUI."
},
{
"code": null,
"e": 13494,
"s": 12558,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Spinner functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style type = \"text/css\">\n #spinner-5 input {width: 100px}\n </style>\n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#spinner-5\" ).spinner({\n icons: {\n down: \"custom-down-icon\", up: \"custom-up-icon\"\n }\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"example\">\n <input type = \"text\" id = \"spinner-5\" value = \"0\" />\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 13693,
"s": 13494,
"text": "Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 13762,
"s": 13693,
"text": "In the above example, you can notice the images spinner are changed."
},
{
"code": null,
"e": 13890,
"s": 13762,
"text": "The following example demonstrates the usage of three options culture, numberFormat and page in the spinner widget of JqueryUI."
},
{
"code": null,
"e": 14990,
"s": 13890,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Spinner functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n <script src = \"/jqueryui/jquery-ui-1.10.4/external/jquery.mousewheel.js\"></script>\n <script src = \"/jqueryui/jquery-ui-1.10.4/external/globalize.js\"></script>\n <script src = \"/jqueryui/jquery-ui-1.10.4/external/globalize.culture.de-DE.js\"></script>\n \n <script>\n $(function() {\n $( \"#spinner-4\" ).spinner({\n culture:\"de-DE\",\n numberFormat:\"C\",\n step:2,\n page:10\n });\n });\n </script>\n </head>\n \n <body>\n <p>\n <label for = \"spinner-4\">Amount to donate:</label>\n <input id = \"spinner-4\" name = \"spinner\" value = \"5\">\n </p>\n \n </body>\n</html>"
},
{
"code": null,
"e": 15189,
"s": 14990,
"text": "Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 15212,
"s": 15189,
"text": "\nAmount to donate:\n▲▼\n"
},
{
"code": null,
"e": 15428,
"s": 15212,
"text": "In the above example, you can see the spinner displays the number in currency format as the numberFormat is set to \"C\" and culture is set to \"de-DE\". Here we have used the Globalize files from the jquery-ui library."
},
{
"code": null,
"e": 15713,
"s": 15428,
"text": "The spinner (\"action\", params) method can perform an action on spinner elements, such as enabling/disabling the spinner. The action is specified as a string in the first argument (e.g., \"disable\" disables the spinner). Check out the actions that can be passed, in the following table."
},
{
"code": null,
"e": 15764,
"s": 15713,
"text": "$(selector, context).spinner (\"action\", params);;\n"
},
{
"code": null,
"e": 15848,
"s": 15764,
"text": "The following table lists the different actions that can be used with this method −"
},
{
"code": null,
"e": 16009,
"s": 15848,
"text": "This action destroys the spinner functionality of an element completely. The elements return to their pre-init state. This method does not accept any arguments."
},
{
"code": null,
"e": 16026,
"s": 16009,
"text": "Action - destroy"
},
{
"code": null,
"e": 16187,
"s": 16026,
"text": "This action destroys the spinner functionality of an element completely. The elements return to their pre-init state. This method does not accept any arguments."
},
{
"code": null,
"e": 16194,
"s": 16187,
"text": "Syntax"
},
{
"code": null,
"e": 16230,
"s": 16194,
"text": "$(\".selector\").spinner(\"destroy\");\n"
},
{
"code": null,
"e": 16321,
"s": 16230,
"text": "This action disables the spinner functionality. This method does not accept any arguments."
},
{
"code": null,
"e": 16338,
"s": 16321,
"text": "Action - disable"
},
{
"code": null,
"e": 16429,
"s": 16338,
"text": "This action disables the spinner functionality. This method does not accept any arguments."
},
{
"code": null,
"e": 16436,
"s": 16429,
"text": "Syntax"
},
{
"code": null,
"e": 16472,
"s": 16436,
"text": "$(\".selector\").spinner(\"disable\");\n"
},
{
"code": null,
"e": 16562,
"s": 16472,
"text": "This action enables the spinner functionality. This method does not accept any arguments."
},
{
"code": null,
"e": 16578,
"s": 16562,
"text": "Action - enable"
},
{
"code": null,
"e": 16668,
"s": 16578,
"text": "This action enables the spinner functionality. This method does not accept any arguments."
},
{
"code": null,
"e": 16675,
"s": 16668,
"text": "Syntax"
},
{
"code": null,
"e": 16710,
"s": 16675,
"text": "$(\".selector\").spinner(\"enable\");\n"
},
{
"code": null,
"e": 16840,
"s": 16710,
"text": "This action gets the value currently associated with the specified optionName. Where optionName is the name of the option to get."
},
{
"code": null,
"e": 16870,
"s": 16840,
"text": "Action - option( optionName )"
},
{
"code": null,
"e": 17000,
"s": 16870,
"text": "This action gets the value currently associated with the specified optionName. Where optionName is the name of the option to get."
},
{
"code": null,
"e": 17007,
"s": 17000,
"text": "Syntax"
},
{
"code": null,
"e": 17075,
"s": 17007,
"text": "var isDisabled = $( \".selector\" ).spinner( \"option\", \"disabled\" );\n"
},
{
"code": null,
"e": 17219,
"s": 17075,
"text": "This action gets an object containing key/value pairs representing the current spinner options hash. This method does not accept any arguments."
},
{
"code": null,
"e": 17235,
"s": 17219,
"text": "Action - option"
},
{
"code": null,
"e": 17379,
"s": 17235,
"text": "This action gets an object containing key/value pairs representing the current spinner options hash. This method does not accept any arguments."
},
{
"code": null,
"e": 17386,
"s": 17379,
"text": "Syntax"
},
{
"code": null,
"e": 17439,
"s": 17386,
"text": "var options = $( \".selector\" ).spinner( \"option\" );\n"
},
{
"code": null,
"e": 17530,
"s": 17439,
"text": "This action sets the value of the spinner option associated with the specified optionName."
},
{
"code": null,
"e": 17550,
"s": 17530,
"text": "Action - optionName"
},
{
"code": null,
"e": 17641,
"s": 17550,
"text": "This action sets the value of the spinner option associated with the specified optionName."
},
{
"code": null,
"e": 17648,
"s": 17641,
"text": "Syntax"
},
{
"code": null,
"e": 17705,
"s": 17648,
"text": "$( \".selector\" ).spinner( \"option\", \"disabled\", true );\n"
},
{
"code": null,
"e": 17759,
"s": 17705,
"text": "This action sets one or more options for the spinner."
},
{
"code": null,
"e": 17786,
"s": 17759,
"text": "Action - option( options )"
},
{
"code": null,
"e": 17840,
"s": 17786,
"text": "This action sets one or more options for the spinner."
},
{
"code": null,
"e": 17847,
"s": 17840,
"text": "Syntax"
},
{
"code": null,
"e": 17902,
"s": 17847,
"text": "$(\".selector\").spinner(\"option\", { disabled: true });\n"
},
{
"code": null,
"e": 18000,
"s": 17902,
"text": "This action decrements the value by the specified number of pages, as defined by the page option."
},
{
"code": null,
"e": 18030,
"s": 18000,
"text": "Action - pageDown( [pages ] )"
},
{
"code": null,
"e": 18205,
"s": 18030,
"text": "This action decrements the value by the specified number of pages, as defined by the page option. Invoking pageDown() will cause start, spin, and stop events to be triggered."
},
{
"code": null,
"e": 18212,
"s": 18205,
"text": "Syntax"
},
{
"code": null,
"e": 18249,
"s": 18212,
"text": "$(\".selector\").spinner(\"pageDown\");\n"
},
{
"code": null,
"e": 18347,
"s": 18249,
"text": "This action increments the value by the specified number of pages, as defined by the page option."
},
{
"code": null,
"e": 18375,
"s": 18347,
"text": "Action - pageUp( [pages ] )"
},
{
"code": null,
"e": 18548,
"s": 18375,
"text": "This action increments the value by the specified number of pages, as defined by the page option. Invoking pageUp() will cause start, spin, and stop events to be triggered."
},
{
"code": null,
"e": 18555,
"s": 18548,
"text": "Syntax"
},
{
"code": null,
"e": 18590,
"s": 18555,
"text": "$(\".selector\").spinner(\"pageUp\");\n"
},
{
"code": null,
"e": 18657,
"s": 18590,
"text": "This action decrements the value by the specified number of steps."
},
{
"code": null,
"e": 18687,
"s": 18657,
"text": "Action - stepDown( [steps ] )"
},
{
"code": null,
"e": 18831,
"s": 18687,
"text": "This action decrements the value by the specified number of steps. Invoking stepDown() will cause start, spin, and stop events to be triggered."
},
{
"code": null,
"e": 18838,
"s": 18831,
"text": "Syntax"
},
{
"code": null,
"e": 18875,
"s": 18838,
"text": "$(\".selector\").spinner(\"stepDown\");\n"
},
{
"code": null,
"e": 18942,
"s": 18875,
"text": "This action increments the value by the specified number of steps."
},
{
"code": null,
"e": 18970,
"s": 18942,
"text": "Action - stepUp( [steps ] )"
},
{
"code": null,
"e": 19112,
"s": 18970,
"text": "This action increments the value by the specified number of steps. Invoking stepUp() will cause start, spin, and stop events to be triggered."
},
{
"code": null,
"e": 19119,
"s": 19112,
"text": "Syntax"
},
{
"code": null,
"e": 19154,
"s": 19119,
"text": "$(\".selector\").spinner(\"stepUp\");\n"
},
{
"code": null,
"e": 19312,
"s": 19154,
"text": "This action gets the current value as a number. The value is parsed based on the numberFormat and culture options. This method does not accept any arguments."
},
{
"code": null,
"e": 19327,
"s": 19312,
"text": "Action - value"
},
{
"code": null,
"e": 19485,
"s": 19327,
"text": "This action gets the current value as a number. The value is parsed based on the numberFormat and culture options. This method does not accept any arguments."
},
{
"code": null,
"e": 19492,
"s": 19485,
"text": "Syntax"
},
{
"code": null,
"e": 19542,
"s": 19492,
"text": "var value = $( \".selector\" ).spinner( \"value\" );\n"
},
{
"code": null,
"e": 19652,
"s": 19542,
"text": "This action sets the value. if value is passed value is parsed based on the numberFormat and culture options."
},
{
"code": null,
"e": 19676,
"s": 19652,
"text": "Action - value( value )"
},
{
"code": null,
"e": 19786,
"s": 19676,
"text": "This action sets the value. if value is passed value is parsed based on the numberFormat and culture options."
},
{
"code": null,
"e": 19793,
"s": 19786,
"text": "Syntax"
},
{
"code": null,
"e": 19835,
"s": 19793,
"text": "$( \".selector\" ).spinner( \"value\", 50 );\n"
},
{
"code": null,
"e": 19933,
"s": 19835,
"text": "This action returns the spinner widget element; the one annotated with the ui-spinner class name."
},
{
"code": null,
"e": 19949,
"s": 19933,
"text": "Action - widget"
},
{
"code": null,
"e": 20047,
"s": 19949,
"text": "This action returns the spinner widget element; the one annotated with the ui-spinner class name."
},
{
"code": null,
"e": 20054,
"s": 20047,
"text": "Syntax"
},
{
"code": null,
"e": 20092,
"s": 20054,
"text": "$( \".selector\" ).spinner( \"widget\");\n"
},
{
"code": null,
"e": 20176,
"s": 20092,
"text": "The following examples demonstrate how to use the actions given in the above table."
},
{
"code": null,
"e": 20269,
"s": 20176,
"text": "The following example demonstrates the use of stepUp, stepDown, pageUp and pageDown methods."
},
{
"code": null,
"e": 21740,
"s": 20269,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Spinner functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style type = \"text/css\">\n #spinner-6 input {width: 100px}\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $(\"#spinner-6\").spinner();\n $('button').button();\n\n $('#stepUp-2').click(function () {\n $(\"#spinner-6\").spinner(\"stepUp\");\n });\n\n $('#stepDown-2').click(function () {\n $(\"#spinner-6\").spinner(\"stepDown\");\n });\n\n $('#pageUp-2').click(function () {\n $(\"#spinner-6\").spinner(\"pageUp\");\n });\n\n $('#pageDown-2').click(function () {\n $(\"#spinner-6\").spinner(\"pageDown\");\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <input id = \"spinner-6\" />\n <br/>\n <button id = \"stepUp-2\">Increment</button>\n <button id = \"stepDown-2\">Decrement</button>\n <button id = \"pageUp-2\">Increment Page</button>\n <button id = \"pageDown-2\">Decrement Page</button>\n </body>\n</html>"
},
{
"code": null,
"e": 21904,
"s": 21740,
"text": "Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you also must see the following output −"
},
{
"code": null,
"e": 21989,
"s": 21904,
"text": "In the above example, use the respective buttons to increment/decrement the spinner."
},
{
"code": null,
"e": 22063,
"s": 21989,
"text": "The following example demonstrates the use of enable and disable methods."
},
{
"code": null,
"e": 23184,
"s": 22063,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Spinner functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style type = \"text/css\">\n #spinner-7 input {width: 100px}\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $(\"#spinner-7\").spinner();\n $('button').button();\n $('#stepUp-3').click(function () {\n $(\"#spinner-7\").spinner(\"enable\");\n });\n $('#stepDown-3').click(function () {\n $(\"#spinner-7\").spinner(\"disable\");\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <input id = \"spinner-7\" />\n <br/>\n <button id = \"stepUp-3\">Enable</button>\n <button id = \"stepDown-3\">Disable</button>\n </body>\n</html>"
},
{
"code": null,
"e": 23348,
"s": 23184,
"text": "Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output −"
},
{
"code": null,
"e": 23435,
"s": 23348,
"text": "In the above example, use the Enable/Disable buttons to enable or disable the spinner."
},
{
"code": null,
"e": 23634,
"s": 23435,
"text": "In addition to the spinner (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below −"
},
{
"code": null,
"e": 23736,
"s": 23634,
"text": "This event is triggered when the value of the spinner has changed and the input is no longer focused."
},
{
"code": null,
"e": 23762,
"s": 23736,
"text": "Event - change(event, ui)"
},
{
"code": null,
"e": 23920,
"s": 23762,
"text": "This event is triggered when the value of the spinner has changed and the input is no longer focused. Where event is of type Event, and ui is of type Object."
},
{
"code": null,
"e": 23927,
"s": 23920,
"text": "Syntax"
},
{
"code": null,
"e": 23995,
"s": 23927,
"text": "$( \".selector\" ).spinner({\n change: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 24048,
"s": 23995,
"text": "This event is triggered when the spinner is created."
},
{
"code": null,
"e": 24074,
"s": 24048,
"text": "Event - create(event, ui)"
},
{
"code": null,
"e": 24183,
"s": 24074,
"text": "This event is triggered when the spinner is created. Where event is of type Event, and ui is of type Object."
},
{
"code": null,
"e": 24190,
"s": 24183,
"text": "Syntax"
},
{
"code": null,
"e": 24258,
"s": 24190,
"text": "$( \".selector\" ).spinner({\n create: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 24310,
"s": 24258,
"text": "This event is triggered during increment/decrement."
},
{
"code": null,
"e": 24334,
"s": 24310,
"text": "Event - spin(event, ui)"
},
{
"code": null,
"e": 24442,
"s": 24334,
"text": "This event is triggered during increment/decrement. Where event is of type Event, and ui is of type Object."
},
{
"code": null,
"e": 24449,
"s": 24442,
"text": "Syntax"
},
{
"code": null,
"e": 24515,
"s": 24449,
"text": "$( \".selector\" ).spinner({\n spin: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 24607,
"s": 24515,
"text": "This event is triggered before a spin. Can be canceled, preventing the spin from occurring."
},
{
"code": null,
"e": 24632,
"s": 24607,
"text": "Event - start(event, ui)"
},
{
"code": null,
"e": 24780,
"s": 24632,
"text": "This event is triggered before a spin. Can be canceled, preventing the spin from occurring. Where event is of type Event, and ui is of type Object."
},
{
"code": null,
"e": 24787,
"s": 24780,
"text": "Syntax"
},
{
"code": null,
"e": 24854,
"s": 24787,
"text": "$( \".selector\" ).spinner({\n start: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 24892,
"s": 24854,
"text": "This event is triggered after a spin."
},
{
"code": null,
"e": 24916,
"s": 24892,
"text": "Event - stop(event, ui)"
},
{
"code": null,
"e": 25010,
"s": 24916,
"text": "This event is triggered after a spin. Where event is of type Event, and ui is of type Object."
},
{
"code": null,
"e": 25017,
"s": 25010,
"text": "Syntax"
},
{
"code": null,
"e": 25083,
"s": 25017,
"text": "$( \".selector\" ).spinner({\n stop: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 25228,
"s": 25083,
"text": "The following example demonstrates the event method usage in spinner widgets. This example demonstrates the use of events spin, change and stop."
},
{
"code": null,
"e": 26698,
"s": 25228,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Spinner functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style type = \"text/css\">\n #spinner-8 input {width: 100px}\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#spinner-8\" ).spinner({\n spin: function( event, ui ) {\n var result = $( \"#result-2\" );\n result.append( \"Spin Value: \"+$( \"#spinner-8\" ).spinner(\"value\") );\n },\n change: function( event, ui ) {\n var result = $( \"#result-2\" );\n result.append( \"Change value: \"+$( \"#spinner-8\" ).spinner(\"value\") );\n },\n stop: function( event, ui ) {\n var result = $( \"#result-2\" );\n result.append( \"Stop value: \"+$( \"#spinner-8\" ).spinner(\"value\") );\n }\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"example\">\n <input type = \"text\" id = \"spinner-8\" value = \"0\" />\n </div>\n <span id = \"result-2\"></span>\n </body>\n</html>"
},
{
"code": null,
"e": 26862,
"s": 26698,
"text": "Let us save the above code in an HTML file spinnerexample.htm and open it in a standard browser which supports javascript, you must also see the following output −"
},
{
"code": null,
"e": 27076,
"s": 26862,
"text": "In the above example change the value of the spinner and see, the messages being displayed below for spin and stop events. Now change the focus of the spinner and you see a message being displayed on change event."
},
{
"code": null,
"e": 27360,
"s": 27076,
"text": "The spinner widget is built with the widget factory and can be extended. To extend widgets, we can either override or add to the behavior of existing methods. Following method provides as extension point with the same API stability as the spinner methods. Listed in the above table."
},
{
"code": null,
"e": 27614,
"s": 27360,
"text": "This method return a String which is an HTML. This HTML can be used for the spinner's increment and decrement buttons. Each button must be given a ui-spinner-button class name for the associated events to work. This method does not accept any arguments."
},
{
"code": null,
"e": 27655,
"s": 27614,
"text": "Extension Point - _buttonHtml(event, ui)"
},
{
"code": null,
"e": 27909,
"s": 27655,
"text": "This method return a String which is an HTML. This HTML can be used for the spinner's increment and decrement buttons. Each button must be given a ui-spinner-button class name for the associated events to work. This method does not accept any arguments."
},
{
"code": null,
"e": 27922,
"s": 27909,
"text": "Code Example"
},
{
"code": null,
"e": 28023,
"s": 27922,
"text": "_buttonHtml: function() {\n return \"\" +\n \"\" +\n \"▲\" +\n \"\" +\n \"\" +\n \"▼\" +\n \"\";\n}"
},
{
"code": null,
"e": 28143,
"s": 28023,
"text": "This method determine the HTML to use to wrap the spinner's <input> element. This method does not accept any arguments."
},
{
"code": null,
"e": 28187,
"s": 28143,
"text": "Extension Point - _uiSpinnerHtml(event, ui)"
},
{
"code": null,
"e": 28307,
"s": 28187,
"text": "This method determine the HTML to use to wrap the spinner's <input> element. This method does not accept any arguments."
},
{
"code": null,
"e": 28320,
"s": 28307,
"text": "Code Example"
},
{
"code": null,
"e": 28364,
"s": 28320,
"text": "_uiSpinnerHtml: function() {\n return \"\";\n}"
},
{
"code": null,
"e": 28371,
"s": 28364,
"text": " Print"
},
{
"code": null,
"e": 28382,
"s": 28371,
"text": " Add Notes"
}
] |
Data Analysis with Python - GeeksforGeeks
|
26 Apr, 2022
Data Analysis is the technique to collect, transform, and organize data to make future predictions, and make informed data-driven decisions. It also helps to find possible solutions for a business problem. There are six steps for Data Analysis. They are:
Ask or Specify Data Requirements
Prepare or Collect Data
Clean and Process
Analyze
Share
Act or Report
Each step has its own process and tools to make overall conclusions based on the data.
Note: To know more about these steps refer to our Six Steps of Data Analysis Process tutorial.
In this article, we will discuss how to do data analysis with Python. We will discuss all sorts of data analysis i.e. analyzing numerical data with NumPy, Tabular data with Pandas, data visualization Matplotlib, and Exploratory data analysis.
NumPy is an array processing package in Python and provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python.
NumPy Array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, the number of dimensions of the array is called the rank of the array. A tuple of integers giving the size of the array along each dimension is known as the shape of the array.
NumPy arrays can be created in multiple ways, with various ranks. It can also be created with the use of different data types like lists, tuples, etc. The type of the resultant array is deduced from the type of the elements in the sequences. NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation.
Python3
import numpy as np b = np.empty(2, dtype = int)print("Matrix b : \n", b) a = np.empty([2, 2], dtype = int)print("\nMatrix a : \n", a) c = np.empty([3, 3])print("\nMatrix c : \n", c)
Output:
Python3
import numpy as np b = np.zeros(2, dtype = int)print("Matrix b : \n", b) a = np.zeros([2, 2], dtype = int)print("\nMatrix a : \n", a) c = np.zeros([3, 3])print("\nMatrix c : \n", c)
Output:
Matrix b :
[0 0]
Matrix a :
[[0 0]
[0 0]]
Matrix c :
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
Arithmetic Operations
Addition:
Python3
import numpy as np # Defining both the matricesa = np.array([5, 72, 13, 100])b = np.array([2, 5, 10, 30]) # Performing addition using arithmetic operatoradd_ans = a+bprint(add_ans) # Performing addition using numpy functionadd_ans = np.add(a, b)print(add_ans) # The same functions and operations can be used for# multiple matricesc = np.array([1, 2, 3, 4])add_ans = a+b+cprint(add_ans) add_ans = np.add(a, b, c)print(add_ans)
Output:
[ 7 77 23 130]
[ 7 77 23 130]
[ 8 79 26 134]
[ 7 77 23 130]
Subtraction:
Python3
import numpy as np # Defining both the matricesa = np.array([5, 72, 13, 100])b = np.array([2, 5, 10, 30]) # Performing subtraction using arithmetic operatorsub_ans = a-bprint(sub_ans) # Performing subtraction using numpy functionsub_ans = np.subtract(a, b)print(sub_ans)
Output:
[ 3 67 3 70]
[ 3 67 3 70]
Multiplication:
Python3
import numpy as np # Defining both the matricesa = np.array([5, 72, 13, 100])b = np.array([2, 5, 10, 30]) # Performing multiplication using arithmetic# operatormul_ans = a*bprint(mul_ans) # Performing multiplication using numpy functionmul_ans = np.multiply(a, b)print(mul_ans)
Output:
[ 10 360 130 3000]
[ 10 360 130 3000]
Division:
Python3
import numpy as np # Defining both the matricesa = np.array([5, 72, 13, 100])b = np.array([2, 5, 10, 30]) # Performing division using arithmetic operatorsdiv_ans = a/bprint(div_ans) # Performing division using numpy functionsdiv_ans = np.divide(a, b)print(div_ans)
Output:
[ 2.5 14.4 1.3 3.33333333]
[ 2.5 14.4 1.3 3.33333333]
For more information, refer to our NumPy – Arithmetic Operations Tutorial
Indexing can be done in NumPy by using an array as an index. In the case of the slice, a view or shallow copy of the array is returned but in the index array, a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples. The last element is indexed by -1 second last by -2 and so on.
Python3
# Python program to demonstrate # the use of index arrays.import numpy as np # Create a sequence of integers from# 10 to 1 with a step of -2a = np.arange(10, 1, -2) print("\n A sequential array with a negative step: \n",a) # Indexes are specified inside the np.array method.newarr = a[np.array([3, 1, 2 ])]print("\n Elements at these indices are:\n",newarr)
Output:
A sequential array with a negative step:
[10 8 6 4 2]
Elements at these indices are:
[4 8 6]
Consider the syntax x[obj] where x is the array and obj is the index. The slice object is the index in the case of basic slicing. Basic slicing occurs when obj is :
a slice object that is of the form start: stop: step
an integer
or a tuple of slice objects and integers
All arrays generated by basic slicing are always the view in the original array.
Python3
# Python program for basic slicing.import numpy as np # Arrange elements from 0 to 19a = np.arrange(20)print("\n Array is:\n ",a) # a[start:stop:step]print("\n a[-8:17:1] = ",a[-8:17:1]) # The : operator means all elements till the end.print("\n a[10:] = ",a[10:])
Output:
Array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
a[-8:17:1] = [12 13 14 15 16]
a[10:] = [10 11 12 13 14 15 16 17 18 19]
Ellipsis can also be used along with basic slicing. Ellipsis (...) is the number of : objects needed to make a selection tuple of the same length as the dimensions of the array.
Python3
# Python program for indexing using basic slicing with ellipsisimport numpy as np # A 3 dimensional array.b = np.array([[[1, 2, 3],[4, 5, 6]], [[7, 8, 9],[10, 11, 12]]]) print(b[...,1]) #Equivalent to b[: ,: ,1 ]
Output:
[[ 2 5]
[ 8 11]]
The term broadcasting refers to how numpy treats arrays with different Dimension during arithmetic operations which lead to certain constraints, the smaller array is broadcast across the larger array so that they have compatible shapes.
Let’s assume that we have a large data set, each datum is a list of parameters. In Numpy we have a 2-D array, where each row is a datum and the number of rows is the size of the data set. Suppose we want to apply some sort of scaling to all these data every parameter gets its own scaling factor or say Every parameter is multiplied by some factor.
Just to have some clear understanding, let’s count calories in foods using a macro-nutrient breakdown. Roughly put, the caloric parts of food are made of fats (9 calories per gram), protein (4 cpg) and carbs (4 cpg). So if we list some foods (our data), and for each food list its macro-nutrient breakdown (parameters), we can then multiply each nutrient by its caloric value (apply scaling) to compute the caloric breakdown of every food item.
With this transformation, we can now compute all kinds of useful information. For example, what is the total number of calories present in some food or, given a breakdown of my dinner know how much calories did I get from protein and so on.
Let’s see a naive way of producing this computation with Numpy:
Python3
import numpy as np macros = np.array([[0.8, 2.9, 3.9],[52.4, 23.6, 36.5],[55.2, 31.7, 23.9],[14.4, 11, 4.9]]) # Create a new array filled with zeros,# of the same shape as macros.result = np.zeros_like(macros) cal_per_macro = np.array([3, 3, 8]) # Now multiply each row of macros by# cal_per_macro. In Numpy, `*` is# element-wise multiplication between two arrays.for i in range(macros.shape[0]): result[i, :] = macros[i, :] * cal_per_macro result
Output:
array([[ 2.4, 8.7, 31.2],
[157.2, 70.8, 292. ],
[165.6, 95.1, 191.2],
[ 43.2, 33. , 39.2]])
Broadcasting Rules: Broadcasting two arrays together follow these rules:
If the arrays don’t have the same rank then prepend the shape of the lower rank array with 1s until both shapes have the same length.
The two arrays are compatible in a dimension if they have the same size in the dimension or if one of the arrays has size 1 in that dimension.
The arrays can be broadcast together iff they are compatible with all dimensions.
After broadcasting, each array behaves as if it had shape equal to the element-wise maximum of shapes of the two input arrays.
In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension.
Python3
import numpy as np v = np.array([12, 24, 36])w = np.array([45, 55]) # To compute an outer product we first# reshape v to a column vector of shape 3x1# then broadcast it against w to yield an output# of shape 3x2 which is the outer product of v and wprint(np.reshape(v, (3, 1)) * w) X = np.array([[12, 22, 33], [45, 55, 66]]) # x has shape 2x3 and v has shape (3, )# so they broadcast to 2x3,print(X + v) # Add a vector to each column of a matrix X has# shape 2x3 and w has shape (2, ) If we transpose X# then it has shape 3x2 and can be broadcast against w# to yield a result of shape 3x2. # Transposing this yields the final result# of shape 2x3 which is the matrix.print((X.T + w).T) # Another solution is to reshape w to be a column# vector of shape 2X1 we can then broadcast it# directly against X to produce the same output.print(X + np.reshape(w, (2, 1))) # Multiply a matrix by a constant, X has shape 2x3.# Numpy treats scalars as arrays of shape();# these can be broadcast together to shape 2x3.print(X * 2)
Output:
[[ 540 660]
[1080 1320]
[1620 1980]]
[[ 24 46 69]
[ 57 79 102]]
[[ 57 67 78]
[100 110 121]]
[[ 57 67 78]
[100 110 121]]
[[ 24 44 66]
[ 90 110 132]]
Note: For more information, refer to our Python NumPy Tutorial.
Python Pandas Is used for relational or labeled data and provides various data structures for manipulating such data and time series. This library is built on top of the NumPy library. This module is generally imported as:
import pandas as pd
Here, pd is referred to as an alias to the Pandas. However, it is not necessary to import the library using the alias, it just helps in writing less amount code every time a method or property is called. Pandas generally provide two data structures for manipulating data, They are:
Series
Dataframe
Series:
Pandas Series is a one-dimensional labelled array capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are collectively called indexes. Pandas Series is nothing but a column in an excel sheet. Labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index.
It can be created using the Series() function by loading the dataset from the existing storage like SQL, Database, CSV Files, Excel Files, etc., or from data structures like lists, dictionaries, etc.
Python3
import pandas as pdimport numpy as np # Creating empty seriesser = pd.Series() print(ser) # simple arraydata = np.array(['g', 'e', 'e', 'k', 's']) ser = pd.Series(data)print(ser)
Output:
Dataframe:
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns.
It can be created using the Dataframe() method and just like series it can also be from different file types and data structures.
Python3
import pandas as pd # Calling DataFrame constructordf = pd.DataFrame()print(df) # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on listdf = pd.DataFrame(lst)df
Output:
We can create a dataframe from the CSV files using the read_csv() function.
Note: This dataset can be downloaded from here.
Python3
import pandas as pd # Reading the CSV filedf = pd.read_csv("Iris.csv") # Printing top 5 rowsdf.head()
Output:
Pandas dataframe.filter() function is used to Subset rows or columns of dataframe according to labels in the specified index. Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index.
Python3
import pandas as pd # Reading the CSV filedf = pd.read_csv("Iris.csv") # applying filter functiondf.filter(["Species", "SepalLengthCm", "SepalLengthCm"]).head()
Output:
In order to sort the data frame in pandas, the function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order.
Python3
import pandas as pd # Reading the CSV filedf = pd.read_csv("Iris.csv") # applying filter functiondf.sort_values(by=['SepalLengthCm'])
Output:
Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. In real data science projects, you’ll be dealing with large amounts of data and trying things over and over, so for efficiency, we use the Groupby concept. Groupby mainly refers to a process involving one or more of the following steps they are:
Splitting: It is a process in which we split data into group by applying some conditions on datasets.
Applying: It is a process in which we apply a function to each group independently.
Combining: It is a process in which we combine different datasets after applying groupby and results into a data structure.
The following image will help in understanding a process involve in Groupby concept.
1. Group the unique values from the Team column
2. Now there’s a bucket for each group
3. Toss the other data into the buckets
4. Apply a function on the weight column of each bucket.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name': ['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age': [27, 24, 22, 32, 33, 36, 27, 32], 'Address': ['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification': ['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFramedf = pd.DataFrame(data1) print("Original Dataframe")display(df) # applying groupby() function to# group the data on Name value.gk = df.groupby('Name') # Let's print the first entries# in all the groups formed.print("After Creating Groups")gk.first()
Output:
Applying function to group:
After splitting a data into a group, we apply a function to each group in order to do that we perform some operations they are:
Aggregation: It is a process in which we compute a summary statistic (or statistics) about each group. For Example, Compute group sums or means
Transformation: It is a process in which we perform some group-specific computations and return a like-indexed. For Example, Filling NAs within groups with a value derived from each group
Filtration: It is a process in which we discard some groups, according to a group-wise computation that evaluates True or False. For Example, Filtering out data based on the group sum or mean
Aggregation is a process in which we compute a summary statistic about each group. The aggregated function returns a single aggregated value for each group. After splitting data into groups using groupby function, several aggregation operations can be performed on the grouped data.
Python3
# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name': ['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age': [27, 24, 22, 32, 33, 36, 27, 32], 'Address': ['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification': ['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFramedf = pd.DataFrame(data1) # performing aggregation using# aggregate method grp1 = df.groupby('Name') grp1.aggregate(np.sum)
Output:
In order to concat dataframe, we use concat() function which helps in concatenating a dataframe. This function does all the heavy lifting of performing concatenation operations along with an axis of Pandas objects while performing optional set logic (union or intersection) of the indexes (if any) on the other axes.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee data data1 = {'key': ['K0', 'K1', 'K2', 'K3'], 'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32],} # Define a dictionary containing employee data data2 = {'key': ['K0', 'K1', 'K2', 'K3'], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj'], 'Qualification':['Btech', 'B.A', 'Bcom', 'B.hons']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2) display(df, df1) # combining series and dataframeres = pd.concat([df, df1], axis=1) res
Output:
When we need to combine very large DataFrames, joins serve as a powerful way to perform these operations swiftly. Joins can only be done on two DataFrames at a time, denoted as left and right tables. The key is the common column that the two DataFrames will be joined on. It’s a good practice to use keys that have unique values throughout the column to avoid unintended duplication of row values. Pandas provide a single function, merge(), as the entry point for all standard database join operations between DataFrame objects.
There are four basic ways to handle the join (inner, left, right, and outer), depending on which rows must retain their data.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee data data1 = {'key': ['K0', 'K1', 'K2', 'K3'], 'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32],} # Define a dictionary containing employee data data2 = {'key': ['K0', 'K1', 'K2', 'K3'], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj'], 'Qualification':['Btech', 'B.A', 'Bcom', 'B.hons']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2) display(df, df1) # using .merge() functionres = pd.merge(df, df1, on='key') res
Output:
In order to join dataframe, we use .join() function this function is used for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee data data1 = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32]} # Define a dictionary containing employee data data2 = {'Address':['Allahabad', 'Kannuaj', 'Allahabad', 'Kannuaj'], 'Qualification':['MCA', 'Phd', 'Bcom', 'B.hons']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1,index=['K0', 'K1', 'K2', 'K3']) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2, index=['K0', 'K2', 'K3', 'K4']) display(df, df1) # joining dataframeres = df.join(df1) res
Output:
For more information, refer to our Pandas Merging, Joining, and Concatenating tutorial
For a complete guide on Pandas refer to our Pandas Tutorial.
Matplotlib is easy to use and an amazing visualizing library in Python. It is built on NumPy arrays and designed to work with the broader SciPy stack and consists of several plots like line, bar, scatter, histogram, etc.
Pyplot is a Matplotlib module that provides a MATLAB-like interface. Pyplot provides functions that interact with the figure i.e. creates a figure, decorates the plot with labels, creates plotting area in a figure.
Python3
# Python program to show pyplot moduleimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [1, 4, 9, 16])plt.axis([0, 6, 0, 20])plt.show()
Output:
A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. It can be created using the bar() method.
Here we will use the iris dataset only
Python3
import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv("Iris.csv") # This will plot a simple bar chartplt.bar(df['Species'], df['SepalLengthCm']) # Title to the plotplt.title("Iris Dataset") # Adding the legendsplt.legend(["bar"])plt.show()
Output:
A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. To create a histogram the first step is to create a bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values which fall into each of the intervals. Bins are clearly identified as consecutive, non-overlapping intervals of variables. The hist() function is used to compute and create a histogram of x.
Python3
import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv("Iris.csv") plt.hist(df["SepalLengthCm"]) # Title to the plotplt.title("Histogram") # Adding the legendsplt.legend(["SepalLengthCm"])plt.show()
Output:
Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot.
Python3
import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv("Iris.csv") plt.scatter(df["Species"], df["SepalLengthCm"]) # Title to the plotplt.title("Scatter Plot") # Adding the legendsplt.legend(["SepalLengthCm"])plt.show()
Output:
A boxplot,Correlation also known as a box and whisker plot. It is a very good visual representation when it comes to measuring the data distribution. Clearly plots the median values, outliers and the quartiles. Understanding data distribution is another important factor which leads to better model building. If data has outliers, box plot is a recommended way to identify them and take necessary actions. The box and whiskers chart shows how data is spread out. Five pieces of information are generally included in the chart
The minimum is shown at the far left of the chart, at the end of the left ‘whisker’
First quartile, Q1, is the far left of the box (left whisker)
The median is shown as a line in the center of the box
Third quartile, Q3, shown at the far right of the box (right whisker)
The maximum is at the far right of the box
Representation of box plot
Python3
import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv("Iris.csv") plt.boxplot(df["SepalWidthCm"]) # Title to the plotplt.title("Box Plot") # Adding the legendsplt.legend(["SepalWidthCm"])plt.show()
Output:
A 2-D Heatmap is a data visualization tool that helps to represent the magnitude of the phenomenon in form of colors. A correlation heatmap is a heatmap that shows a 2D correlation matrix between two discrete dimensions, using colored cells to represent data from usually a monochromatic scale. The values of the first dimension appear as the rows of the table while of the second dimension as a column. The color of the cell is proportional to the number of measurements that match the dimensional value. This makes correlation heatmaps ideal for data analysis since it makes patterns easily readable and highlights the differences and variation in the same data. A correlation heatmap, like a regular heatmap, is assisted by a colorbar making data easily readable and comprehensible.
Note: The data here has to be passed with corr() method to generate a correlation heatmap. Also, corr() itself eliminates columns which will be of no use while generating a correlation heatmap and selects those which can be used.
Python3
import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv("Iris.csv") plt.imshow(df.corr() , cmap = 'autumn' , interpolation = 'nearest' ) plt.title("Heat Map")plt.show()
Output:
For more information on data visualization refer to our below tutorials –
Data Visualization using Matplotlib
Data Visualization with Python Seaborn
Data Visualisation in Python using Matplotlib and Seaborn
Using Plotly for Interactive Data Visualization in Python
Interactive Data Visualization with Bokeh
Exploratory Data Analysis (EDA) is a technique to analyze data using some visual Techniques. With this technique, we can get detailed information about the statistical summary of the data. We will also be able to deal with the duplicates values, outliers, and also see some trends or patterns present in the dataset.
Note: We will be using Iris Dataset.
We will use the shape parameter to get the shape of the dataset.
Example:
Python3
df.shape
Output:
(150, 6)
We can see that the dataframe contains 6 columns and 150 rows.
Now, let’s also the columns and their data types. For this, we will use the info() method.
Example:
Python3
df.info()
Output:
We can see that only one column has categorical data and all the other columns are of the numeric type with non-Null entries.
Let’s get a quick statistical summary of the dataset using the describe() method. The describe() function applies basic statistical computations on the dataset like extreme values, count of data points standard deviation, etc. Any missing value or NaN value is automatically skipped. describe() function gives a good picture of the distribution of data.
Example:
Python3
df.describe()
Output:
We can see the count of each column along with their mean value, standard deviation, minimum and maximum values.
We will check if our data contains any missing values or not. Missing values can occur when no information is provided for one or more items or for a whole unit. We will use the isnull() method.
Example:
Python3
df.isnull().sum()
Output:
We can see that no column as any missing value.
Let’s see if our dataset contains any duplicates or not. Pandas drop_duplicates() method helps in removing duplicates from the data frame.
Example:
Python3
data = df.drop_duplicates(subset ="Species",)data
Output:
We can see that there are only three unique species. Let’s see if the dataset is balanced or not i.e. all the species contain equal amounts of rows or not. We will use the Series.value_counts() function. This function returns a Series containing counts of unique values.
Example:
Python3
df.value_counts("Species")
Output:
We can see that all the species contain an equal amount of rows, so we should not delete any entries.
We will see the relationship between the sepal length and sepal width and also between petal length and petal width.
Example 1: Comparing Sepal Length and Sepal Width
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.scatterplot(x='SepalLengthCm', y='SepalWidthCm', hue='Species', data=df, ) # Placing Legend outside the Figureplt.legend(bbox_to_anchor=(1, 1), loc=2) plt.show()
Output:
From the above plot, we can infer that –
Species Setosa has smaller sepal lengths but larger sepal widths.
Versicolor Species lies in the middle of the other two species in terms of sepal length and width
Species Virginica has larger sepal lengths but smaller sepal widths.
Example 2: Comparing Petal Length and Petal Width
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.scatterplot(x='PetalLengthCm', y='PetalWidthCm', hue='Species', data=df, ) # Placing Legend outside the Figureplt.legend(bbox_to_anchor=(1, 1), loc=2) plt.show()
Output:
From the above plot, we can infer that –
Species Setosa has smaller petal lengths and widths.
Versicolor Species lies in the middle of the other two species in terms of petal length and width
Species Virginica has the largest of petal lengths and widths.
Let’s plot all the column’s relationships using a pairplot. It can be used for multivariate analysis.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.pairplot(df.drop(['Id'], axis = 1), hue='Species', height=2)
Output:
We can see many types of relationships from this plot such as the species Seotsa has the smallest of petals widths and lengths. It also has the smallest sepal length but larger sepal widths. Such information can be gathered about any other species.
Pandas dataframe.corr() is used to find the pairwise correlation of all columns in the dataframe. Any NA values are automatically excluded. For any non-numeric data type columns in the dataframe it is ignored.
Example:
Python3
data.corr(method='pearson')
Output:
The heatmap is a data visualization technique that is used to analyze the dataset as colors in two dimensions. Basically, it shows a correlation between all numerical variables in the dataset. In simpler terms, we can plot the above-found correlation using the heatmaps.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.heatmap(df.corr(method='pearson').drop( ['Id'], axis=1).drop(['Id'], axis=0), annot = True); plt.show()
Output:
From the above graph, we can see that –
Petal width and petal length have high correlations.
Petal length and sepal width have good correlations.
Petal Width and Sepal length have good correlations.
An Outlier is a data-item/object that deviates significantly from the rest of the (so-called normal)objects. They can be caused by measurement or execution errors. The analysis for outlier detection is referred to as outlier mining. There are many ways to detect the outliers, and the removal process is the data frame same as removing a data item from the panda’s dataframe.
Let’s consider the iris dataset and let’s plot the boxplot for the SepalWidthCm column.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # Load the datasetdf = pd.read_csv('Iris.csv') sns.boxplot(x='SepalWidthCm', data=df)
Output:
In the above graph, the values above 4 and below 2 are acting as outliers.
For removing the outlier, one must follow the same process of removing an entry from the dataset using its exact position in the dataset because in all the above methods of detecting the outliers end result is the list of all those data items that satisfy the outlier definition according to the method used.
Example: We will detect the outliers using IQR and then we will remove them. We will also draw the boxplot to see if the outliers are removed or not.
Python3
# Importingimport sklearnfrom sklearn.datasets import load_bostonimport pandas as pdimport seaborn as sns # Load the datasetdf = pd.read_csv('Iris.csv') # IQRQ1 = np.percentile(df['SepalWidthCm'], 25, interpolation = 'midpoint') Q3 = np.percentile(df['SepalWidthCm'], 75, interpolation = 'midpoint')IQR = Q3 - Q1 print("Old Shape: ", df.shape) # Upper boundupper = np.where(df['SepalWidthCm'] >= (Q3+1.5*IQR)) # Lower boundlower = np.where(df['SepalWidthCm'] <= (Q1-1.5*IQR)) # Removing the Outliersdf.drop(upper[0], inplace = True)df.drop(lower[0], inplace = True) print("New Shape: ", df.shape) sns.boxplot(x='SepalWidthCm', data=df)
Output:
For more information about EDA, refer to our below tutorials –
What is Exploratory Data Analysis ?
Exploratory Data Analysis in Python | Set 1
Exploratory Data Analysis in Python | Set 2
Exploratory Data Analysis on Iris Dataset
surindertarika1234
abhishek0719kadiyan
data-science
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 24547,
"s": 24292,
"text": "Data Analysis is the technique to collect, transform, and organize data to make future predictions, and make informed data-driven decisions. It also helps to find possible solutions for a business problem. There are six steps for Data Analysis. They are:"
},
{
"code": null,
"e": 24580,
"s": 24547,
"text": "Ask or Specify Data Requirements"
},
{
"code": null,
"e": 24604,
"s": 24580,
"text": "Prepare or Collect Data"
},
{
"code": null,
"e": 24622,
"s": 24604,
"text": "Clean and Process"
},
{
"code": null,
"e": 24630,
"s": 24622,
"text": "Analyze"
},
{
"code": null,
"e": 24636,
"s": 24630,
"text": "Share"
},
{
"code": null,
"e": 24650,
"s": 24636,
"text": "Act or Report"
},
{
"code": null,
"e": 24737,
"s": 24650,
"text": "Each step has its own process and tools to make overall conclusions based on the data."
},
{
"code": null,
"e": 24833,
"s": 24737,
"text": "Note: To know more about these steps refer to our Six Steps of Data Analysis Process tutorial. "
},
{
"code": null,
"e": 25076,
"s": 24833,
"text": "In this article, we will discuss how to do data analysis with Python. We will discuss all sorts of data analysis i.e. analyzing numerical data with NumPy, Tabular data with Pandas, data visualization Matplotlib, and Exploratory data analysis."
},
{
"code": null,
"e": 25294,
"s": 25076,
"text": "NumPy is an array processing package in Python and provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python."
},
{
"code": null,
"e": 25599,
"s": 25294,
"text": "NumPy Array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, the number of dimensions of the array is called the rank of the array. A tuple of integers giving the size of the array along each dimension is known as the shape of the array. "
},
{
"code": null,
"e": 25995,
"s": 25599,
"text": "NumPy arrays can be created in multiple ways, with various ranks. It can also be created with the use of different data types like lists, tuples, etc. The type of the resultant array is deduced from the type of the elements in the sequences. NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation."
},
{
"code": null,
"e": 26003,
"s": 25995,
"text": "Python3"
},
{
"code": "import numpy as np b = np.empty(2, dtype = int)print(\"Matrix b : \\n\", b) a = np.empty([2, 2], dtype = int)print(\"\\nMatrix a : \\n\", a) c = np.empty([3, 3])print(\"\\nMatrix c : \\n\", c)",
"e": 26191,
"s": 26003,
"text": null
},
{
"code": null,
"e": 26199,
"s": 26191,
"text": "Output:"
},
{
"code": null,
"e": 26207,
"s": 26199,
"text": "Python3"
},
{
"code": "import numpy as np b = np.zeros(2, dtype = int)print(\"Matrix b : \\n\", b) a = np.zeros([2, 2], dtype = int)print(\"\\nMatrix a : \\n\", a) c = np.zeros([3, 3])print(\"\\nMatrix c : \\n\", c)",
"e": 26395,
"s": 26207,
"text": null
},
{
"code": null,
"e": 26403,
"s": 26395,
"text": "Output:"
},
{
"code": null,
"e": 26502,
"s": 26403,
"text": "Matrix b : \n [0 0]\n\nMatrix a : \n [[0 0]\n [0 0]]\n\nMatrix c : \n [[0. 0. 0.]\n [0. 0. 0.]\n [0. 0. 0.]]"
},
{
"code": null,
"e": 26524,
"s": 26502,
"text": "Arithmetic Operations"
},
{
"code": null,
"e": 26535,
"s": 26524,
"text": "Addition: "
},
{
"code": null,
"e": 26543,
"s": 26535,
"text": "Python3"
},
{
"code": "import numpy as np # Defining both the matricesa = np.array([5, 72, 13, 100])b = np.array([2, 5, 10, 30]) # Performing addition using arithmetic operatoradd_ans = a+bprint(add_ans) # Performing addition using numpy functionadd_ans = np.add(a, b)print(add_ans) # The same functions and operations can be used for# multiple matricesc = np.array([1, 2, 3, 4])add_ans = a+b+cprint(add_ans) add_ans = np.add(a, b, c)print(add_ans)",
"e": 26974,
"s": 26543,
"text": null
},
{
"code": null,
"e": 26982,
"s": 26974,
"text": "Output:"
},
{
"code": null,
"e": 27054,
"s": 26982,
"text": "[ 7 77 23 130]\n[ 7 77 23 130]\n[ 8 79 26 134]\n[ 7 77 23 130]"
},
{
"code": null,
"e": 27067,
"s": 27054,
"text": "Subtraction:"
},
{
"code": null,
"e": 27075,
"s": 27067,
"text": "Python3"
},
{
"code": "import numpy as np # Defining both the matricesa = np.array([5, 72, 13, 100])b = np.array([2, 5, 10, 30]) # Performing subtraction using arithmetic operatorsub_ans = a-bprint(sub_ans) # Performing subtraction using numpy functionsub_ans = np.subtract(a, b)print(sub_ans)",
"e": 27349,
"s": 27075,
"text": null
},
{
"code": null,
"e": 27357,
"s": 27349,
"text": "Output:"
},
{
"code": null,
"e": 27385,
"s": 27357,
"text": "[ 3 67 3 70]\n[ 3 67 3 70]"
},
{
"code": null,
"e": 27401,
"s": 27385,
"text": "Multiplication:"
},
{
"code": null,
"e": 27409,
"s": 27401,
"text": "Python3"
},
{
"code": "import numpy as np # Defining both the matricesa = np.array([5, 72, 13, 100])b = np.array([2, 5, 10, 30]) # Performing multiplication using arithmetic# operatormul_ans = a*bprint(mul_ans) # Performing multiplication using numpy functionmul_ans = np.multiply(a, b)print(mul_ans)",
"e": 27690,
"s": 27409,
"text": null
},
{
"code": null,
"e": 27698,
"s": 27690,
"text": "Output:"
},
{
"code": null,
"e": 27742,
"s": 27698,
"text": "[ 10 360 130 3000]\n[ 10 360 130 3000]"
},
{
"code": null,
"e": 27752,
"s": 27742,
"text": "Division:"
},
{
"code": null,
"e": 27760,
"s": 27752,
"text": "Python3"
},
{
"code": "import numpy as np # Defining both the matricesa = np.array([5, 72, 13, 100])b = np.array([2, 5, 10, 30]) # Performing division using arithmetic operatorsdiv_ans = a/bprint(div_ans) # Performing division using numpy functionsdiv_ans = np.divide(a, b)print(div_ans)",
"e": 28028,
"s": 27760,
"text": null
},
{
"code": null,
"e": 28036,
"s": 28028,
"text": "Output:"
},
{
"code": null,
"e": 28136,
"s": 28036,
"text": "[ 2.5 14.4 1.3 3.33333333]\n[ 2.5 14.4 1.3 3.33333333]"
},
{
"code": null,
"e": 28210,
"s": 28136,
"text": "For more information, refer to our NumPy – Arithmetic Operations Tutorial"
},
{
"code": null,
"e": 28572,
"s": 28210,
"text": "Indexing can be done in NumPy by using an array as an index. In the case of the slice, a view or shallow copy of the array is returned but in the index array, a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples. The last element is indexed by -1 second last by -2 and so on."
},
{
"code": null,
"e": 28580,
"s": 28572,
"text": "Python3"
},
{
"code": "# Python program to demonstrate # the use of index arrays.import numpy as np # Create a sequence of integers from# 10 to 1 with a step of -2a = np.arange(10, 1, -2) print(\"\\n A sequential array with a negative step: \\n\",a) # Indexes are specified inside the np.array method.newarr = a[np.array([3, 1, 2 ])]print(\"\\n Elements at these indices are:\\n\",newarr)",
"e": 28942,
"s": 28580,
"text": null
},
{
"code": null,
"e": 28950,
"s": 28942,
"text": "Output:"
},
{
"code": null,
"e": 29052,
"s": 28950,
"text": "A sequential array with a negative step: \n [10 8 6 4 2]\n\n Elements at these indices are:\n [4 8 6]"
},
{
"code": null,
"e": 29217,
"s": 29052,
"text": "Consider the syntax x[obj] where x is the array and obj is the index. The slice object is the index in the case of basic slicing. Basic slicing occurs when obj is :"
},
{
"code": null,
"e": 29270,
"s": 29217,
"text": "a slice object that is of the form start: stop: step"
},
{
"code": null,
"e": 29281,
"s": 29270,
"text": "an integer"
},
{
"code": null,
"e": 29322,
"s": 29281,
"text": "or a tuple of slice objects and integers"
},
{
"code": null,
"e": 29403,
"s": 29322,
"text": "All arrays generated by basic slicing are always the view in the original array."
},
{
"code": null,
"e": 29411,
"s": 29403,
"text": "Python3"
},
{
"code": "# Python program for basic slicing.import numpy as np # Arrange elements from 0 to 19a = np.arrange(20)print(\"\\n Array is:\\n \",a) # a[start:stop:step]print(\"\\n a[-8:17:1] = \",a[-8:17:1]) # The : operator means all elements till the end.print(\"\\n a[10:] = \",a[10:])",
"e": 29679,
"s": 29411,
"text": null
},
{
"code": null,
"e": 29687,
"s": 29679,
"text": "Output:"
},
{
"code": null,
"e": 29835,
"s": 29687,
"text": "Array is:\n[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]\n\na[-8:17:1] = [12 13 14 15 16]\n\na[10:] = [10 11 12 13 14 15 16 17 18 19] "
},
{
"code": null,
"e": 30013,
"s": 29835,
"text": "Ellipsis can also be used along with basic slicing. Ellipsis (...) is the number of : objects needed to make a selection tuple of the same length as the dimensions of the array."
},
{
"code": null,
"e": 30021,
"s": 30013,
"text": "Python3"
},
{
"code": "# Python program for indexing using basic slicing with ellipsisimport numpy as np # A 3 dimensional array.b = np.array([[[1, 2, 3],[4, 5, 6]], [[7, 8, 9],[10, 11, 12]]]) print(b[...,1]) #Equivalent to b[: ,: ,1 ]",
"e": 30247,
"s": 30021,
"text": null
},
{
"code": null,
"e": 30255,
"s": 30247,
"text": "Output:"
},
{
"code": null,
"e": 30274,
"s": 30255,
"text": "[[ 2 5]\n [ 8 11]]"
},
{
"code": null,
"e": 30512,
"s": 30274,
"text": "The term broadcasting refers to how numpy treats arrays with different Dimension during arithmetic operations which lead to certain constraints, the smaller array is broadcast across the larger array so that they have compatible shapes. "
},
{
"code": null,
"e": 30861,
"s": 30512,
"text": "Let’s assume that we have a large data set, each datum is a list of parameters. In Numpy we have a 2-D array, where each row is a datum and the number of rows is the size of the data set. Suppose we want to apply some sort of scaling to all these data every parameter gets its own scaling factor or say Every parameter is multiplied by some factor."
},
{
"code": null,
"e": 31306,
"s": 30861,
"text": "Just to have some clear understanding, let’s count calories in foods using a macro-nutrient breakdown. Roughly put, the caloric parts of food are made of fats (9 calories per gram), protein (4 cpg) and carbs (4 cpg). So if we list some foods (our data), and for each food list its macro-nutrient breakdown (parameters), we can then multiply each nutrient by its caloric value (apply scaling) to compute the caloric breakdown of every food item."
},
{
"code": null,
"e": 31547,
"s": 31306,
"text": "With this transformation, we can now compute all kinds of useful information. For example, what is the total number of calories present in some food or, given a breakdown of my dinner know how much calories did I get from protein and so on."
},
{
"code": null,
"e": 31611,
"s": 31547,
"text": "Let’s see a naive way of producing this computation with Numpy:"
},
{
"code": null,
"e": 31619,
"s": 31611,
"text": "Python3"
},
{
"code": "import numpy as np macros = np.array([[0.8, 2.9, 3.9],[52.4, 23.6, 36.5],[55.2, 31.7, 23.9],[14.4, 11, 4.9]]) # Create a new array filled with zeros,# of the same shape as macros.result = np.zeros_like(macros) cal_per_macro = np.array([3, 3, 8]) # Now multiply each row of macros by# cal_per_macro. In Numpy, `*` is# element-wise multiplication between two arrays.for i in range(macros.shape[0]): result[i, :] = macros[i, :] * cal_per_macro result",
"e": 32075,
"s": 31619,
"text": null
},
{
"code": null,
"e": 32083,
"s": 32075,
"text": "Output:"
},
{
"code": null,
"e": 32204,
"s": 32083,
"text": "array([[ 2.4, 8.7, 31.2],\n [157.2, 70.8, 292. ],\n [165.6, 95.1, 191.2],\n [ 43.2, 33. , 39.2]])"
},
{
"code": null,
"e": 32277,
"s": 32204,
"text": "Broadcasting Rules: Broadcasting two arrays together follow these rules:"
},
{
"code": null,
"e": 32411,
"s": 32277,
"text": "If the arrays don’t have the same rank then prepend the shape of the lower rank array with 1s until both shapes have the same length."
},
{
"code": null,
"e": 32554,
"s": 32411,
"text": "The two arrays are compatible in a dimension if they have the same size in the dimension or if one of the arrays has size 1 in that dimension."
},
{
"code": null,
"e": 32636,
"s": 32554,
"text": "The arrays can be broadcast together iff they are compatible with all dimensions."
},
{
"code": null,
"e": 32763,
"s": 32636,
"text": "After broadcasting, each array behaves as if it had shape equal to the element-wise maximum of shapes of the two input arrays."
},
{
"code": null,
"e": 32919,
"s": 32763,
"text": "In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension."
},
{
"code": null,
"e": 32927,
"s": 32919,
"text": "Python3"
},
{
"code": "import numpy as np v = np.array([12, 24, 36])w = np.array([45, 55]) # To compute an outer product we first# reshape v to a column vector of shape 3x1# then broadcast it against w to yield an output# of shape 3x2 which is the outer product of v and wprint(np.reshape(v, (3, 1)) * w) X = np.array([[12, 22, 33], [45, 55, 66]]) # x has shape 2x3 and v has shape (3, )# so they broadcast to 2x3,print(X + v) # Add a vector to each column of a matrix X has# shape 2x3 and w has shape (2, ) If we transpose X# then it has shape 3x2 and can be broadcast against w# to yield a result of shape 3x2. # Transposing this yields the final result# of shape 2x3 which is the matrix.print((X.T + w).T) # Another solution is to reshape w to be a column# vector of shape 2X1 we can then broadcast it# directly against X to produce the same output.print(X + np.reshape(w, (2, 1))) # Multiply a matrix by a constant, X has shape 2x3.# Numpy treats scalars as arrays of shape();# these can be broadcast together to shape 2x3.print(X * 2)",
"e": 33952,
"s": 32927,
"text": null
},
{
"code": null,
"e": 33960,
"s": 33952,
"text": "Output:"
},
{
"code": null,
"e": 34124,
"s": 33960,
"text": "[[ 540 660]\n [1080 1320]\n [1620 1980]]\n[[ 24 46 69]\n [ 57 79 102]]\n[[ 57 67 78]\n [100 110 121]]\n[[ 57 67 78]\n [100 110 121]]\n[[ 24 44 66]\n [ 90 110 132]]"
},
{
"code": null,
"e": 34188,
"s": 34124,
"text": "Note: For more information, refer to our Python NumPy Tutorial."
},
{
"code": null,
"e": 34411,
"s": 34188,
"text": "Python Pandas Is used for relational or labeled data and provides various data structures for manipulating such data and time series. This library is built on top of the NumPy library. This module is generally imported as:"
},
{
"code": null,
"e": 34431,
"s": 34411,
"text": "import pandas as pd"
},
{
"code": null,
"e": 34714,
"s": 34431,
"text": "Here, pd is referred to as an alias to the Pandas. However, it is not necessary to import the library using the alias, it just helps in writing less amount code every time a method or property is called. Pandas generally provide two data structures for manipulating data, They are: "
},
{
"code": null,
"e": 34721,
"s": 34714,
"text": "Series"
},
{
"code": null,
"e": 34731,
"s": 34721,
"text": "Dataframe"
},
{
"code": null,
"e": 34740,
"s": 34731,
"text": "Series: "
},
{
"code": null,
"e": 35171,
"s": 34740,
"text": "Pandas Series is a one-dimensional labelled array capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are collectively called indexes. Pandas Series is nothing but a column in an excel sheet. Labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 35371,
"s": 35171,
"text": "It can be created using the Series() function by loading the dataset from the existing storage like SQL, Database, CSV Files, Excel Files, etc., or from data structures like lists, dictionaries, etc."
},
{
"code": null,
"e": 35379,
"s": 35371,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np # Creating empty seriesser = pd.Series() print(ser) # simple arraydata = np.array(['g', 'e', 'e', 'k', 's']) ser = pd.Series(data)print(ser)",
"e": 35564,
"s": 35379,
"text": null
},
{
"code": null,
"e": 35572,
"s": 35564,
"text": "Output:"
},
{
"code": null,
"e": 35583,
"s": 35572,
"text": "Dataframe:"
},
{
"code": null,
"e": 35922,
"s": 35583,
"text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns."
},
{
"code": null,
"e": 36052,
"s": 35922,
"text": "It can be created using the Dataframe() method and just like series it can also be from different file types and data structures."
},
{
"code": null,
"e": 36060,
"s": 36052,
"text": "Python3"
},
{
"code": "import pandas as pd # Calling DataFrame constructordf = pd.DataFrame()print(df) # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on listdf = pd.DataFrame(lst)df",
"e": 36299,
"s": 36060,
"text": null
},
{
"code": null,
"e": 36307,
"s": 36299,
"text": "Output:"
},
{
"code": null,
"e": 36383,
"s": 36307,
"text": "We can create a dataframe from the CSV files using the read_csv() function."
},
{
"code": null,
"e": 36431,
"s": 36383,
"text": "Note: This dataset can be downloaded from here."
},
{
"code": null,
"e": 36439,
"s": 36431,
"text": "Python3"
},
{
"code": "import pandas as pd # Reading the CSV filedf = pd.read_csv(\"Iris.csv\") # Printing top 5 rowsdf.head()",
"e": 36543,
"s": 36439,
"text": null
},
{
"code": null,
"e": 36551,
"s": 36543,
"text": "Output:"
},
{
"code": null,
"e": 36795,
"s": 36551,
"text": "Pandas dataframe.filter() function is used to Subset rows or columns of dataframe according to labels in the specified index. Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index."
},
{
"code": null,
"e": 36803,
"s": 36795,
"text": "Python3"
},
{
"code": "import pandas as pd # Reading the CSV filedf = pd.read_csv(\"Iris.csv\") # applying filter functiondf.filter([\"Species\", \"SepalLengthCm\", \"SepalLengthCm\"]).head()",
"e": 36966,
"s": 36803,
"text": null
},
{
"code": null,
"e": 36974,
"s": 36966,
"text": "Output:"
},
{
"code": null,
"e": 37132,
"s": 36974,
"text": "In order to sort the data frame in pandas, the function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order."
},
{
"code": null,
"e": 37140,
"s": 37132,
"text": "Python3"
},
{
"code": "import pandas as pd # Reading the CSV filedf = pd.read_csv(\"Iris.csv\") # applying filter functiondf.sort_values(by=['SepalLengthCm'])",
"e": 37276,
"s": 37140,
"text": null
},
{
"code": null,
"e": 37284,
"s": 37276,
"text": "Output:"
},
{
"code": null,
"e": 37646,
"s": 37284,
"text": "Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. In real data science projects, you’ll be dealing with large amounts of data and trying things over and over, so for efficiency, we use the Groupby concept. Groupby mainly refers to a process involving one or more of the following steps they are:"
},
{
"code": null,
"e": 37748,
"s": 37646,
"text": "Splitting: It is a process in which we split data into group by applying some conditions on datasets."
},
{
"code": null,
"e": 37832,
"s": 37748,
"text": "Applying: It is a process in which we apply a function to each group independently."
},
{
"code": null,
"e": 37956,
"s": 37832,
"text": "Combining: It is a process in which we combine different datasets after applying groupby and results into a data structure."
},
{
"code": null,
"e": 38041,
"s": 37956,
"text": "The following image will help in understanding a process involve in Groupby concept."
},
{
"code": null,
"e": 38089,
"s": 38041,
"text": "1. Group the unique values from the Team column"
},
{
"code": null,
"e": 38128,
"s": 38089,
"text": "2. Now there’s a bucket for each group"
},
{
"code": null,
"e": 38168,
"s": 38128,
"text": "3. Toss the other data into the buckets"
},
{
"code": null,
"e": 38225,
"s": 38168,
"text": "4. Apply a function on the weight column of each bucket."
},
{
"code": null,
"e": 38233,
"s": 38225,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name': ['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age': [27, 24, 22, 32, 33, 36, 27, 32], 'Address': ['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification': ['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFramedf = pd.DataFrame(data1) print(\"Original Dataframe\")display(df) # applying groupby() function to# group the data on Name value.gk = df.groupby('Name') # Let's print the first entries# in all the groups formed.print(\"After Creating Groups\")gk.first()",
"e": 39029,
"s": 38233,
"text": null
},
{
"code": null,
"e": 39037,
"s": 39029,
"text": "Output:"
},
{
"code": null,
"e": 39065,
"s": 39037,
"text": "Applying function to group:"
},
{
"code": null,
"e": 39193,
"s": 39065,
"text": "After splitting a data into a group, we apply a function to each group in order to do that we perform some operations they are:"
},
{
"code": null,
"e": 39337,
"s": 39193,
"text": "Aggregation: It is a process in which we compute a summary statistic (or statistics) about each group. For Example, Compute group sums or means"
},
{
"code": null,
"e": 39525,
"s": 39337,
"text": "Transformation: It is a process in which we perform some group-specific computations and return a like-indexed. For Example, Filling NAs within groups with a value derived from each group"
},
{
"code": null,
"e": 39717,
"s": 39525,
"text": "Filtration: It is a process in which we discard some groups, according to a group-wise computation that evaluates True or False. For Example, Filtering out data based on the group sum or mean"
},
{
"code": null,
"e": 40000,
"s": 39717,
"text": "Aggregation is a process in which we compute a summary statistic about each group. The aggregated function returns a single aggregated value for each group. After splitting data into groups using groupby function, several aggregation operations can be performed on the grouped data."
},
{
"code": null,
"e": 40008,
"s": 40000,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name': ['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age': [27, 24, 22, 32, 33, 36, 27, 32], 'Address': ['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification': ['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFramedf = pd.DataFrame(data1) # performing aggregation using# aggregate method grp1 = df.groupby('Name') grp1.aggregate(np.sum)",
"e": 40729,
"s": 40008,
"text": null
},
{
"code": null,
"e": 40737,
"s": 40729,
"text": "Output:"
},
{
"code": null,
"e": 41054,
"s": 40737,
"text": "In order to concat dataframe, we use concat() function which helps in concatenating a dataframe. This function does all the heavy lifting of performing concatenation operations along with an axis of Pandas objects while performing optional set logic (union or intersection) of the indexes (if any) on the other axes."
},
{
"code": null,
"e": 41062,
"s": 41054,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee data data1 = {'key': ['K0', 'K1', 'K2', 'K3'], 'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32],} # Define a dictionary containing employee data data2 = {'key': ['K0', 'K1', 'K2', 'K3'], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj'], 'Qualification':['Btech', 'B.A', 'Bcom', 'B.hons']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2) display(df, df1) # combining series and dataframeres = pd.concat([df, df1], axis=1) res",
"e": 41738,
"s": 41062,
"text": null
},
{
"code": null,
"e": 41746,
"s": 41738,
"text": "Output:"
},
{
"code": null,
"e": 42275,
"s": 41746,
"text": "When we need to combine very large DataFrames, joins serve as a powerful way to perform these operations swiftly. Joins can only be done on two DataFrames at a time, denoted as left and right tables. The key is the common column that the two DataFrames will be joined on. It’s a good practice to use keys that have unique values throughout the column to avoid unintended duplication of row values. Pandas provide a single function, merge(), as the entry point for all standard database join operations between DataFrame objects."
},
{
"code": null,
"e": 42401,
"s": 42275,
"text": "There are four basic ways to handle the join (inner, left, right, and outer), depending on which rows must retain their data."
},
{
"code": null,
"e": 42409,
"s": 42401,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee data data1 = {'key': ['K0', 'K1', 'K2', 'K3'], 'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32],} # Define a dictionary containing employee data data2 = {'key': ['K0', 'K1', 'K2', 'K3'], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj'], 'Qualification':['Btech', 'B.A', 'Bcom', 'B.hons']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2) display(df, df1) # using .merge() functionres = pd.merge(df, df1, on='key') res",
"e": 43077,
"s": 42409,
"text": null
},
{
"code": null,
"e": 43085,
"s": 43077,
"text": "Output:"
},
{
"code": null,
"e": 43267,
"s": 43085,
"text": "In order to join dataframe, we use .join() function this function is used for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame."
},
{
"code": null,
"e": 43275,
"s": 43267,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee data data1 = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32]} # Define a dictionary containing employee data data2 = {'Address':['Allahabad', 'Kannuaj', 'Allahabad', 'Kannuaj'], 'Qualification':['MCA', 'Phd', 'Bcom', 'B.hons']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1,index=['K0', 'K1', 'K2', 'K3']) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2, index=['K0', 'K2', 'K3', 'K4']) display(df, df1) # joining dataframeres = df.join(df1) res",
"e": 43907,
"s": 43275,
"text": null
},
{
"code": null,
"e": 43915,
"s": 43907,
"text": "Output:"
},
{
"code": null,
"e": 44002,
"s": 43915,
"text": "For more information, refer to our Pandas Merging, Joining, and Concatenating tutorial"
},
{
"code": null,
"e": 44063,
"s": 44002,
"text": "For a complete guide on Pandas refer to our Pandas Tutorial."
},
{
"code": null,
"e": 44285,
"s": 44063,
"text": "Matplotlib is easy to use and an amazing visualizing library in Python. It is built on NumPy arrays and designed to work with the broader SciPy stack and consists of several plots like line, bar, scatter, histogram, etc. "
},
{
"code": null,
"e": 44500,
"s": 44285,
"text": "Pyplot is a Matplotlib module that provides a MATLAB-like interface. Pyplot provides functions that interact with the figure i.e. creates a figure, decorates the plot with labels, creates plotting area in a figure."
},
{
"code": null,
"e": 44508,
"s": 44500,
"text": "Python3"
},
{
"code": "# Python program to show pyplot moduleimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [1, 4, 9, 16])plt.axis([0, 6, 0, 20])plt.show()",
"e": 44652,
"s": 44508,
"text": null
},
{
"code": null,
"e": 44660,
"s": 44652,
"text": "Output:"
},
{
"code": null,
"e": 45006,
"s": 44660,
"text": "A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. It can be created using the bar() method."
},
{
"code": null,
"e": 45045,
"s": 45006,
"text": "Here we will use the iris dataset only"
},
{
"code": null,
"e": 45053,
"s": 45045,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv(\"Iris.csv\") # This will plot a simple bar chartplt.bar(df['Species'], df['SepalLengthCm']) # Title to the plotplt.title(\"Iris Dataset\") # Adding the legendsplt.legend([\"bar\"])plt.show()",
"e": 45311,
"s": 45053,
"text": null
},
{
"code": null,
"e": 45319,
"s": 45311,
"text": "Output:"
},
{
"code": null,
"e": 45872,
"s": 45319,
"text": "A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. To create a histogram the first step is to create a bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values which fall into each of the intervals. Bins are clearly identified as consecutive, non-overlapping intervals of variables. The hist() function is used to compute and create a histogram of x."
},
{
"code": null,
"e": 45880,
"s": 45872,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv(\"Iris.csv\") plt.hist(df[\"SepalLengthCm\"]) # Title to the plotplt.title(\"Histogram\") # Adding the legendsplt.legend([\"SepalLengthCm\"])plt.show()",
"e": 46096,
"s": 45880,
"text": null
},
{
"code": null,
"e": 46104,
"s": 46096,
"text": "Output:"
},
{
"code": null,
"e": 46306,
"s": 46104,
"text": "Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot."
},
{
"code": null,
"e": 46314,
"s": 46306,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv(\"Iris.csv\") plt.scatter(df[\"Species\"], df[\"SepalLengthCm\"]) # Title to the plotplt.title(\"Scatter Plot\") # Adding the legendsplt.legend([\"SepalLengthCm\"])plt.show()",
"e": 46551,
"s": 46314,
"text": null
},
{
"code": null,
"e": 46559,
"s": 46551,
"text": "Output:"
},
{
"code": null,
"e": 47085,
"s": 46559,
"text": "A boxplot,Correlation also known as a box and whisker plot. It is a very good visual representation when it comes to measuring the data distribution. Clearly plots the median values, outliers and the quartiles. Understanding data distribution is another important factor which leads to better model building. If data has outliers, box plot is a recommended way to identify them and take necessary actions. The box and whiskers chart shows how data is spread out. Five pieces of information are generally included in the chart"
},
{
"code": null,
"e": 47169,
"s": 47085,
"text": "The minimum is shown at the far left of the chart, at the end of the left ‘whisker’"
},
{
"code": null,
"e": 47231,
"s": 47169,
"text": "First quartile, Q1, is the far left of the box (left whisker)"
},
{
"code": null,
"e": 47286,
"s": 47231,
"text": "The median is shown as a line in the center of the box"
},
{
"code": null,
"e": 47356,
"s": 47286,
"text": "Third quartile, Q3, shown at the far right of the box (right whisker)"
},
{
"code": null,
"e": 47399,
"s": 47356,
"text": "The maximum is at the far right of the box"
},
{
"code": null,
"e": 47426,
"s": 47399,
"text": "Representation of box plot"
},
{
"code": null,
"e": 47434,
"s": 47426,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv(\"Iris.csv\") plt.boxplot(df[\"SepalWidthCm\"]) # Title to the plotplt.title(\"Box Plot\") # Adding the legendsplt.legend([\"SepalWidthCm\"])plt.show()",
"e": 47650,
"s": 47434,
"text": null
},
{
"code": null,
"e": 47658,
"s": 47650,
"text": "Output:"
},
{
"code": null,
"e": 48444,
"s": 47658,
"text": "A 2-D Heatmap is a data visualization tool that helps to represent the magnitude of the phenomenon in form of colors. A correlation heatmap is a heatmap that shows a 2D correlation matrix between two discrete dimensions, using colored cells to represent data from usually a monochromatic scale. The values of the first dimension appear as the rows of the table while of the second dimension as a column. The color of the cell is proportional to the number of measurements that match the dimensional value. This makes correlation heatmaps ideal for data analysis since it makes patterns easily readable and highlights the differences and variation in the same data. A correlation heatmap, like a regular heatmap, is assisted by a colorbar making data easily readable and comprehensible."
},
{
"code": null,
"e": 48674,
"s": 48444,
"text": "Note: The data here has to be passed with corr() method to generate a correlation heatmap. Also, corr() itself eliminates columns which will be of no use while generating a correlation heatmap and selects those which can be used."
},
{
"code": null,
"e": 48682,
"s": 48674,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport pandas as pd df = pd.read_csv(\"Iris.csv\") plt.imshow(df.corr() , cmap = 'autumn' , interpolation = 'nearest' ) plt.title(\"Heat Map\")plt.show()",
"e": 48868,
"s": 48682,
"text": null
},
{
"code": null,
"e": 48876,
"s": 48868,
"text": "Output:"
},
{
"code": null,
"e": 48951,
"s": 48876,
"text": "For more information on data visualization refer to our below tutorials – "
},
{
"code": null,
"e": 48987,
"s": 48951,
"text": "Data Visualization using Matplotlib"
},
{
"code": null,
"e": 49026,
"s": 48987,
"text": "Data Visualization with Python Seaborn"
},
{
"code": null,
"e": 49084,
"s": 49026,
"text": "Data Visualisation in Python using Matplotlib and Seaborn"
},
{
"code": null,
"e": 49142,
"s": 49084,
"text": "Using Plotly for Interactive Data Visualization in Python"
},
{
"code": null,
"e": 49184,
"s": 49142,
"text": "Interactive Data Visualization with Bokeh"
},
{
"code": null,
"e": 49501,
"s": 49184,
"text": "Exploratory Data Analysis (EDA) is a technique to analyze data using some visual Techniques. With this technique, we can get detailed information about the statistical summary of the data. We will also be able to deal with the duplicates values, outliers, and also see some trends or patterns present in the dataset."
},
{
"code": null,
"e": 49538,
"s": 49501,
"text": "Note: We will be using Iris Dataset."
},
{
"code": null,
"e": 49603,
"s": 49538,
"text": "We will use the shape parameter to get the shape of the dataset."
},
{
"code": null,
"e": 49612,
"s": 49603,
"text": "Example:"
},
{
"code": null,
"e": 49620,
"s": 49612,
"text": "Python3"
},
{
"code": "df.shape",
"e": 49629,
"s": 49620,
"text": null
},
{
"code": null,
"e": 49637,
"s": 49629,
"text": "Output:"
},
{
"code": null,
"e": 49646,
"s": 49637,
"text": "(150, 6)"
},
{
"code": null,
"e": 49709,
"s": 49646,
"text": "We can see that the dataframe contains 6 columns and 150 rows."
},
{
"code": null,
"e": 49800,
"s": 49709,
"text": "Now, let’s also the columns and their data types. For this, we will use the info() method."
},
{
"code": null,
"e": 49809,
"s": 49800,
"text": "Example:"
},
{
"code": null,
"e": 49817,
"s": 49809,
"text": "Python3"
},
{
"code": "df.info()",
"e": 49827,
"s": 49817,
"text": null
},
{
"code": null,
"e": 49835,
"s": 49827,
"text": "Output:"
},
{
"code": null,
"e": 49961,
"s": 49835,
"text": "We can see that only one column has categorical data and all the other columns are of the numeric type with non-Null entries."
},
{
"code": null,
"e": 50315,
"s": 49961,
"text": "Let’s get a quick statistical summary of the dataset using the describe() method. The describe() function applies basic statistical computations on the dataset like extreme values, count of data points standard deviation, etc. Any missing value or NaN value is automatically skipped. describe() function gives a good picture of the distribution of data."
},
{
"code": null,
"e": 50324,
"s": 50315,
"text": "Example:"
},
{
"code": null,
"e": 50332,
"s": 50324,
"text": "Python3"
},
{
"code": "df.describe()",
"e": 50346,
"s": 50332,
"text": null
},
{
"code": null,
"e": 50354,
"s": 50346,
"text": "Output:"
},
{
"code": null,
"e": 50467,
"s": 50354,
"text": "We can see the count of each column along with their mean value, standard deviation, minimum and maximum values."
},
{
"code": null,
"e": 50662,
"s": 50467,
"text": "We will check if our data contains any missing values or not. Missing values can occur when no information is provided for one or more items or for a whole unit. We will use the isnull() method."
},
{
"code": null,
"e": 50671,
"s": 50662,
"text": "Example:"
},
{
"code": null,
"e": 50679,
"s": 50671,
"text": "Python3"
},
{
"code": "df.isnull().sum()",
"e": 50697,
"s": 50679,
"text": null
},
{
"code": null,
"e": 50705,
"s": 50697,
"text": "Output:"
},
{
"code": null,
"e": 50753,
"s": 50705,
"text": "We can see that no column as any missing value."
},
{
"code": null,
"e": 50892,
"s": 50753,
"text": "Let’s see if our dataset contains any duplicates or not. Pandas drop_duplicates() method helps in removing duplicates from the data frame."
},
{
"code": null,
"e": 50901,
"s": 50892,
"text": "Example:"
},
{
"code": null,
"e": 50909,
"s": 50901,
"text": "Python3"
},
{
"code": "data = df.drop_duplicates(subset =\"Species\",)data",
"e": 50959,
"s": 50909,
"text": null
},
{
"code": null,
"e": 50967,
"s": 50959,
"text": "Output:"
},
{
"code": null,
"e": 51239,
"s": 50967,
"text": "We can see that there are only three unique species. Let’s see if the dataset is balanced or not i.e. all the species contain equal amounts of rows or not. We will use the Series.value_counts() function. This function returns a Series containing counts of unique values. "
},
{
"code": null,
"e": 51248,
"s": 51239,
"text": "Example:"
},
{
"code": null,
"e": 51256,
"s": 51248,
"text": "Python3"
},
{
"code": "df.value_counts(\"Species\")",
"e": 51283,
"s": 51256,
"text": null
},
{
"code": null,
"e": 51291,
"s": 51283,
"text": "Output:"
},
{
"code": null,
"e": 51393,
"s": 51291,
"text": "We can see that all the species contain an equal amount of rows, so we should not delete any entries."
},
{
"code": null,
"e": 51510,
"s": 51393,
"text": "We will see the relationship between the sepal length and sepal width and also between petal length and petal width."
},
{
"code": null,
"e": 51560,
"s": 51510,
"text": "Example 1: Comparing Sepal Length and Sepal Width"
},
{
"code": null,
"e": 51568,
"s": 51560,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.scatterplot(x='SepalLengthCm', y='SepalWidthCm', hue='Species', data=df, ) # Placing Legend outside the Figureplt.legend(bbox_to_anchor=(1, 1), loc=2) plt.show()",
"e": 51827,
"s": 51568,
"text": null
},
{
"code": null,
"e": 51835,
"s": 51827,
"text": "Output:"
},
{
"code": null,
"e": 51877,
"s": 51835,
"text": "From the above plot, we can infer that – "
},
{
"code": null,
"e": 51943,
"s": 51877,
"text": "Species Setosa has smaller sepal lengths but larger sepal widths."
},
{
"code": null,
"e": 52041,
"s": 51943,
"text": "Versicolor Species lies in the middle of the other two species in terms of sepal length and width"
},
{
"code": null,
"e": 52110,
"s": 52041,
"text": "Species Virginica has larger sepal lengths but smaller sepal widths."
},
{
"code": null,
"e": 52160,
"s": 52110,
"text": "Example 2: Comparing Petal Length and Petal Width"
},
{
"code": null,
"e": 52168,
"s": 52160,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.scatterplot(x='PetalLengthCm', y='PetalWidthCm', hue='Species', data=df, ) # Placing Legend outside the Figureplt.legend(bbox_to_anchor=(1, 1), loc=2) plt.show()",
"e": 52427,
"s": 52168,
"text": null
},
{
"code": null,
"e": 52435,
"s": 52427,
"text": "Output:"
},
{
"code": null,
"e": 52477,
"s": 52435,
"text": "From the above plot, we can infer that – "
},
{
"code": null,
"e": 52530,
"s": 52477,
"text": "Species Setosa has smaller petal lengths and widths."
},
{
"code": null,
"e": 52628,
"s": 52530,
"text": "Versicolor Species lies in the middle of the other two species in terms of petal length and width"
},
{
"code": null,
"e": 52691,
"s": 52628,
"text": "Species Virginica has the largest of petal lengths and widths."
},
{
"code": null,
"e": 52793,
"s": 52691,
"text": "Let’s plot all the column’s relationships using a pairplot. It can be used for multivariate analysis."
},
{
"code": null,
"e": 52802,
"s": 52793,
"text": "Example:"
},
{
"code": null,
"e": 52810,
"s": 52802,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.pairplot(df.drop(['Id'], axis = 1), hue='Species', height=2)",
"e": 52964,
"s": 52810,
"text": null
},
{
"code": null,
"e": 52972,
"s": 52964,
"text": "Output:"
},
{
"code": null,
"e": 53221,
"s": 52972,
"text": "We can see many types of relationships from this plot such as the species Seotsa has the smallest of petals widths and lengths. It also has the smallest sepal length but larger sepal widths. Such information can be gathered about any other species."
},
{
"code": null,
"e": 53431,
"s": 53221,
"text": "Pandas dataframe.corr() is used to find the pairwise correlation of all columns in the dataframe. Any NA values are automatically excluded. For any non-numeric data type columns in the dataframe it is ignored."
},
{
"code": null,
"e": 53440,
"s": 53431,
"text": "Example:"
},
{
"code": null,
"e": 53448,
"s": 53440,
"text": "Python3"
},
{
"code": "data.corr(method='pearson')",
"e": 53476,
"s": 53448,
"text": null
},
{
"code": null,
"e": 53484,
"s": 53476,
"text": "Output:"
},
{
"code": null,
"e": 53755,
"s": 53484,
"text": "The heatmap is a data visualization technique that is used to analyze the dataset as colors in two dimensions. Basically, it shows a correlation between all numerical variables in the dataset. In simpler terms, we can plot the above-found correlation using the heatmaps."
},
{
"code": null,
"e": 53764,
"s": 53755,
"text": "Example:"
},
{
"code": null,
"e": 53772,
"s": 53764,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.heatmap(df.corr(method='pearson').drop( ['Id'], axis=1).drop(['Id'], axis=0), annot = True); plt.show()",
"e": 53969,
"s": 53772,
"text": null
},
{
"code": null,
"e": 53977,
"s": 53969,
"text": "Output:"
},
{
"code": null,
"e": 54017,
"s": 53977,
"text": "From the above graph, we can see that –"
},
{
"code": null,
"e": 54070,
"s": 54017,
"text": "Petal width and petal length have high correlations."
},
{
"code": null,
"e": 54123,
"s": 54070,
"text": "Petal length and sepal width have good correlations."
},
{
"code": null,
"e": 54176,
"s": 54123,
"text": "Petal Width and Sepal length have good correlations."
},
{
"code": null,
"e": 54552,
"s": 54176,
"text": "An Outlier is a data-item/object that deviates significantly from the rest of the (so-called normal)objects. They can be caused by measurement or execution errors. The analysis for outlier detection is referred to as outlier mining. There are many ways to detect the outliers, and the removal process is the data frame same as removing a data item from the panda’s dataframe."
},
{
"code": null,
"e": 54640,
"s": 54552,
"text": "Let’s consider the iris dataset and let’s plot the boxplot for the SepalWidthCm column."
},
{
"code": null,
"e": 54649,
"s": 54640,
"text": "Example:"
},
{
"code": null,
"e": 54657,
"s": 54649,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # Load the datasetdf = pd.read_csv('Iris.csv') sns.boxplot(x='SepalWidthCm', data=df)",
"e": 54818,
"s": 54657,
"text": null
},
{
"code": null,
"e": 54826,
"s": 54818,
"text": "Output:"
},
{
"code": null,
"e": 54901,
"s": 54826,
"text": "In the above graph, the values above 4 and below 2 are acting as outliers."
},
{
"code": null,
"e": 55210,
"s": 54901,
"text": "For removing the outlier, one must follow the same process of removing an entry from the dataset using its exact position in the dataset because in all the above methods of detecting the outliers end result is the list of all those data items that satisfy the outlier definition according to the method used."
},
{
"code": null,
"e": 55360,
"s": 55210,
"text": "Example: We will detect the outliers using IQR and then we will remove them. We will also draw the boxplot to see if the outliers are removed or not."
},
{
"code": null,
"e": 55368,
"s": 55360,
"text": "Python3"
},
{
"code": "# Importingimport sklearnfrom sklearn.datasets import load_bostonimport pandas as pdimport seaborn as sns # Load the datasetdf = pd.read_csv('Iris.csv') # IQRQ1 = np.percentile(df['SepalWidthCm'], 25, interpolation = 'midpoint') Q3 = np.percentile(df['SepalWidthCm'], 75, interpolation = 'midpoint')IQR = Q3 - Q1 print(\"Old Shape: \", df.shape) # Upper boundupper = np.where(df['SepalWidthCm'] >= (Q3+1.5*IQR)) # Lower boundlower = np.where(df['SepalWidthCm'] <= (Q1-1.5*IQR)) # Removing the Outliersdf.drop(upper[0], inplace = True)df.drop(lower[0], inplace = True) print(\"New Shape: \", df.shape) sns.boxplot(x='SepalWidthCm', data=df)",
"e": 56043,
"s": 55368,
"text": null
},
{
"code": null,
"e": 56051,
"s": 56043,
"text": "Output:"
},
{
"code": null,
"e": 56115,
"s": 56051,
"text": "For more information about EDA, refer to our below tutorials – "
},
{
"code": null,
"e": 56151,
"s": 56115,
"text": "What is Exploratory Data Analysis ?"
},
{
"code": null,
"e": 56195,
"s": 56151,
"text": "Exploratory Data Analysis in Python | Set 1"
},
{
"code": null,
"e": 56239,
"s": 56195,
"text": "Exploratory Data Analysis in Python | Set 2"
},
{
"code": null,
"e": 56281,
"s": 56239,
"text": "Exploratory Data Analysis on Iris Dataset"
},
{
"code": null,
"e": 56300,
"s": 56281,
"text": "surindertarika1234"
},
{
"code": null,
"e": 56320,
"s": 56300,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 56333,
"s": 56320,
"text": "data-science"
},
{
"code": null,
"e": 56340,
"s": 56333,
"text": "Python"
},
{
"code": null,
"e": 56438,
"s": 56340,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 56470,
"s": 56438,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 56512,
"s": 56470,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 56568,
"s": 56512,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 56610,
"s": 56568,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 56632,
"s": 56610,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 56663,
"s": 56632,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 56718,
"s": 56663,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 56757,
"s": 56718,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 56786,
"s": 56757,
"text": "Create a directory in Python"
}
] |
Matlab-Matrix - Trace
|
Trace helps you to calculate the sum of diagonal elements in a given matrix.
Consider the given 3x3 matrix. Let us find out the sum of diagonal elements as shown below −
a = [ 1 2 3; 2 3 4; 1 2 5];
test = trace(a)
The execution in MATLAB is as follows −
>> a = [ 1 2 3; 2 3 4; 1 2 5]
test = trace(a)
a =
1 2 3
2 3 4
1 2 5
test =
9
>>
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2076,
"s": 1999,
"text": "Trace helps you to calculate the sum of diagonal elements in a given matrix."
},
{
"code": null,
"e": 2169,
"s": 2076,
"text": "Consider the given 3x3 matrix. Let us find out the sum of diagonal elements as shown below −"
},
{
"code": null,
"e": 2213,
"s": 2169,
"text": "a = [ 1 2 3; 2 3 4; 1 2 5];\ntest = trace(a)"
},
{
"code": null,
"e": 2253,
"s": 2213,
"text": "The execution in MATLAB is as follows −"
},
{
"code": null,
"e": 2361,
"s": 2253,
"text": ">> a = [ 1 2 3; 2 3 4; 1 2 5]\ntest = trace(a)\n\na =\n\n 1 2 3\n 2 3 4\n 1 2 5\n \ntest =\n\n 9\n \n>>\n"
},
{
"code": null,
"e": 2394,
"s": 2361,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2407,
"s": 2394,
"text": " Nouman Azam"
},
{
"code": null,
"e": 2442,
"s": 2407,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 2455,
"s": 2442,
"text": " Nouman Azam"
},
{
"code": null,
"e": 2488,
"s": 2455,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2497,
"s": 2488,
"text": " Sanjeev"
},
{
"code": null,
"e": 2530,
"s": 2497,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2546,
"s": 2530,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2579,
"s": 2546,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2595,
"s": 2579,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2628,
"s": 2595,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2645,
"s": 2628,
"text": " Phinite Academy"
},
{
"code": null,
"e": 2652,
"s": 2645,
"text": " Print"
},
{
"code": null,
"e": 2663,
"s": 2652,
"text": " Add Notes"
}
] |
How to send PDF in express route response and force browser download ? - GeeksforGeeks
|
26 Apr, 2021
In this article, we will see how to send PDF files in the express route’s response and make the browser force download the file.
Approach:
Load required packages, then create an express app.Define the routes for homepage and PDF download requests.Create an index.html file with a single button to download PDF.Execute ajax call on button click to GET the PDF.Specify responseType of ajax call as “blob” in the xhrFields, as “blob” is used to store objects such as images, audios and videos, since they require more space than other data types.On successful ajax call, convert the received PDF file from blob format to PDF format.Now, to make the browser force download the PDF –a. Create a hidden <a> tag.b. Create a reference to the file using window.URL.createObjectURL() method.c. Set its href attribute to the blob’s URL.d. Set its download attribute to the filename.e. Click on the <a> tag.f. Remove the <a> tag from the DOM.g. Release an existing object URL, (the reference to the file), and let the browser know not to keep the reference to the file any longer.
Load required packages, then create an express app.
Define the routes for homepage and PDF download requests.
Create an index.html file with a single button to download PDF.
Execute ajax call on button click to GET the PDF.
Specify responseType of ajax call as “blob” in the xhrFields, as “blob” is used to store objects such as images, audios and videos, since they require more space than other data types.
On successful ajax call, convert the received PDF file from blob format to PDF format.
Now, to make the browser force download the PDF –a. Create a hidden <a> tag.b. Create a reference to the file using window.URL.createObjectURL() method.c. Set its href attribute to the blob’s URL.d. Set its download attribute to the filename.e. Click on the <a> tag.f. Remove the <a> tag from the DOM.g. Release an existing object URL, (the reference to the file), and let the browser know not to keep the reference to the file any longer.
Step 1: Install necessary packages
Firstly, install the following node packages.
npm install --save express
Step 2: Create a basic Express server setup
Create a file named app.js and with the following code as shown below.
App.js
// Load necessary packagesconst express = require("express"); // create an express appconst app = express(); // define PORT number to listen to the requestsconst PORT = process.env.PORT || 3000; // to serve files from uploads directoryapp.use("/uploads", express.static("uploads")); // express routesapp.use("/", require("./routes")); // listen to requestsapp.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));
Step 3: Define routes for the app
Create a file named routes.js and with the following code as shown below.
routes.js
// Load necessary packagesconst express = require("express"); // express router const router = express.Router(); // respond with index.html when a GET request is made to the homepagerouter.get("/", (req, res) => { res.sendFile(__dirname + "/views/index.html");}); // route for handling PDF requestrouter.get("/downloadPDF", (req, res) => { res.download("uploads/Resume.pdf");}); // export router middleware and use it in app.jsmodule.exports = router;
Step 4: Run the server
Now start your express server using the following command:
node app.js
Step 5: Open browser and enter URL
Open your favorite browser and in the address bar enter http://localhost:3000/downloadPDF and then hit Enter, Resume.pdf file will get downloaded automatically.
Output:
Step 6: To make the PDF downloadable through a button.
You can make the browser download the PDF one click of a button using on click event listener on the button and then making an ajax request to the above URL.
To make PDF download on button click, firstly create an index.html file with the following contents:
index.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous" /></head><body> <div class="container"> <button id="download" class="btn btn-primary my-5"> Download PDF </button> </div> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"> </script> <script> $("#download").click(function (e) { $.ajax({ type: "GET", url: "/downloadPDF", xhrFields: { // specify response type as "blob" to handle objects responseType: "blob", }, success: function (data) { // creating a hidden <a> tag var a = document.createElement("a"); // creating a reference to the file var url = window.URL.createObjectURL(data); // setting anchor tag's href attribute to the blob's URL a.href = url; // setting anchor tag's download attribute to the filename a.download = "Resume.pdf"; document.body.append(a); // click on the <a> tag a.click(); // after clicking it, remove it from the DOM a.remove(); // release an existing object URL which was previously // created by calling URL.createObjectURL() // once we have finished using an object URL, let the // browser know not to keep the reference to the file any longer. window.URL.revokeObjectURL(url); }, error: function (result) { alert("error"); }, }); }); </script></body></html>
Output:
Express.js
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to read and write Excel file in Node.js ?
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24486,
"s": 24458,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 24615,
"s": 24486,
"text": "In this article, we will see how to send PDF files in the express route’s response and make the browser force download the file."
},
{
"code": null,
"e": 24625,
"s": 24615,
"text": "Approach:"
},
{
"code": null,
"e": 25556,
"s": 24625,
"text": "Load required packages, then create an express app.Define the routes for homepage and PDF download requests.Create an index.html file with a single button to download PDF.Execute ajax call on button click to GET the PDF.Specify responseType of ajax call as “blob” in the xhrFields, as “blob” is used to store objects such as images, audios and videos, since they require more space than other data types.On successful ajax call, convert the received PDF file from blob format to PDF format.Now, to make the browser force download the PDF –a. Create a hidden <a> tag.b. Create a reference to the file using window.URL.createObjectURL() method.c. Set its href attribute to the blob’s URL.d. Set its download attribute to the filename.e. Click on the <a> tag.f. Remove the <a> tag from the DOM.g. Release an existing object URL, (the reference to the file), and let the browser know not to keep the reference to the file any longer."
},
{
"code": null,
"e": 25608,
"s": 25556,
"text": "Load required packages, then create an express app."
},
{
"code": null,
"e": 25666,
"s": 25608,
"text": "Define the routes for homepage and PDF download requests."
},
{
"code": null,
"e": 25730,
"s": 25666,
"text": "Create an index.html file with a single button to download PDF."
},
{
"code": null,
"e": 25780,
"s": 25730,
"text": "Execute ajax call on button click to GET the PDF."
},
{
"code": null,
"e": 25965,
"s": 25780,
"text": "Specify responseType of ajax call as “blob” in the xhrFields, as “blob” is used to store objects such as images, audios and videos, since they require more space than other data types."
},
{
"code": null,
"e": 26053,
"s": 25965,
"text": "On successful ajax call, convert the received PDF file from blob format to PDF format."
},
{
"code": null,
"e": 26493,
"s": 26053,
"text": "Now, to make the browser force download the PDF –a. Create a hidden <a> tag.b. Create a reference to the file using window.URL.createObjectURL() method.c. Set its href attribute to the blob’s URL.d. Set its download attribute to the filename.e. Click on the <a> tag.f. Remove the <a> tag from the DOM.g. Release an existing object URL, (the reference to the file), and let the browser know not to keep the reference to the file any longer."
},
{
"code": null,
"e": 26529,
"s": 26493,
"text": "Step 1: Install necessary packages"
},
{
"code": null,
"e": 26575,
"s": 26529,
"text": "Firstly, install the following node packages."
},
{
"code": null,
"e": 26602,
"s": 26575,
"text": "npm install --save express"
},
{
"code": null,
"e": 26646,
"s": 26602,
"text": "Step 2: Create a basic Express server setup"
},
{
"code": null,
"e": 26717,
"s": 26646,
"text": "Create a file named app.js and with the following code as shown below."
},
{
"code": null,
"e": 26724,
"s": 26717,
"text": "App.js"
},
{
"code": "// Load necessary packagesconst express = require(\"express\"); // create an express appconst app = express(); // define PORT number to listen to the requestsconst PORT = process.env.PORT || 3000; // to serve files from uploads directoryapp.use(\"/uploads\", express.static(\"uploads\")); // express routesapp.use(\"/\", require(\"./routes\")); // listen to requestsapp.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));",
"e": 27164,
"s": 26724,
"text": null
},
{
"code": null,
"e": 27198,
"s": 27164,
"text": "Step 3: Define routes for the app"
},
{
"code": null,
"e": 27272,
"s": 27198,
"text": "Create a file named routes.js and with the following code as shown below."
},
{
"code": null,
"e": 27282,
"s": 27272,
"text": "routes.js"
},
{
"code": "// Load necessary packagesconst express = require(\"express\"); // express router const router = express.Router(); // respond with index.html when a GET request is made to the homepagerouter.get(\"/\", (req, res) => { res.sendFile(__dirname + \"/views/index.html\");}); // route for handling PDF requestrouter.get(\"/downloadPDF\", (req, res) => { res.download(\"uploads/Resume.pdf\");}); // export router middleware and use it in app.jsmodule.exports = router;",
"e": 27744,
"s": 27282,
"text": null
},
{
"code": null,
"e": 27767,
"s": 27744,
"text": "Step 4: Run the server"
},
{
"code": null,
"e": 27826,
"s": 27767,
"text": "Now start your express server using the following command:"
},
{
"code": null,
"e": 27838,
"s": 27826,
"text": "node app.js"
},
{
"code": null,
"e": 27874,
"s": 27838,
"text": "Step 5: Open browser and enter URL "
},
{
"code": null,
"e": 28035,
"s": 27874,
"text": "Open your favorite browser and in the address bar enter http://localhost:3000/downloadPDF and then hit Enter, Resume.pdf file will get downloaded automatically."
},
{
"code": null,
"e": 28043,
"s": 28035,
"text": "Output:"
},
{
"code": null,
"e": 28098,
"s": 28043,
"text": "Step 6: To make the PDF downloadable through a button."
},
{
"code": null,
"e": 28256,
"s": 28098,
"text": "You can make the browser download the PDF one click of a button using on click event listener on the button and then making an ajax request to the above URL."
},
{
"code": null,
"e": 28357,
"s": 28256,
"text": "To make PDF download on button click, firstly create an index.html file with the following contents:"
},
{
"code": null,
"e": 28368,
"s": 28357,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\" crossorigin=\"anonymous\" /></head><body> <div class=\"container\"> <button id=\"download\" class=\"btn btn-primary my-5\"> Download PDF </button> </div> <script src=\"https://code.jquery.com/jquery-3.6.0.js\" integrity=\"sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf\" crossorigin=\"anonymous\"> </script> <script> $(\"#download\").click(function (e) { $.ajax({ type: \"GET\", url: \"/downloadPDF\", xhrFields: { // specify response type as \"blob\" to handle objects responseType: \"blob\", }, success: function (data) { // creating a hidden <a> tag var a = document.createElement(\"a\"); // creating a reference to the file var url = window.URL.createObjectURL(data); // setting anchor tag's href attribute to the blob's URL a.href = url; // setting anchor tag's download attribute to the filename a.download = \"Resume.pdf\"; document.body.append(a); // click on the <a> tag a.click(); // after clicking it, remove it from the DOM a.remove(); // release an existing object URL which was previously // created by calling URL.createObjectURL() // once we have finished using an object URL, let the // browser know not to keep the reference to the file any longer. window.URL.revokeObjectURL(url); }, error: function (result) { alert(\"error\"); }, }); }); </script></body></html>",
"e": 30388,
"s": 28368,
"text": null
},
{
"code": null,
"e": 30396,
"s": 30388,
"text": "Output:"
},
{
"code": null,
"e": 30407,
"s": 30396,
"text": "Express.js"
},
{
"code": null,
"e": 30414,
"s": 30407,
"text": "Picked"
},
{
"code": null,
"e": 30422,
"s": 30414,
"text": "Node.js"
},
{
"code": null,
"e": 30439,
"s": 30422,
"text": "Web Technologies"
},
{
"code": null,
"e": 30537,
"s": 30439,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30566,
"s": 30537,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 30596,
"s": 30566,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 30653,
"s": 30596,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 30707,
"s": 30653,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 30753,
"s": 30707,
"text": "How to read and write Excel file in Node.js ?"
},
{
"code": null,
"e": 30795,
"s": 30753,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30838,
"s": 30795,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30900,
"s": 30838,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30945,
"s": 30900,
"text": "Convert a string to an integer in JavaScript"
}
] |
C++ Program to Find Closest Pair of Points in an Array
|
This is the program to find closest pair of points in an array.
For Distance between Closest point
Begin
Declare function Closest_dist_Spoint(poi stp[], int s, double dist, poi &pnt1, poi &pnt2) to the double datatype.
Declare Minimum to the double datatype.
Initialize Minimum = dist.
for (int i = 0; i < s; ++i)
for (int j = i+1; j < s && (stp[j].poi2 - stp[i].poi2) < Minimum; ++j)
if (Distance(stp[i],stp[j]) < Minimum) then
Minimum = Distance(stp[i], stp[j]).
pnt1.poi1 = stp[i].poi1, pnt1.poi2 = stp[i].poi2.
pnt2.poi1 = stp[j].poi1, pnt2.poi2 = stp[j].poi2.
Return Minimum.
End.
To Calculate smallest distance −
Begin
Declare function Closest_dist(poi P[], poi stp[], int n, poi &pnt1, poi &pnt2) to the double datatype.
Declare static object pt1, pt2, pt3, pt4 of poi structure.
if (n <= 3) then
return S_Distance(P, n, pt1, pt2).
Declare medium to the integer datatype.
Initialize midium = n/2.
Declare object mediumPoint of poi structure.
Initialize midiumPoint = P[midium].
Declare D_Left to the double datatype.
Initialize D _Left = Closest_dist(P, stp, midium, pt1, pt2).
Declare D_Right to the double datatype.
Initialize D_Right = Closest_dist(P + midium, stp, n-midium, pt3, pt4).
if(D_Left < D_Right) then
pnt1.poi1 = pt1.poi1; pnt1.poi2 = pt1.poi2.
pnt2.poi1 = pt2.poi1; pnt2.poi2 = pt2.poi2.
else
pnt1.poi1 = pt3.poi1; pnt1.poi2 = pt3.poi2;
pnt2.poi1 = pt4.poi1; pnt2.poi2 = pt4.poi2;
Declare min_dist to the double datatype.
Initialize min_dist = Minimum(D_Left, D_Right).
Declare j to the integer datatype.
initialize j = 0.
for (int i = 0; i < n; i++)
if (abs(P[i].poi1 - midiumPoint.poi1) < min_dist) then
stp[j++] = P[i].
Declare min_dist_strip, F_Min to the double datatype.
Initalize min_dist_strip = Closest_dist_Spoint(stp, j, min_dist, pt1, pt2).
Initialize F_Min = min_dist.
if(min_dist_strip < min_dist) then
pnt1.poi1 = pt1.poi1; pnt1.poi2 = pt1.poi2;
pnt2.poi1 = pt2.poi1; pnt2.poi2 = pt2.poi2;
F_Min = min_dist_strip;
Return F_Min.
End.
Live Demo
#include <iostream>
#include <cfloat>
#include <cstdlib>
#include <cmath>
using namespace std;
struct poi {
double poi1, poi2;
};
inline int Comp_poi1(const void* x, const void* b) {
poi *p1 = (poi *)x, *pnt2 = (poi *)b;
return (p1->poi1 - pnt2->poi1);
}
inline int Comp_poi2(const void* x, const void* y) {
poi *pnt1 = (poi *)x, *pnt2 = (poi *)y;
return (pnt1->poi2 - pnt2->poi2);
}
inline double Distance(poi pnt1, poi pnt2) { // Calculate the distance between two points
return sqrt( (pnt1.poi1 - pnt2.poi1)*(pnt1.poi1 - pnt2.poi1) +
(pnt1.poi2 - pnt2.poi2)*(pnt1.poi2 - pnt2.poi2) );
}
double S_Distance(poi P[], int n, poi &pnt1, poi &pnt2) {
double min = DBL_MAX;
for (int i = 0; i < n; ++i)
for (int j = i+1; j < n; ++j)
if (Distance(P[i], P[j]) < min) {
min = Distance(P[i], P[j]);
pnt1.poi1 = P[i].poi1, pnt1.poi2 = P[i].poi2;
pnt2.poi1 = P[j].poi1, pnt2.poi2 = P[j].poi2;
}
return min;
}
inline double Minimum(double poi1, double poi2) { // Find minimum between two values
return (poi1 < poi2)? poi1 : poi2;
}
double Closest_dist_Spoint(poi stp[], int s, double dist, poi &pnt1, poi &pnt2) { // Calculate distance beween the closest points
double Minimum = dist; // Initialize the minimum distance as dist
qsort(stp, s, sizeof(poi), Comp_poi2);
for (int i = 0; i < s; ++i)
for (int j = i+1; j < s && (stp[j].poi2 - stp[i].poi2) < Minimum; ++j)
if (Distance(stp[i],stp[j]) < Minimum) {
Minimum = Distance(stp[i], stp[j]);
pnt1.poi1 = stp[i].poi1, pnt1.poi2 = stp[i].poi2;
pnt2.poi1 = stp[j].poi1, pnt2.poi2 = stp[j].poi2;
}
return Minimum;
}
double Closest_dist(poi P[], poi stp[], int n, poi &pnt1, poi &pnt2) { // Calculate smallest distance.
static poi pt1, pt2, pt3, pt4;
if (n <= 3)
return S_Distance(P, n, pt1, pt2);
int medium = n/2; // Calculate the mid point
poi mediumPoint = P[medium];
double D_Left = Closest_dist(P, stp, medium, pt1, pt2); // D_Left: left of medium point
double D_Right = Closest_dist(P + medium, stp, n-medium, pt3, pt4); // D_Right: right side of the medium point
if(D_Left < D_Right) {
pnt1.poi1 = pt1.poi1; pnt1.poi2 = pt1.poi2; // Store the pair that has smaller distance
pnt2.poi1 = pt2.poi1; pnt2.poi2 = pt2.poi2;
} else {
pnt1.poi1 = pt3.poi1; pnt1.poi2 = pt3.poi2;
pnt2.poi1 = pt4.poi1; pnt2.poi2 = pt4.poi2;
}
double min_dist = Minimum(D_Left, D_Right);
int j = 0;
for (int i = 0; i < n; i++)
if (abs(P[i].poi1 - mediumPoint.poi1) < min_dist)
stp[j++] = P[i];
double min_dist_strip = Closest_dist_Spoint(stp, j, min_dist, pt1, pt2);
double F_Min = min_dist;
if(min_dist_strip < min_dist) {
pnt1.poi1 = pt1.poi1; pnt1.poi2 = pt1.poi2;
pnt2.poi1 = pt2.poi1; pnt2.poi2 = pt2.poi2;
F_Min = min_dist_strip;
}
return F_Min;
}
int main() {
poi P[] = {{4, 1}, {15, 20}, {30, 40}, {8, 4}, {13, 11}, {5, 6}};
poi pnt1 = {DBL_MAX, DBL_MAX}, pnt2 = {DBL_MAX, DBL_MAX}; // Closest pair of points in array
int n = sizeof(P) / sizeof(P[0]);
qsort(P, n, sizeof(poi), Comp_poi1);
poi *stp = new poi[n];
cout << "The closest distance of point in array is: " << Closest_dist(P, stp, n, pnt1, pnt2) << endl;
cout << "The closest pair of point in array: (" << pnt1.poi1 << "," << pnt1.poi2 << ") and ("
<< pnt2.poi1 << "," << pnt2.poi2 << ")" << endl;
delete[] stp;
return 0;
}
The closest distance of point in array is: 3.60555
The closest pair of point in array: (13,11) and (15,20)
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "This is the program to find closest pair of points in an array."
},
{
"code": null,
"e": 1161,
"s": 1126,
"text": "For Distance between Closest point"
},
{
"code": null,
"e": 1714,
"s": 1161,
"text": "Begin\n Declare function Closest_dist_Spoint(poi stp[], int s, double dist, poi &pnt1, poi &pnt2) to the double datatype.\n Declare Minimum to the double datatype.\n Initialize Minimum = dist.\n for (int i = 0; i < s; ++i)\n for (int j = i+1; j < s && (stp[j].poi2 - stp[i].poi2) < Minimum; ++j)\n if (Distance(stp[i],stp[j]) < Minimum) then\n Minimum = Distance(stp[i], stp[j]).\n pnt1.poi1 = stp[i].poi1, pnt1.poi2 = stp[i].poi2.\n pnt2.poi1 = stp[j].poi1, pnt2.poi2 = stp[j].poi2.\n Return Minimum.\nEnd."
},
{
"code": null,
"e": 1747,
"s": 1714,
"text": "To Calculate smallest distance −"
},
{
"code": null,
"e": 3255,
"s": 1747,
"text": "Begin\n Declare function Closest_dist(poi P[], poi stp[], int n, poi &pnt1, poi &pnt2) to the double datatype.\n Declare static object pt1, pt2, pt3, pt4 of poi structure.\n if (n <= 3) then\n return S_Distance(P, n, pt1, pt2).\n Declare medium to the integer datatype.\n Initialize midium = n/2.\n Declare object mediumPoint of poi structure.\n Initialize midiumPoint = P[midium].\n Declare D_Left to the double datatype.\n Initialize D _Left = Closest_dist(P, stp, midium, pt1, pt2).\n Declare D_Right to the double datatype.\n Initialize D_Right = Closest_dist(P + midium, stp, n-midium, pt3, pt4).\n if(D_Left < D_Right) then\n pnt1.poi1 = pt1.poi1; pnt1.poi2 = pt1.poi2.\n pnt2.poi1 = pt2.poi1; pnt2.poi2 = pt2.poi2.\n else\n pnt1.poi1 = pt3.poi1; pnt1.poi2 = pt3.poi2;\n pnt2.poi1 = pt4.poi1; pnt2.poi2 = pt4.poi2;\n Declare min_dist to the double datatype.\n Initialize min_dist = Minimum(D_Left, D_Right).\n Declare j to the integer datatype.\n initialize j = 0.\n for (int i = 0; i < n; i++)\n if (abs(P[i].poi1 - midiumPoint.poi1) < min_dist) then\n stp[j++] = P[i].\n Declare min_dist_strip, F_Min to the double datatype.\n Initalize min_dist_strip = Closest_dist_Spoint(stp, j, min_dist, pt1, pt2).\n Initialize F_Min = min_dist.\n if(min_dist_strip < min_dist) then\n pnt1.poi1 = pt1.poi1; pnt1.poi2 = pt1.poi2;\n pnt2.poi1 = pt2.poi1; pnt2.poi2 = pt2.poi2;\n F_Min = min_dist_strip;\n Return F_Min.\nEnd."
},
{
"code": null,
"e": 3266,
"s": 3255,
"text": " Live Demo"
},
{
"code": null,
"e": 6812,
"s": 3266,
"text": "#include <iostream>\n#include <cfloat>\n#include <cstdlib>\n#include <cmath>\nusing namespace std;\nstruct poi {\n double poi1, poi2;\n};\ninline int Comp_poi1(const void* x, const void* b) {\n poi *p1 = (poi *)x, *pnt2 = (poi *)b;\n return (p1->poi1 - pnt2->poi1);\n}\ninline int Comp_poi2(const void* x, const void* y) {\n poi *pnt1 = (poi *)x, *pnt2 = (poi *)y;\n return (pnt1->poi2 - pnt2->poi2);\n}\ninline double Distance(poi pnt1, poi pnt2) { // Calculate the distance between two points\n return sqrt( (pnt1.poi1 - pnt2.poi1)*(pnt1.poi1 - pnt2.poi1) +\n (pnt1.poi2 - pnt2.poi2)*(pnt1.poi2 - pnt2.poi2) );\n}\ndouble S_Distance(poi P[], int n, poi &pnt1, poi &pnt2) {\n double min = DBL_MAX;\n for (int i = 0; i < n; ++i)\n for (int j = i+1; j < n; ++j)\n if (Distance(P[i], P[j]) < min) {\n min = Distance(P[i], P[j]);\n pnt1.poi1 = P[i].poi1, pnt1.poi2 = P[i].poi2;\n pnt2.poi1 = P[j].poi1, pnt2.poi2 = P[j].poi2;\n }\n return min;\n}\ninline double Minimum(double poi1, double poi2) { // Find minimum between two values\n return (poi1 < poi2)? poi1 : poi2;\n}\ndouble Closest_dist_Spoint(poi stp[], int s, double dist, poi &pnt1, poi &pnt2) { // Calculate distance beween the closest points\n double Minimum = dist; // Initialize the minimum distance as dist\n qsort(stp, s, sizeof(poi), Comp_poi2);\n for (int i = 0; i < s; ++i)\n for (int j = i+1; j < s && (stp[j].poi2 - stp[i].poi2) < Minimum; ++j)\n if (Distance(stp[i],stp[j]) < Minimum) {\n Minimum = Distance(stp[i], stp[j]);\n pnt1.poi1 = stp[i].poi1, pnt1.poi2 = stp[i].poi2;\n pnt2.poi1 = stp[j].poi1, pnt2.poi2 = stp[j].poi2;\n }\n return Minimum;\n}\ndouble Closest_dist(poi P[], poi stp[], int n, poi &pnt1, poi &pnt2) { // Calculate smallest distance.\n static poi pt1, pt2, pt3, pt4;\n if (n <= 3)\n return S_Distance(P, n, pt1, pt2);\n int medium = n/2; // Calculate the mid point\n poi mediumPoint = P[medium];\n double D_Left = Closest_dist(P, stp, medium, pt1, pt2); // D_Left: left of medium point\n double D_Right = Closest_dist(P + medium, stp, n-medium, pt3, pt4); // D_Right: right side of the medium point\n if(D_Left < D_Right) {\n pnt1.poi1 = pt1.poi1; pnt1.poi2 = pt1.poi2; // Store the pair that has smaller distance\n pnt2.poi1 = pt2.poi1; pnt2.poi2 = pt2.poi2;\n } else {\n pnt1.poi1 = pt3.poi1; pnt1.poi2 = pt3.poi2;\n pnt2.poi1 = pt4.poi1; pnt2.poi2 = pt4.poi2;\n }\n double min_dist = Minimum(D_Left, D_Right);\n int j = 0;\n for (int i = 0; i < n; i++)\n if (abs(P[i].poi1 - mediumPoint.poi1) < min_dist)\n stp[j++] = P[i];\n double min_dist_strip = Closest_dist_Spoint(stp, j, min_dist, pt1, pt2);\n double F_Min = min_dist;\n if(min_dist_strip < min_dist) {\n pnt1.poi1 = pt1.poi1; pnt1.poi2 = pt1.poi2;\n pnt2.poi1 = pt2.poi1; pnt2.poi2 = pt2.poi2;\n F_Min = min_dist_strip;\n }\n return F_Min;\n}\nint main() {\n poi P[] = {{4, 1}, {15, 20}, {30, 40}, {8, 4}, {13, 11}, {5, 6}};\n poi pnt1 = {DBL_MAX, DBL_MAX}, pnt2 = {DBL_MAX, DBL_MAX}; // Closest pair of points in array\n int n = sizeof(P) / sizeof(P[0]);\n qsort(P, n, sizeof(poi), Comp_poi1);\n poi *stp = new poi[n];\n cout << \"The closest distance of point in array is: \" << Closest_dist(P, stp, n, pnt1, pnt2) << endl;\n cout << \"The closest pair of point in array: (\" << pnt1.poi1 << \",\" << pnt1.poi2 << \") and (\"\n << pnt2.poi1 << \",\" << pnt2.poi2 << \")\" << endl;\n delete[] stp;\n return 0;\n}"
},
{
"code": null,
"e": 6919,
"s": 6812,
"text": "The closest distance of point in array is: 3.60555\nThe closest pair of point in array: (13,11) and (15,20)"
}
] |
Conditional rendering component using Enums in ReactJS - GeeksforGeeks
|
23 Nov, 2021
In some situations, React Js developer needs to render and hide components based on the particular condition. For example, while building a To-do list app, the developer needs to render tasks if any pending task is available otherwise they need to show a message like “There is no pending task available.”
There are several methods to render components conditionally in react Js such as if-else, and ternary operator, etc. If only 2 to 3 components are available to render conditionally, developers can use if-else or switch case method. If there are more than 3 components available to render conditionally, if-else becomes complex. So, developers should use enums to keep code clean.
In this tutorial, we are going to learn that how developers can render components conditionally using enums. To start with enums, users need to create a new react project.
Creating react project:
Step 1: To create a new React project, run the below command to your terminal.
npx create-react-app testapp
Step 2: To move inside the project directory, run the below command to your terminal.
cd testapp
Now, you have created react app successfully.
Next, users need to create 2 to 3 components in our project. Create a ‘components‘ folder inside the ‘src‘ folder. Also, create the first.js and second.js files inside the components folder.
Project structure: It should look like the below image.
In this file, we will add some basic React code to render on the webpage. The user needs to add the following code to the ‘first.js’ file.
Filename: first.js
Javascript
import React, { Component } from 'react'; // Some basic code to render first componentclass First extends Component { render() { return ( <div> <h1 style={{color: "green"}}>GeeksForGeeks</h1> <h2>This is a first component</h2> </div> ); }} export default First;
In this file, we will add some basic React code that is different from the first component. So, we can know which component is rendering on the screen. Edit the ‘second.js’ file and add the below code inside it.
Filename: second.js
Javascript
import React, { Component } from 'react'; // some basic code to render second componentclass Second extends Component { render() { return ( <div> <h1 style={{color: "green"}}>GeeksForGeeks</h1> <h2>This is a second component.</h2> </div> ); }} export default Second;
Rendering component using enum
Step 1: In javascript, we can create an object with key-value pairs and use it as an enum. Below, you can see the demo of a javascript object with key-value pair.
Syntax:
const Enumobj = {
key: value,
};
Example:
const Enumobj = {
first: <First />,
second: <Second />
};
Step 2: Now, we will make a javascript function that takes a state as a parameter and return a React component based on the state.
Syntax:
function Enum({state}){
return {object[state]};
}
Example:
function Enum({ state }) {
return <div>{Enumobj[state]}</div>;
}
Step 3: Let’s embed the ‘Enum‘ function in our ‘App‘ component. While calling the ‘Enum‘ function, we will add state value as props.
Syntax:
return (
<div>
<Enum state="Value"></Enum>
</div>
);
Example:
return (
<div>
<Enum state="first"></Enum>
<Enum state="second"></Enum>
</div>
);
Filename: App.js
In the App.js file, we will create an enum object first. After that, we will add an ‘enum’ function to render components according to state value. At last, we will edit the ‘App‘ component and call the ‘enum‘ function inside the component to render it conditionally. The user needs to add the below code to the ‘App.js‘ file.
Filename: App.js
Javascript
import React, { Component } from 'react';import Second from './components/second'import First from './components/first' // Creating enum objectconst Enumobj = { first: <First />, second: <Second />}; // Creating enum function to return// Particular component according to state valuefunction Enum({ state }) { return <div>{Enumobj[state]}</div>;} // Call enum function inside the App componentclass App extends Component { render() { return ( <div> <Enum state="first"></Enum> <Enum state="second"></Enum> </div> ); }} export default App;
Steps to run: The user needs to run beneath the command to the terminal in the current directory to see the output.
npm start
Output:
sumitgumber28
React-Questions
Program Output
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of C programs | Set 31 (Pointers)
Output of C Program | Set 24
How to show full column content in a PySpark Dataframe ?
unsigned specifier (%u) in C with Examples
Output of Java Programs | Set 12
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
Create a Responsive Navbar using ReactJS
How to pass data from one component to other component in ReactJS ?
|
[
{
"code": null,
"e": 24330,
"s": 24302,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 24636,
"s": 24330,
"text": "In some situations, React Js developer needs to render and hide components based on the particular condition. For example, while building a To-do list app, the developer needs to render tasks if any pending task is available otherwise they need to show a message like “There is no pending task available.”"
},
{
"code": null,
"e": 25016,
"s": 24636,
"text": "There are several methods to render components conditionally in react Js such as if-else, and ternary operator, etc. If only 2 to 3 components are available to render conditionally, developers can use if-else or switch case method. If there are more than 3 components available to render conditionally, if-else becomes complex. So, developers should use enums to keep code clean."
},
{
"code": null,
"e": 25188,
"s": 25016,
"text": "In this tutorial, we are going to learn that how developers can render components conditionally using enums. To start with enums, users need to create a new react project."
},
{
"code": null,
"e": 25212,
"s": 25188,
"text": "Creating react project:"
},
{
"code": null,
"e": 25291,
"s": 25212,
"text": "Step 1: To create a new React project, run the below command to your terminal."
},
{
"code": null,
"e": 25320,
"s": 25291,
"text": "npx create-react-app testapp"
},
{
"code": null,
"e": 25406,
"s": 25320,
"text": "Step 2: To move inside the project directory, run the below command to your terminal."
},
{
"code": null,
"e": 25417,
"s": 25406,
"text": "cd testapp"
},
{
"code": null,
"e": 25464,
"s": 25417,
"text": "Now, you have created react app successfully. "
},
{
"code": null,
"e": 25655,
"s": 25464,
"text": "Next, users need to create 2 to 3 components in our project. Create a ‘components‘ folder inside the ‘src‘ folder. Also, create the first.js and second.js files inside the components folder."
},
{
"code": null,
"e": 25711,
"s": 25655,
"text": "Project structure: It should look like the below image."
},
{
"code": null,
"e": 25850,
"s": 25711,
"text": "In this file, we will add some basic React code to render on the webpage. The user needs to add the following code to the ‘first.js’ file."
},
{
"code": null,
"e": 25869,
"s": 25850,
"text": "Filename: first.js"
},
{
"code": null,
"e": 25880,
"s": 25869,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'; // Some basic code to render first componentclass First extends Component { render() { return ( <div> <h1 style={{color: \"green\"}}>GeeksForGeeks</h1> <h2>This is a first component</h2> </div> ); }} export default First;",
"e": 26175,
"s": 25880,
"text": null
},
{
"code": null,
"e": 26388,
"s": 26175,
"text": " In this file, we will add some basic React code that is different from the first component. So, we can know which component is rendering on the screen. Edit the ‘second.js’ file and add the below code inside it."
},
{
"code": null,
"e": 26408,
"s": 26388,
"text": "Filename: second.js"
},
{
"code": null,
"e": 26419,
"s": 26408,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'; // some basic code to render second componentclass Second extends Component { render() { return ( <div> <h1 style={{color: \"green\"}}>GeeksForGeeks</h1> <h2>This is a second component.</h2> </div> ); }} export default Second;",
"e": 26719,
"s": 26419,
"text": null
},
{
"code": null,
"e": 26752,
"s": 26719,
"text": " Rendering component using enum "
},
{
"code": null,
"e": 26915,
"s": 26752,
"text": "Step 1: In javascript, we can create an object with key-value pairs and use it as an enum. Below, you can see the demo of a javascript object with key-value pair."
},
{
"code": null,
"e": 26923,
"s": 26915,
"text": "Syntax:"
},
{
"code": null,
"e": 26958,
"s": 26923,
"text": "const Enumobj = {\n key: value,\n};"
},
{
"code": null,
"e": 26967,
"s": 26958,
"text": "Example:"
},
{
"code": null,
"e": 27029,
"s": 26967,
"text": "const Enumobj = {\n first: <First />,\n second: <Second />\n};"
},
{
"code": null,
"e": 27160,
"s": 27029,
"text": "Step 2: Now, we will make a javascript function that takes a state as a parameter and return a React component based on the state."
},
{
"code": null,
"e": 27168,
"s": 27160,
"text": "Syntax:"
},
{
"code": null,
"e": 27220,
"s": 27168,
"text": "function Enum({state}){\n return {object[state]};\n}"
},
{
"code": null,
"e": 27229,
"s": 27220,
"text": "Example:"
},
{
"code": null,
"e": 27296,
"s": 27229,
"text": "function Enum({ state }) {\n return <div>{Enumobj[state]}</div>;\n}"
},
{
"code": null,
"e": 27430,
"s": 27296,
"text": "Step 3: Let’s embed the ‘Enum‘ function in our ‘App‘ component. While calling the ‘Enum‘ function, we will add state value as props. "
},
{
"code": null,
"e": 27438,
"s": 27430,
"text": "Syntax:"
},
{
"code": null,
"e": 27516,
"s": 27438,
"text": " return (\n <div>\n <Enum state=\"Value\"></Enum>\n </div>\n );"
},
{
"code": null,
"e": 27525,
"s": 27516,
"text": "Example:"
},
{
"code": null,
"e": 27640,
"s": 27525,
"text": " return (\n <div>\n <Enum state=\"first\"></Enum>\n <Enum state=\"second\"></Enum>\n </div>\n );"
},
{
"code": null,
"e": 27657,
"s": 27640,
"text": "Filename: App.js"
},
{
"code": null,
"e": 27983,
"s": 27657,
"text": "In the App.js file, we will create an enum object first. After that, we will add an ‘enum’ function to render components according to state value. At last, we will edit the ‘App‘ component and call the ‘enum‘ function inside the component to render it conditionally. The user needs to add the below code to the ‘App.js‘ file."
},
{
"code": null,
"e": 28000,
"s": 27983,
"text": "Filename: App.js"
},
{
"code": null,
"e": 28011,
"s": 28000,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react';import Second from './components/second'import First from './components/first' // Creating enum objectconst Enumobj = { first: <First />, second: <Second />}; // Creating enum function to return// Particular component according to state valuefunction Enum({ state }) { return <div>{Enumobj[state]}</div>;} // Call enum function inside the App componentclass App extends Component { render() { return ( <div> <Enum state=\"first\"></Enum> <Enum state=\"second\"></Enum> </div> ); }} export default App;",
"e": 28586,
"s": 28011,
"text": null
},
{
"code": null,
"e": 28703,
"s": 28586,
"text": " Steps to run: The user needs to run beneath the command to the terminal in the current directory to see the output."
},
{
"code": null,
"e": 28714,
"s": 28703,
"text": " npm start"
},
{
"code": null,
"e": 28722,
"s": 28714,
"text": "Output:"
},
{
"code": null,
"e": 28738,
"s": 28724,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28754,
"s": 28738,
"text": "React-Questions"
},
{
"code": null,
"e": 28769,
"s": 28754,
"text": "Program Output"
},
{
"code": null,
"e": 28777,
"s": 28769,
"text": "ReactJS"
},
{
"code": null,
"e": 28794,
"s": 28777,
"text": "Web Technologies"
},
{
"code": null,
"e": 28892,
"s": 28794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28933,
"s": 28892,
"text": "Output of C programs | Set 31 (Pointers)"
},
{
"code": null,
"e": 28962,
"s": 28933,
"text": "Output of C Program | Set 24"
},
{
"code": null,
"e": 29019,
"s": 28962,
"text": "How to show full column content in a PySpark Dataframe ?"
},
{
"code": null,
"e": 29062,
"s": 29019,
"text": "unsigned specifier (%u) in C with Examples"
},
{
"code": null,
"e": 29095,
"s": 29062,
"text": "Output of Java Programs | Set 12"
},
{
"code": null,
"e": 29138,
"s": 29095,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29183,
"s": 29138,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 29248,
"s": 29183,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 29289,
"s": 29248,
"text": "Create a Responsive Navbar using ReactJS"
}
] |
Longest Palindromic Substring | Practice | GeeksforGeeks
|
Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least starting index ).
Example 1:
Input:
S = "aaaabbaa"
Output:
aabbaa
Explanation:
The longest palindrome string present in
the given string is "aabbaa".
Your Task:
You don't need to read input or print anything. Your task is to complete the function longestPalindrome() which takes string S as input parameters and returns longest pallindrome present in string.
Expected Time Complexity: O(|S|2)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ |S| ≤ 104
0
jy9041473 hours ago
Esay with 100% solve by Yadav jitu
class Solution{ String longestPalindrome(String s){ if(s.length()<2) return s; String longStr=s.substring(0,1); for (int i = 0; i <s.length() ; i++) { //check for odd string length String tempStr=checkInput(s,i,i); if(longStr.length()<tempStr.length()) { longStr=tempStr; } //check for even string length tempStr = checkInput(s,i,i+1); if(longStr.length()<tempStr.length()) { longStr=tempStr; } }
return longStr; } public static String checkInput(String str, int left, int right){ while(left>=0 && right <str.length() && str.charAt(left)==str.charAt(right)){ left--; right++; }
return str.substring(left+1,right); }}
+1
manoj3821 week ago
class Solution{
public:
string longestPalindrome(string S){
// code here
int ans=1,n=S.length();
string t;
for(int i=0;i<n;i++){
// for odd length substring
int a=i-1,b=i+1,temp=1;
while(a>=0&&b<n&&S[a]==S[b]){
a--,b++;temp+=2;
}
if(temp>ans){t=S.substr(a+1,temp);ans=temp;}
//for even length substring
a=i,b=i+1,temp=0;
while(a>=0&&b<n&&S[a]==S[b]){
a--,b++;temp+=2;
}
if(temp>ans){t=S.substr(a+1,temp);ans=temp;}
}
if(ans==1){t=S[0];return t;}
return t;
}
};
0
getkar1281 month ago
def longestPalindrome(self, S):
# code here
res = ""
resLen = 0
for i in range(len(S)):
# odd length
l, r = i, i
while l >= 0 and r < len(S) and S[l] == S[r]:
if r-l+1 > resLen:
res = S[l:r+1]
resLen = r-l+1
l -= 1
r += 1
l, r = i, i+1
while l >= 0 and r < len(S) and S[l] == S[r]:
if r-l+1 > resLen:
res = S[l:r+1]
resLen = r-l+1
l -= 1
r += 1
return res
+2
dhruvvsingh221 month ago
Long code but simple approach ans easy to understand using 2d dp table
class Solution{
public:
string longestPalindrome(string str)
{
int n = str.length();
int dp[n][n];
int maxLength=1;
int start = 0;
int end = 0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
{
dp[i][j] = 0;
}
}
for(int i=0;i<n;i++)
{
dp[i][i] = 1;
}
for(int i=0;i<n;i++)
{
if(str[i]==str[i+1])
{
dp[i][i+1] = 1;
if(maxLength<2)
{
start = i;
end = i+1;
maxLength = 2;
}
}
}
for(int i=2;i<n;i++){
for(int j=0,k=i;j<n-i,k<n;j++,k++){
if(str[j]==str[k] && dp[j+1][k-1]==1)
{
dp[j][k] = 1;
if(maxLength<abs(k-j+1))
{
start = j;
end = k;
maxLength = max(maxLength,abs(k-j+1));
}
}
}
}
return str.substr(start,end-start+1);
}
};
+1
madhukartemba1 month ago
JAVA SOLUTION:
SOURCE: https://www.youtube.com/watch?v=WpYHNHofwjc
String longestPalindrome(String S){
// code here
int n = S.length();
boolean dp[][] = new boolean[n][n];
int max_len = 1;
int st = 0, en = 0;
for(int gap=0; gap<n; gap++)
{
for(int i=0, j=gap; j<n; j++, i++)
{
if(gap==0)
{
dp[i][j] = true;
}
else if(gap==1)
{
if(S.charAt(i)==S.charAt(j))
{
dp[i][j] = true;
}
else
{
dp[i][j] = false;
}
}
else
{
if(S.charAt(i)==S.charAt(j))
{
dp[i][j] = dp[i+1][j-1];
}
else
{
dp[i][j] = false;
}
}
if(dp[i][j] == true)
{
//System.out.println(i + " " + j);
if(gap+1>max_len)
{
st = i;
en = j;
max_len = gap+1;
}
else if(gap+1==max_len)
{
if(i<st)
{
st = i;
gap = j;
}
}
}
}
}
return S.substring(st, en+1);
}
-1
sudarshanp49122 months ago
EASY TO UNDERSTAND SOLUTION:
bool isPalindrome(string str)
{
int n=str.length();
for(int i=0;i<n/2;i++)
{
if(str[i]!=str[n-1-i])
return false;
}
return true;
}
string longestPalindrome(string S)
{
if(isPalindrome(S))
return S;
int n=S.length(),ans=0;
string sol;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
string str=S.substr(i,j-i+1);
if(isPalindrome(str))
{
int len=str.length();
if(len>ans)
{
ans=len;
sol=str;
}
}
}
}
return sol;
}
0
mikumar2 months ago
class Solution{ public static boolean pal(String s) { int l =0 ; int h = s.length()-1; while(l<h) { if(s.charAt(l)!=s.charAt(h)) return false; l++; h--; } return true; } String longestPalindrome(String s){ ArrayList<String>al = new ArrayList<>(); for(int i =0 ; i<s.length() ; i++){ for(int j = i+1 ; j<=s.length(); j++){ al.add(s.substring(i , j)); } } String msi =""; int maxi=-1; for(int i =0 ; i<al.size();i++) { if(pal(al.get(i))==true) { if(al.get(i).length()>maxi) { maxi = al.get(i).length(); msi = al.get(i); } } } return msi; }}
+1
dassdazzer1232 months ago
TC-→O(n2) || SC-→ O(1)
string longestPalindrome(string S){ if(S.length()<=1) return S; int mx_len=1; int n=S.length(); int start=0,end=0; //odd length palindrome for(int i=0;i<n;i++) { int l=i,r=i; while(l>=0 && r<n) { if(S[l]==S[r]) { l--; r++; } else break; } int len=r-l-1; if(len>mx_len) { mx_len=len; start=l+1; end=r-1; } } //Even length palindrome for(int i=0;i<n;i++) { int l=i,r=i+1; while(l>=0 && r<n) { if(S[l]==S[r]) { l--; r++; } else break; } int len=r-l-1; if(len>mx_len) { mx_len=len; start=l+1; end=r-1; } } return S.substr(start,mx_len); }
0
tanishqspike1142 months ago
C++ Code | O(N^2) Time and O(1) Space Solution
class Solution{
private:
pair<int,int> expand(string &S,int L,int R){
while(L>=0 and R<S.length() and S[L]==S[R]){
L--;
R++;
}
if(S[L]!=S[R]){
L++;
R--;
}
return {L,R};
}
public:
string longestPalindrome(string S){
/*
Using the property that a panlindrom mirrors from its center we try to expand from everypoint
and from everypoint we will try to go as many spaces in right and left till they both are equal
*/
using paint=pair<int,int>;
int start=0,end=0,n=S.length()-1;
for(int i=0;i<n;i++){
paint a=expand(S,i,i);
paint b=expand(S,i,i+1);
paint final = a.second-a.first>b.second-b.first?a:b;
if(final.second-final.first>end-start){
start=final.first;
end=final.second;
}
}
start=max(0,start);
end=min(n,end);
return S.substr(start,end-start+1);
}
};
+2
navidulhaque2 months ago
TC-O(n)^2 .... SC-O(n)^2for better understanding watch pepcoding's video
string longestPalindrome(string s){
int n=s.size();
int dp[n][n];
memset(dp,0,sizeof(dp));
int ans=INT_MIN;
int st=0;
int en=0;
string res;
for(int gap=0;gap<n;gap++){
for(int i=0,j=gap;j<n;j++,i++){
if(gap==0){
dp[i][j]=1;
}
else if(gap==1){
dp[i][j]=s[i]==s[j]?1:0;
}
else{
dp[i][j]=s[i]==s[j]?dp[i+1][j-1]:0;
}
if(ans<j-i&&dp[i][j]==1){
ans=j-i;
st=i;
en=j-i;
}
}
}
return s.substr(st,en+1);
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 572,
"s": 238,
"text": "Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least starting index )."
},
{
"code": null,
"e": 584,
"s": 572,
"text": "\nExample 1:"
},
{
"code": null,
"e": 705,
"s": 584,
"text": "Input:\nS = \"aaaabbaa\"\nOutput:\naabbaa\nExplanation:\nThe longest palindrome string present in\nthe given string is \"aabbaa\"."
},
{
"code": null,
"e": 917,
"s": 705,
"text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function longestPalindrome() which takes string S as input parameters and returns longest pallindrome present in string."
},
{
"code": null,
"e": 983,
"s": 917,
"text": "\nExpected Time Complexity: O(|S|2)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1011,
"s": 983,
"text": "\nConstraints:\n1 ≤ |S| ≤ 104"
},
{
"code": null,
"e": 1013,
"s": 1011,
"text": "0"
},
{
"code": null,
"e": 1033,
"s": 1013,
"text": "jy9041473 hours ago"
},
{
"code": null,
"e": 1069,
"s": 1033,
"text": "Esay with 100% solve by Yadav jitu"
},
{
"code": null,
"e": 1630,
"s": 1069,
"text": " class Solution{ String longestPalindrome(String s){ if(s.length()<2) return s; String longStr=s.substring(0,1); for (int i = 0; i <s.length() ; i++) { //check for odd string length String tempStr=checkInput(s,i,i); if(longStr.length()<tempStr.length()) { longStr=tempStr; } //check for even string length tempStr = checkInput(s,i,i+1); if(longStr.length()<tempStr.length()) { longStr=tempStr; } }"
},
{
"code": null,
"e": 1854,
"s": 1630,
"text": " return longStr; } public static String checkInput(String str, int left, int right){ while(left>=0 && right <str.length() && str.charAt(left)==str.charAt(right)){ left--; right++; }"
},
{
"code": null,
"e": 1902,
"s": 1854,
"text": " return str.substring(left+1,right); }}"
},
{
"code": null,
"e": 1905,
"s": 1902,
"text": "+1"
},
{
"code": null,
"e": 1924,
"s": 1905,
"text": "manoj3821 week ago"
},
{
"code": null,
"e": 2658,
"s": 1924,
"text": "class Solution{ \npublic:\n string longestPalindrome(string S){\n // code here \n int ans=1,n=S.length();\n string t;\n for(int i=0;i<n;i++){\n // for odd length substring\n int a=i-1,b=i+1,temp=1;\n while(a>=0&&b<n&&S[a]==S[b]){\n a--,b++;temp+=2;\n }\n if(temp>ans){t=S.substr(a+1,temp);ans=temp;}\n //for even length substring\n \n a=i,b=i+1,temp=0;\n while(a>=0&&b<n&&S[a]==S[b]){\n a--,b++;temp+=2;\n }\n if(temp>ans){t=S.substr(a+1,temp);ans=temp;}\n \n \n \n }\n if(ans==1){t=S[0];return t;}\n return t; \n }\n};"
},
{
"code": null,
"e": 2660,
"s": 2658,
"text": "0"
},
{
"code": null,
"e": 2681,
"s": 2660,
"text": "getkar1281 month ago"
},
{
"code": null,
"e": 3293,
"s": 2681,
"text": "def longestPalindrome(self, S):\n # code here\n res = \"\"\n resLen = 0\n for i in range(len(S)):\n # odd length\n l, r = i, i\n while l >= 0 and r < len(S) and S[l] == S[r]:\n if r-l+1 > resLen:\n res = S[l:r+1]\n resLen = r-l+1\n l -= 1\n r += 1\n l, r = i, i+1\n while l >= 0 and r < len(S) and S[l] == S[r]:\n if r-l+1 > resLen:\n res = S[l:r+1]\n resLen = r-l+1\n l -= 1\n r += 1\n return res"
},
{
"code": null,
"e": 3296,
"s": 3293,
"text": "+2"
},
{
"code": null,
"e": 3321,
"s": 3296,
"text": "dhruvvsingh221 month ago"
},
{
"code": null,
"e": 4577,
"s": 3321,
"text": "Long code but simple approach ans easy to understand using 2d dp table\nclass Solution{ \npublic:\n string longestPalindrome(string str)\n {\n int n = str.length();\n int dp[n][n];\n int maxLength=1;\n int start = 0;\n int end = 0;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++)\n {\n dp[i][j] = 0;\n }\n }\n for(int i=0;i<n;i++)\n {\n dp[i][i] = 1;\n }\n for(int i=0;i<n;i++)\n {\n if(str[i]==str[i+1])\n {\n dp[i][i+1] = 1;\n if(maxLength<2)\n {\n start = i;\n end = i+1;\n maxLength = 2;\n }\n }\n }\n for(int i=2;i<n;i++){\n for(int j=0,k=i;j<n-i,k<n;j++,k++){\n if(str[j]==str[k] && dp[j+1][k-1]==1)\n {\n dp[j][k] = 1;\n if(maxLength<abs(k-j+1))\n {\n start = j;\n end = k;\n maxLength = max(maxLength,abs(k-j+1));\n }\n }\n }\n }\n return str.substr(start,end-start+1);\n }\n};"
},
{
"code": null,
"e": 4580,
"s": 4577,
"text": "+1"
},
{
"code": null,
"e": 4605,
"s": 4580,
"text": "madhukartemba1 month ago"
},
{
"code": null,
"e": 4620,
"s": 4605,
"text": "JAVA SOLUTION:"
},
{
"code": null,
"e": 4672,
"s": 4620,
"text": "SOURCE: https://www.youtube.com/watch?v=WpYHNHofwjc"
},
{
"code": null,
"e": 6424,
"s": 4672,
"text": "String longestPalindrome(String S){\n // code here\n int n = S.length();\n \n boolean dp[][] = new boolean[n][n];\n \n int max_len = 1;\n \n int st = 0, en = 0;\n \n for(int gap=0; gap<n; gap++)\n {\n for(int i=0, j=gap; j<n; j++, i++)\n {\n if(gap==0)\n {\n dp[i][j] = true;\n }\n else if(gap==1)\n {\n if(S.charAt(i)==S.charAt(j))\n {\n dp[i][j] = true;\n }\n else\n {\n dp[i][j] = false;\n }\n }\n else\n {\n if(S.charAt(i)==S.charAt(j))\n {\n dp[i][j] = dp[i+1][j-1];\n }\n else\n {\n dp[i][j] = false;\n }\n \n }\n \n if(dp[i][j] == true)\n {\n //System.out.println(i + \" \" + j);\n if(gap+1>max_len)\n {\n st = i;\n en = j;\n max_len = gap+1;\n }\n else if(gap+1==max_len)\n {\n if(i<st)\n {\n st = i;\n gap = j;\n }\n }\n }\n }\n }\n \n return S.substring(st, en+1);\n \n \n \n }"
},
{
"code": null,
"e": 6427,
"s": 6424,
"text": "-1"
},
{
"code": null,
"e": 6454,
"s": 6427,
"text": "sudarshanp49122 months ago"
},
{
"code": null,
"e": 6483,
"s": 6454,
"text": "EASY TO UNDERSTAND SOLUTION:"
},
{
"code": null,
"e": 7309,
"s": 6483,
"text": "bool isPalindrome(string str)\n {\n int n=str.length();\n for(int i=0;i<n/2;i++)\n {\n if(str[i]!=str[n-1-i])\n return false;\n }\n return true;\n }\n \n string longestPalindrome(string S)\n {\n if(isPalindrome(S))\n return S;\n \n int n=S.length(),ans=0;\n string sol;\n \n for(int i=0;i<n;i++)\n {\n for(int j=i;j<n;j++)\n {\n string str=S.substr(i,j-i+1);\n \n if(isPalindrome(str))\n {\n int len=str.length();\n if(len>ans)\n {\n ans=len;\n sol=str;\n }\n }\n }\n }\n return sol;\n }"
},
{
"code": null,
"e": 7311,
"s": 7309,
"text": "0"
},
{
"code": null,
"e": 7331,
"s": 7311,
"text": "mikumar2 months ago"
},
{
"code": null,
"e": 8115,
"s": 7331,
"text": "class Solution{ public static boolean pal(String s) { int l =0 ; int h = s.length()-1; while(l<h) { if(s.charAt(l)!=s.charAt(h)) return false; l++; h--; } return true; } String longestPalindrome(String s){ ArrayList<String>al = new ArrayList<>(); for(int i =0 ; i<s.length() ; i++){ for(int j = i+1 ; j<=s.length(); j++){ al.add(s.substring(i , j)); } } String msi =\"\"; int maxi=-1; for(int i =0 ; i<al.size();i++) { if(pal(al.get(i))==true) { if(al.get(i).length()>maxi) { maxi = al.get(i).length(); msi = al.get(i); } } } return msi; }} "
},
{
"code": null,
"e": 8118,
"s": 8115,
"text": "+1"
},
{
"code": null,
"e": 8144,
"s": 8118,
"text": "dassdazzer1232 months ago"
},
{
"code": null,
"e": 8168,
"s": 8144,
"text": "TC-→O(n2) || SC-→ O(1)"
},
{
"code": null,
"e": 9269,
"s": 8170,
"text": "string longestPalindrome(string S){ if(S.length()<=1) return S; int mx_len=1; int n=S.length(); int start=0,end=0; //odd length palindrome for(int i=0;i<n;i++) { int l=i,r=i; while(l>=0 && r<n) { if(S[l]==S[r]) { l--; r++; } else break; } int len=r-l-1; if(len>mx_len) { mx_len=len; start=l+1; end=r-1; } } //Even length palindrome for(int i=0;i<n;i++) { int l=i,r=i+1; while(l>=0 && r<n) { if(S[l]==S[r]) { l--; r++; } else break; } int len=r-l-1; if(len>mx_len) { mx_len=len; start=l+1; end=r-1; } } return S.substr(start,mx_len); }"
},
{
"code": null,
"e": 9271,
"s": 9269,
"text": "0"
},
{
"code": null,
"e": 9299,
"s": 9271,
"text": "tanishqspike1142 months ago"
},
{
"code": null,
"e": 9346,
"s": 9299,
"text": "C++ Code | O(N^2) Time and O(1) Space Solution"
},
{
"code": null,
"e": 10394,
"s": 9346,
"text": "class Solution{ \nprivate:\n pair<int,int> expand(string &S,int L,int R){\n while(L>=0 and R<S.length() and S[L]==S[R]){\n L--;\n R++;\n }\n if(S[L]!=S[R]){\n L++;\n R--;\n }\n return {L,R};\n }\npublic:\n string longestPalindrome(string S){\n /*\n Using the property that a panlindrom mirrors from its center we try to expand from everypoint\n and from everypoint we will try to go as many spaces in right and left till they both are equal\n */\n using paint=pair<int,int>;\n int start=0,end=0,n=S.length()-1;\n for(int i=0;i<n;i++){\n paint a=expand(S,i,i);\n paint b=expand(S,i,i+1);\n paint final = a.second-a.first>b.second-b.first?a:b;\n if(final.second-final.first>end-start){\n start=final.first;\n end=final.second;\n }\n }\n start=max(0,start);\n end=min(n,end);\n return S.substr(start,end-start+1);\n }\n};"
},
{
"code": null,
"e": 10397,
"s": 10394,
"text": "+2"
},
{
"code": null,
"e": 10422,
"s": 10397,
"text": "navidulhaque2 months ago"
},
{
"code": null,
"e": 10495,
"s": 10422,
"text": "TC-O(n)^2 .... SC-O(n)^2for better understanding watch pepcoding's video"
},
{
"code": null,
"e": 11248,
"s": 10495,
"text": "string longestPalindrome(string s){\n int n=s.size();\n int dp[n][n];\n memset(dp,0,sizeof(dp));\n int ans=INT_MIN;\n int st=0;\n int en=0;\n string res;\n for(int gap=0;gap<n;gap++){\n for(int i=0,j=gap;j<n;j++,i++){\n if(gap==0){\n dp[i][j]=1;\n }\n else if(gap==1){\n dp[i][j]=s[i]==s[j]?1:0;\n }\n else{\n dp[i][j]=s[i]==s[j]?dp[i+1][j-1]:0;\n }\n if(ans<j-i&&dp[i][j]==1){\n ans=j-i;\n st=i;\n en=j-i;\n }\n }\n }\n return s.substr(st,en+1);\n }"
},
{
"code": null,
"e": 11394,
"s": 11248,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 11430,
"s": 11394,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11440,
"s": 11430,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11450,
"s": 11440,
"text": "\nContest\n"
},
{
"code": null,
"e": 11513,
"s": 11450,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11661,
"s": 11513,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 11869,
"s": 11661,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 11975,
"s": 11869,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Check if a given number is Pronic - GeeksforGeeks
|
31 Jan, 2022
The numbers that can be arranged to form a rectangle are called Rectangular Numbers (also known as Pronic numbers). The first few Pronic numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 . . . . . . Pronic number is a number which is the product of two consecutive integers, that is, a number n is a product of x and (x+1). The task is to check and print Pronic Numbers in a range.Examples :
Input : 6
Output : Pronic Number
Explanation: 6 = 2 * 3 i.e 6 is a product
of two consecutive integers 2 and 3.
Input :56
Output :Pronic Number
Explanation: 56 = 7 * 8 i.e 56 is a product
of two consecutive integers 7 and 8.
Input : 8
Output : Not a Pronic Number
Explanation: 8 = 2 * 4 i.e 8 is a product of
2 and 4 which are not consecutive integers.
C++
Java
Python3
C#
PHP
Javascript
// C/C++ program to check// if a number is pronic#include <iostream>#include <math.h>using namespace std; // function to check// Pronic Numberbool checkPronic(int x){ for (int i = 0; i <= (int)(sqrt(x)); i++) // Checking Pronic Number // by multiplying consecutive // numbers if (x == i * (i + 1)) return true; return false;} // Driver Codeint main(void){ // Printing Pronic Numbers // upto 200 for (int i = 0; i <= 200; i++) if (checkPronic(i)) cout << i << " "; return 0;} // This code is contributed// by Nikita Tiwari.
// Java program to check and// Print Pronic Number upto 200import java.io.*;import java.util.*;import java.math.*; class GFG{ // function to check Pronic Number static boolean checkPronic(int x) { for (int i = 0; i <= (int)(Math.sqrt(x)); i++) // Checking Pronic Number // by multiplying consecutive // numbers if (x == i * (i + 1)) return true; return false; } // Driver Code public static void main(String[] args) { // Printing Pronic // Numbers upto 200 for (int i = 0; i <= 200; i++) if (checkPronic(i)) System.out.print(i + " "); }} // This code is contributed// by Nikita Tiwari
# Python program to check# and print Pronic Numbers# upto 200import math # function to check# Pronic Numberdef checkPronic (x) : i = 0 while ( i <= (int)(math.sqrt(x)) ) : # Checking Pronic Number # by multiplying consecutive # numbers if ( x == i * (i + 1)) : return True i = i + 1 return False # Driver Code # Printing Pronic# Numbers upto 200i = 0while (i <= 200 ) : if checkPronic(i) : print(i,end=" ") i = i + 1 # This code is contributed# by Nikita Tiwari.
// Java program to check and// Print Pronic Number upto 200using System; class GFG{ // function to check // Pronic Number static bool checkPronic(int x) { for (int i = 0; i <= (int)(Math.Sqrt(x)); i++) // Checking Pronic Number by // multiplying consecutive numbers if (x == i * (i + 1)) return true; return false; } // Driver Code public static void Main() { // Printing Pronic // Numbers upto 200 for (int i = 0; i <= 200; i++) if (checkPronic(i)) Console.Write(i + " "); }} // This code is contributed by vt_m.
<?php// PHP program to check// if a number is pronic // function to check// Pronic Numberfunction checkPronic($x){ for ($i = 0; $i <= (sqrt($x)); $i++) // Checking Pronic Number // by multiplying consecutive // numbers if ($x == $i * ($i + 1)) return true; return false;} // Driver Code // Printing Pronic// Numbers upto 200for ($i = 0; $i <= 200; $i++) if (checkPronic($i)) echo $i , " "; // This code is contributed by Ajit?>
<script> // Javascript program to check// if a number is pronic // function to check// Pronic Numberfunction checkPronic(x){ for (var i = 0; i <= parseInt(Math.sqrt(x)); i++) // Checking Pronic Number // by multiplying consecutive // numbers if (x == i * (i + 1)) return true; return false;} // Driver Code // Printing Pronic Numbers// upto 200for (var i = 0; i <= 200; i++) if (checkPronic(i)) document.write(i + " "); // This code is contributed by noob2000</script>
Output :
0 2 6 12 20 30 42 56 72 90 110 132 156 182
This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
noob2000
amartyaghoshgfg
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Program to find sum of elements in a given array
Program for Decimal to Binary Conversion
Program for factorial of a number
Operators in C / C++
The Knight's tour problem | Backtracking-1
Efficient program to print all prime factors of a given number
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
|
[
{
"code": null,
"e": 24802,
"s": 24774,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 25255,
"s": 24802,
"text": "The numbers that can be arranged to form a rectangle are called Rectangular Numbers (also known as Pronic numbers). The first few Pronic numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 . . . . . . Pronic number is a number which is the product of two consecutive integers, that is, a number n is a product of x and (x+1). The task is to check and print Pronic Numbers in a range.Examples : "
},
{
"code": null,
"e": 25615,
"s": 25255,
"text": "Input : 6\nOutput : Pronic Number\nExplanation: 6 = 2 * 3 i.e 6 is a product\nof two consecutive integers 2 and 3.\n\nInput :56\nOutput :Pronic Number\nExplanation: 56 = 7 * 8 i.e 56 is a product \nof two consecutive integers 7 and 8. \n\nInput : 8\nOutput : Not a Pronic Number\nExplanation: 8 = 2 * 4 i.e 8 is a product of \n2 and 4 which are not consecutive integers."
},
{
"code": null,
"e": 25621,
"s": 25617,
"text": "C++"
},
{
"code": null,
"e": 25626,
"s": 25621,
"text": "Java"
},
{
"code": null,
"e": 25634,
"s": 25626,
"text": "Python3"
},
{
"code": null,
"e": 25637,
"s": 25634,
"text": "C#"
},
{
"code": null,
"e": 25641,
"s": 25637,
"text": "PHP"
},
{
"code": null,
"e": 25652,
"s": 25641,
"text": "Javascript"
},
{
"code": "// C/C++ program to check// if a number is pronic#include <iostream>#include <math.h>using namespace std; // function to check// Pronic Numberbool checkPronic(int x){ for (int i = 0; i <= (int)(sqrt(x)); i++) // Checking Pronic Number // by multiplying consecutive // numbers if (x == i * (i + 1)) return true; return false;} // Driver Codeint main(void){ // Printing Pronic Numbers // upto 200 for (int i = 0; i <= 200; i++) if (checkPronic(i)) cout << i << \" \"; return 0;} // This code is contributed// by Nikita Tiwari.",
"e": 26276,
"s": 25652,
"text": null
},
{
"code": "// Java program to check and// Print Pronic Number upto 200import java.io.*;import java.util.*;import java.math.*; class GFG{ // function to check Pronic Number static boolean checkPronic(int x) { for (int i = 0; i <= (int)(Math.sqrt(x)); i++) // Checking Pronic Number // by multiplying consecutive // numbers if (x == i * (i + 1)) return true; return false; } // Driver Code public static void main(String[] args) { // Printing Pronic // Numbers upto 200 for (int i = 0; i <= 200; i++) if (checkPronic(i)) System.out.print(i + \" \"); }} // This code is contributed// by Nikita Tiwari",
"e": 27057,
"s": 26276,
"text": null
},
{
"code": "# Python program to check# and print Pronic Numbers# upto 200import math # function to check# Pronic Numberdef checkPronic (x) : i = 0 while ( i <= (int)(math.sqrt(x)) ) : # Checking Pronic Number # by multiplying consecutive # numbers if ( x == i * (i + 1)) : return True i = i + 1 return False # Driver Code # Printing Pronic# Numbers upto 200i = 0while (i <= 200 ) : if checkPronic(i) : print(i,end=\" \") i = i + 1 # This code is contributed# by Nikita Tiwari.",
"e": 27599,
"s": 27057,
"text": null
},
{
"code": "// Java program to check and// Print Pronic Number upto 200using System; class GFG{ // function to check // Pronic Number static bool checkPronic(int x) { for (int i = 0; i <= (int)(Math.Sqrt(x)); i++) // Checking Pronic Number by // multiplying consecutive numbers if (x == i * (i + 1)) return true; return false; } // Driver Code public static void Main() { // Printing Pronic // Numbers upto 200 for (int i = 0; i <= 200; i++) if (checkPronic(i)) Console.Write(i + \" \"); }} // This code is contributed by vt_m.",
"e": 28305,
"s": 27599,
"text": null
},
{
"code": "<?php// PHP program to check// if a number is pronic // function to check// Pronic Numberfunction checkPronic($x){ for ($i = 0; $i <= (sqrt($x)); $i++) // Checking Pronic Number // by multiplying consecutive // numbers if ($x == $i * ($i + 1)) return true; return false;} // Driver Code // Printing Pronic// Numbers upto 200for ($i = 0; $i <= 200; $i++) if (checkPronic($i)) echo $i , \" \"; // This code is contributed by Ajit?>",
"e": 28803,
"s": 28305,
"text": null
},
{
"code": "<script> // Javascript program to check// if a number is pronic // function to check// Pronic Numberfunction checkPronic(x){ for (var i = 0; i <= parseInt(Math.sqrt(x)); i++) // Checking Pronic Number // by multiplying consecutive // numbers if (x == i * (i + 1)) return true; return false;} // Driver Code // Printing Pronic Numbers// upto 200for (var i = 0; i <= 200; i++) if (checkPronic(i)) document.write(i + \" \"); // This code is contributed by noob2000</script>",
"e": 29348,
"s": 28803,
"text": null
},
{
"code": null,
"e": 29359,
"s": 29348,
"text": "Output : "
},
{
"code": null,
"e": 29402,
"s": 29359,
"text": "0 2 6 12 20 30 42 56 72 90 110 132 156 182"
},
{
"code": null,
"e": 29824,
"s": 29402,
"text": "This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29830,
"s": 29824,
"text": "jit_t"
},
{
"code": null,
"e": 29839,
"s": 29830,
"text": "noob2000"
},
{
"code": null,
"e": 29855,
"s": 29839,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 29862,
"s": 29855,
"text": "series"
},
{
"code": null,
"e": 29875,
"s": 29862,
"text": "Mathematical"
},
{
"code": null,
"e": 29888,
"s": 29875,
"text": "Mathematical"
},
{
"code": null,
"e": 29895,
"s": 29888,
"text": "series"
},
{
"code": null,
"e": 29993,
"s": 29895,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30017,
"s": 29993,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30060,
"s": 30017,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30109,
"s": 30060,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30150,
"s": 30109,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 30184,
"s": 30150,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 30205,
"s": 30184,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 30248,
"s": 30205,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 30311,
"s": 30248,
"text": "Efficient program to print all prime factors of a given number"
},
{
"code": null,
"e": 30364,
"s": 30311,
"text": "Find minimum number of coins that make a given value"
}
] |
Two interfaces with same methods having same signature but different return types - GeeksforGeeks
|
17 Apr, 2019
Java does not support multiple inheritances but we can achieve the effect of multiple inheritances using interfaces. In interfaces, a class can implement more than one interface which can’t be done through extends keyword.Please refer Multiple inheritance in java for more.Let’s say we have two interfaces with same method name (geek) and different return types(int and String)
public interface InterfaceX{ public int geek();}public interface InterfaceY{ public String geek();}
Now, Suppose we have a class that implements both those interfaces:
public class Testing implements InterfaceX, InterfaceY{public String geek() { return "hello"; }}
The question is: Can a java class implement Two interfaces with same methods having the same signature but different return types??No, its an errorIf two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously.According to JLS (§8.4.2) methods with same signature is not allowed in this case.
Two methods or constructors, M and N, have the same signature if they have,
the same name
the same type parameters (if any) (§8.4.4), and
after adopting the formal parameter types of N
to the type parameters of M, the same formal parameter types.
It is a compile-time error to declare two methods with override-equivalent signatures in a class.
// JAVA program to illustrate the behavior// of program when two interfaces having same // methods and different return-typeinterface bishal{public void show();} interface geeks{public int show();} class Test implements bishal, geeks{ void show() // Overloaded method based on return type, Error { } int show() // Error { return 1; }public static void main(String args[]) { }}
Output:
error: method show() is already defined in class Test
error: Test is not abstract and does not override abstract method show() in geeks
error: show() in Test cannot implement show() in bishal
// Java program to illustrate the behavior of the program// when two interfaces having the same methods and different return-type// and we defined the method in the child classinterface InterfaceA{public int fun();}interface InterfaceB{public String moreFun();} class MainClass implements InterfaceA, InterfaceB{public String getStuff() { return "one"; }}
error: MainClass is not abstract and does not override abstract method fun() in InterfaceA
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
Abstract Class and Interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 23581,
"s": 23553,
"text": "\n17 Apr, 2019"
},
{
"code": null,
"e": 23959,
"s": 23581,
"text": "Java does not support multiple inheritances but we can achieve the effect of multiple inheritances using interfaces. In interfaces, a class can implement more than one interface which can’t be done through extends keyword.Please refer Multiple inheritance in java for more.Let’s say we have two interfaces with same method name (geek) and different return types(int and String)"
},
{
"code": "public interface InterfaceX{ public int geek();}public interface InterfaceY{ public String geek();}",
"e": 24065,
"s": 23959,
"text": null
},
{
"code": null,
"e": 24133,
"s": 24065,
"text": "Now, Suppose we have a class that implements both those interfaces:"
},
{
"code": "public class Testing implements InterfaceX, InterfaceY{public String geek() { return \"hello\"; }}",
"e": 24243,
"s": 24133,
"text": null
},
{
"code": null,
"e": 24629,
"s": 24243,
"text": "The question is: Can a java class implement Two interfaces with same methods having the same signature but different return types??No, its an errorIf two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously.According to JLS (§8.4.2) methods with same signature is not allowed in this case."
},
{
"code": null,
"e": 24878,
"s": 24629,
"text": "Two methods or constructors, M and N, have the same signature if they have,\nthe same name\nthe same type parameters (if any) (§8.4.4), and\nafter adopting the formal parameter types of N \n to the type parameters of M, the same formal parameter types."
},
{
"code": null,
"e": 24976,
"s": 24878,
"text": "It is a compile-time error to declare two methods with override-equivalent signatures in a class."
},
{
"code": "// JAVA program to illustrate the behavior// of program when two interfaces having same // methods and different return-typeinterface bishal{public void show();} interface geeks{public int show();} class Test implements bishal, geeks{ void show() // Overloaded method based on return type, Error { } int show() // Error { return 1; }public static void main(String args[]) { }}",
"e": 25395,
"s": 24976,
"text": null
},
{
"code": null,
"e": 25403,
"s": 25395,
"text": "Output:"
},
{
"code": null,
"e": 25596,
"s": 25403,
"text": "error: method show() is already defined in class Test\nerror: Test is not abstract and does not override abstract method show() in geeks\nerror: show() in Test cannot implement show() in bishal\n"
},
{
"code": "// Java program to illustrate the behavior of the program// when two interfaces having the same methods and different return-type// and we defined the method in the child classinterface InterfaceA{public int fun();}interface InterfaceB{public String moreFun();} class MainClass implements InterfaceA, InterfaceB{public String getStuff() { return \"one\"; }}",
"e": 25975,
"s": 25596,
"text": null
},
{
"code": null,
"e": 26067,
"s": 25975,
"text": "error: MainClass is not abstract and does not override abstract method fun() in InterfaceA\n"
},
{
"code": null,
"e": 26373,
"s": 26067,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 26498,
"s": 26373,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26511,
"s": 26498,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26540,
"s": 26511,
"text": "Abstract Class and Interface"
},
{
"code": null,
"e": 26545,
"s": 26540,
"text": "Java"
},
{
"code": null,
"e": 26550,
"s": 26545,
"text": "Java"
},
{
"code": null,
"e": 26648,
"s": 26550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26657,
"s": 26648,
"text": "Comments"
},
{
"code": null,
"e": 26670,
"s": 26657,
"text": "Old Comments"
},
{
"code": null,
"e": 26700,
"s": 26670,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26715,
"s": 26700,
"text": "Stream In Java"
},
{
"code": null,
"e": 26736,
"s": 26715,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26782,
"s": 26736,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26801,
"s": 26782,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26818,
"s": 26801,
"text": "Generics in Java"
},
{
"code": null,
"e": 26861,
"s": 26818,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26877,
"s": 26861,
"text": "Strings in Java"
},
{
"code": null,
"e": 26933,
"s": 26877,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Character Recognition and Segmentation For Custom Data Using Detectron2 | by Syam Kakarla | Towards Data Science
|
What is Detectron2?
Project Setup
Build the Model
Training and Evaluation
Results
Resources
Detectron2 is an opensource object recognition and segmentation software system that implements state of the art algorithms as part of Facebook AI Research(FAIR). It is a ground-up rewrite in PyTorch to its previous version Detectron, and it originates from MaskRCNN-Benchmark.
You can see the details of Detectron2 along with the benchmark comparisons, different applications, customizations, and brief up on nuts and bolts of its working nature from PyTorch DevCon19.
The Detectron also provides a large collection of baselines trained with Detectron2 and you can access the code from Model Zoo to start with. Use this notebook provided by FAIR to play with Detectron2.
colab.research.google.com
We are going to develop a character recognition and segmentation for “Telugu Characters”. To build this project we need the data suitable for the mentioned machine learning task. As there is not sufficient data available we need to collect the custom data.
Use the article on “How to Prepare a Custom Dataset for Character Recognition and Segmentation?” to create your own custom data which includes tools and programs to collect data and preprocess and building annotations of data.
towardsdatascience.com
Here you can see the project structure consisting of the files and directories such as test_data and train_data consists of images and annotations for training and testing the models.
| Detectron2_Telugu_Characters.ipynb| label2coco.py| resize.py| test.json| train.json| Viewer.ipynb|+---results| res1.PNG| res2.PNG| res3.PNG| res4.PNG| res5.PNG| res6.PNG| res7.PNG|+---test_data| img1.json| img1.png| img10.json| img10.png| img11.json| img11.png| img12.json| img12.png| img13.json| img13.png| img14.json| img14.png| img15.json| img15.png| img16.json| img16.png| img17.json| img17.png| img18.json| img18.png| img19.json| img19.png| img2.json| img2.png| img20.json| img20.png| img3.json| img3.png| img4.json| img4.png| img5.json| img5.png| img6.json| img6.png| img7.json| img7.png| img8.json| img8.png| img9.json| img9.png|+---test_images| 81XtS7O3nUL._SL1500_.jpg| alpha1.jpg| download.jfif| images (1).jfif| images (2).jfif| images (2).png| images (3).jfif| images (3).png| images (4).jfif| images (4).png| images (5).jfif| images (5).png| images (6).jfif| images (7).jfif| images.jfif| images.png| test_1.jpg| x1080.jfif|\---train_data img1.json img1.png img10.json img10.png img100.json img100.png img101.json img101.png img102.json img102.png img103.json img103.png img104.json img104.png img105.json img105.png img106.json img106.png img107.json img107.png img108.json img108.png img109.json img109.png img11.json img11.png img110.json img110.png img111.json img111.png img112.json img112.png img113.json img113.png img114.json img114.png img115.json img115.png img116.json img116.png img117.json img117.png img118.json img118.png img119.json img119.png img12.json img12.png img120.json img120.png img121.json img121.png img122.json img122.png img123.json img123.png img124.json img124.png img125.json img125.png img126.json img126.png img127.json img127.png img128.json img128.png img129.json img129.png img13.json img13.png img130.json img130.png img131.json img131.png img132.json img132.png img133.json img133.png img134.json img134.png img135.json img135.png img136.json img136.png img137.json img137.png img138.json img138.png img139.json img139.png img14.json img14.png img140.json img140.png img141.json img141.png img142.json img142.png img143.json img143.png img144.json img144.png img145.json img145.png img146.json img146.png img147.json img147.png img148.json img148.png img149.json img149.png img15.json img15.png img150.json img150.png img151.json img151.png img152.json img152.png img153.json img153.png img154.json img154.png img155.json img155.png img156.json img156.png img157.json img157.png img158.json img158.png img159.json img159.png img16.json img16.png img160.json img160.png img161.json img161.png img162.json img162.png img163.json img163.png img164.json img164.png img165.json img165.png img166.json img166.png img167.json img167.png img168.json img168.png img169.json img169.png img17.json img17.png img170.json img170.png img171.json img171.png img172.json img172.png img173.json img173.png img174.json img174.png img175.json img175.png img176.json img176.png img177.json img177.png img178.json img178.png img179.json img179.png img18.json img18.png img180.json img180.png img181.json img181.png img182.json img182.png img183.json img183.png img184.json img184.png img185.json img185.png img186.json img186.png img187.json img187.png img188.json img188.png img189.json img189.png img19.json img19.png img190.json img190.png img191.json img191.png img192.json img192.png img193.json img193.png img194.json img194.png img195.json img195.png img196.json img196.png img197.json img197.png img198.json img198.png img199.json img199.png img2.json img2.png img20.json img20.png img200.json img200.png img21.json img21.png img22.json img22.png img23.json img23.png img24.json img24.png img25.json img25.png img26.json img26.png img27.json img27.png img28.json img28.png img29.json img29.png img3.json img3.png img30.json img30.png img31.json img31.png img32.json img32.png img33.json img33.png img34.json img34.png img35.json img35.png img36.json img36.png img37.json img37.png img38.json img38.png img39.json img39.png img4.json img4.png img40.json img40.png img41.json img41.png img42.json img42.png img43.json img43.png img44.json img44.png img45.json img45.png img46.json img46.png img47.json img47.png img48.json img48.png img49.json img49.png img5.json img5.png img50.json img50.png img51.json img51.png img52.json img52.png img53.json img53.png img54.json img54.png img55.json img55.png img56.json img56.png img57.json img57.png img58.json img58.png img59.json img59.png img6.json img6.png img60.json img60.png img61.json img61.png img62.json img62.png img63.json img63.png img64.json img64.png img65.json img65.png img66.json img66.png img67.json img67.png img68.json img68.png img69.json img69.png img7.json img7.png img70.json img70.png img71.json img71.png img72.json img72.png img73.json img73.png img74.json img74.png img75.json img75.png img76.json img76.png img77.json img77.png img78.json img78.png img79.json img79.png img8.json img8.png img80.json img80.png img81.json img81.png img82.json img82.png img83.json img83.png img84.json img84.png img85.json img85.png img86.json img86.png img87.json img87.png img88.json img88.png img89.json img89.png img9.json img9.png img90.json img90.png img91.json img91.png img92.json img92.png img93.json img93.png img94.json img94.png img95.json img95.png img96.json img96.png img97.json img97.png img98.json img98.png img99.json img99.png
In this section, we are going to see to build a model to perform Telugu character recognition and segmentation using Detectron2.
since we are following Common Objects in Context(COCO) dataset format, we need to register the train and test data as COCO instances. Here is the code:
We need the metadata of the training set and the dataset_dicts i.e., internal format os annotations of the train images.
Let’s see some of the training samples:
we are using the COCO pre-trained R50-FPN Mask R-CNN model from the Model Zoo. The next step is to configure the model using the configuration file, loading weights and setting a threshold value in this case 0.5
Here we are using previously COCO registered data i.e., train and test data, number of workers as 4, a path to load the model weights and images per batch as 2, the base learning rate as 0.001, and maximum iterations as 200 and number of classes as 6.
Here you can see the details of the training data:
Here values such as total loss, classification loss, and different metrics are depicted as graphs and they are shown using tensorboard.dev. Here is the link:
tensorboard.dev
TheCOCOEvaluator is used to evaluate the test dataset and the evaluation results are save in the ‘output’ directory. The inference_on_dataset function also provides accurate speed benchmarks for the given model and dataset.
Here is the output:
Even though the Mean Average Precision(AP) is not greater than 0.81%. Considering only 200 images for training data resulting in almost accurate predictions is a better sign and quite promising.
Here are the few unseen samples were given to the model and the results are :
You can use this method to implement your own object recognition and segmentation system using Detectron2.
|
[
{
"code": null,
"e": 191,
"s": 171,
"text": "What is Detectron2?"
},
{
"code": null,
"e": 205,
"s": 191,
"text": "Project Setup"
},
{
"code": null,
"e": 221,
"s": 205,
"text": "Build the Model"
},
{
"code": null,
"e": 245,
"s": 221,
"text": "Training and Evaluation"
},
{
"code": null,
"e": 253,
"s": 245,
"text": "Results"
},
{
"code": null,
"e": 263,
"s": 253,
"text": "Resources"
},
{
"code": null,
"e": 541,
"s": 263,
"text": "Detectron2 is an opensource object recognition and segmentation software system that implements state of the art algorithms as part of Facebook AI Research(FAIR). It is a ground-up rewrite in PyTorch to its previous version Detectron, and it originates from MaskRCNN-Benchmark."
},
{
"code": null,
"e": 733,
"s": 541,
"text": "You can see the details of Detectron2 along with the benchmark comparisons, different applications, customizations, and brief up on nuts and bolts of its working nature from PyTorch DevCon19."
},
{
"code": null,
"e": 935,
"s": 733,
"text": "The Detectron also provides a large collection of baselines trained with Detectron2 and you can access the code from Model Zoo to start with. Use this notebook provided by FAIR to play with Detectron2."
},
{
"code": null,
"e": 961,
"s": 935,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 1218,
"s": 961,
"text": "We are going to develop a character recognition and segmentation for “Telugu Characters”. To build this project we need the data suitable for the mentioned machine learning task. As there is not sufficient data available we need to collect the custom data."
},
{
"code": null,
"e": 1445,
"s": 1218,
"text": "Use the article on “How to Prepare a Custom Dataset for Character Recognition and Segmentation?” to create your own custom data which includes tools and programs to collect data and preprocess and building annotations of data."
},
{
"code": null,
"e": 1468,
"s": 1445,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1652,
"s": 1468,
"text": "Here you can see the project structure consisting of the files and directories such as test_data and train_data consists of images and annotations for training and testing the models."
},
{
"code": null,
"e": 10192,
"s": 1652,
"text": "| Detectron2_Telugu_Characters.ipynb| label2coco.py| resize.py| test.json| train.json| Viewer.ipynb|+---results| res1.PNG| res2.PNG| res3.PNG| res4.PNG| res5.PNG| res6.PNG| res7.PNG|+---test_data| img1.json| img1.png| img10.json| img10.png| img11.json| img11.png| img12.json| img12.png| img13.json| img13.png| img14.json| img14.png| img15.json| img15.png| img16.json| img16.png| img17.json| img17.png| img18.json| img18.png| img19.json| img19.png| img2.json| img2.png| img20.json| img20.png| img3.json| img3.png| img4.json| img4.png| img5.json| img5.png| img6.json| img6.png| img7.json| img7.png| img8.json| img8.png| img9.json| img9.png|+---test_images| 81XtS7O3nUL._SL1500_.jpg| alpha1.jpg| download.jfif| images (1).jfif| images (2).jfif| images (2).png| images (3).jfif| images (3).png| images (4).jfif| images (4).png| images (5).jfif| images (5).png| images (6).jfif| images (7).jfif| images.jfif| images.png| test_1.jpg| x1080.jfif|\\---train_data img1.json img1.png img10.json img10.png img100.json img100.png img101.json img101.png img102.json img102.png img103.json img103.png img104.json img104.png img105.json img105.png img106.json img106.png img107.json img107.png img108.json img108.png img109.json img109.png img11.json img11.png img110.json img110.png img111.json img111.png img112.json img112.png img113.json img113.png img114.json img114.png img115.json img115.png img116.json img116.png img117.json img117.png img118.json img118.png img119.json img119.png img12.json img12.png img120.json img120.png img121.json img121.png img122.json img122.png img123.json img123.png img124.json img124.png img125.json img125.png img126.json img126.png img127.json img127.png img128.json img128.png img129.json img129.png img13.json img13.png img130.json img130.png img131.json img131.png img132.json img132.png img133.json img133.png img134.json img134.png img135.json img135.png img136.json img136.png img137.json img137.png img138.json img138.png img139.json img139.png img14.json img14.png img140.json img140.png img141.json img141.png img142.json img142.png img143.json img143.png img144.json img144.png img145.json img145.png img146.json img146.png img147.json img147.png img148.json img148.png img149.json img149.png img15.json img15.png img150.json img150.png img151.json img151.png img152.json img152.png img153.json img153.png img154.json img154.png img155.json img155.png img156.json img156.png img157.json img157.png img158.json img158.png img159.json img159.png img16.json img16.png img160.json img160.png img161.json img161.png img162.json img162.png img163.json img163.png img164.json img164.png img165.json img165.png img166.json img166.png img167.json img167.png img168.json img168.png img169.json img169.png img17.json img17.png img170.json img170.png img171.json img171.png img172.json img172.png img173.json img173.png img174.json img174.png img175.json img175.png img176.json img176.png img177.json img177.png img178.json img178.png img179.json img179.png img18.json img18.png img180.json img180.png img181.json img181.png img182.json img182.png img183.json img183.png img184.json img184.png img185.json img185.png img186.json img186.png img187.json img187.png img188.json img188.png img189.json img189.png img19.json img19.png img190.json img190.png img191.json img191.png img192.json img192.png img193.json img193.png img194.json img194.png img195.json img195.png img196.json img196.png img197.json img197.png img198.json img198.png img199.json img199.png img2.json img2.png img20.json img20.png img200.json img200.png img21.json img21.png img22.json img22.png img23.json img23.png img24.json img24.png img25.json img25.png img26.json img26.png img27.json img27.png img28.json img28.png img29.json img29.png img3.json img3.png img30.json img30.png img31.json img31.png img32.json img32.png img33.json img33.png img34.json img34.png img35.json img35.png img36.json img36.png img37.json img37.png img38.json img38.png img39.json img39.png img4.json img4.png img40.json img40.png img41.json img41.png img42.json img42.png img43.json img43.png img44.json img44.png img45.json img45.png img46.json img46.png img47.json img47.png img48.json img48.png img49.json img49.png img5.json img5.png img50.json img50.png img51.json img51.png img52.json img52.png img53.json img53.png img54.json img54.png img55.json img55.png img56.json img56.png img57.json img57.png img58.json img58.png img59.json img59.png img6.json img6.png img60.json img60.png img61.json img61.png img62.json img62.png img63.json img63.png img64.json img64.png img65.json img65.png img66.json img66.png img67.json img67.png img68.json img68.png img69.json img69.png img7.json img7.png img70.json img70.png img71.json img71.png img72.json img72.png img73.json img73.png img74.json img74.png img75.json img75.png img76.json img76.png img77.json img77.png img78.json img78.png img79.json img79.png img8.json img8.png img80.json img80.png img81.json img81.png img82.json img82.png img83.json img83.png img84.json img84.png img85.json img85.png img86.json img86.png img87.json img87.png img88.json img88.png img89.json img89.png img9.json img9.png img90.json img90.png img91.json img91.png img92.json img92.png img93.json img93.png img94.json img94.png img95.json img95.png img96.json img96.png img97.json img97.png img98.json img98.png img99.json img99.png"
},
{
"code": null,
"e": 10321,
"s": 10192,
"text": "In this section, we are going to see to build a model to perform Telugu character recognition and segmentation using Detectron2."
},
{
"code": null,
"e": 10473,
"s": 10321,
"text": "since we are following Common Objects in Context(COCO) dataset format, we need to register the train and test data as COCO instances. Here is the code:"
},
{
"code": null,
"e": 10594,
"s": 10473,
"text": "We need the metadata of the training set and the dataset_dicts i.e., internal format os annotations of the train images."
},
{
"code": null,
"e": 10634,
"s": 10594,
"text": "Let’s see some of the training samples:"
},
{
"code": null,
"e": 10846,
"s": 10634,
"text": "we are using the COCO pre-trained R50-FPN Mask R-CNN model from the Model Zoo. The next step is to configure the model using the configuration file, loading weights and setting a threshold value in this case 0.5"
},
{
"code": null,
"e": 11098,
"s": 10846,
"text": "Here we are using previously COCO registered data i.e., train and test data, number of workers as 4, a path to load the model weights and images per batch as 2, the base learning rate as 0.001, and maximum iterations as 200 and number of classes as 6."
},
{
"code": null,
"e": 11149,
"s": 11098,
"text": "Here you can see the details of the training data:"
},
{
"code": null,
"e": 11307,
"s": 11149,
"text": "Here values such as total loss, classification loss, and different metrics are depicted as graphs and they are shown using tensorboard.dev. Here is the link:"
},
{
"code": null,
"e": 11323,
"s": 11307,
"text": "tensorboard.dev"
},
{
"code": null,
"e": 11547,
"s": 11323,
"text": "TheCOCOEvaluator is used to evaluate the test dataset and the evaluation results are save in the ‘output’ directory. The inference_on_dataset function also provides accurate speed benchmarks for the given model and dataset."
},
{
"code": null,
"e": 11567,
"s": 11547,
"text": "Here is the output:"
},
{
"code": null,
"e": 11762,
"s": 11567,
"text": "Even though the Mean Average Precision(AP) is not greater than 0.81%. Considering only 200 images for training data resulting in almost accurate predictions is a better sign and quite promising."
},
{
"code": null,
"e": 11840,
"s": 11762,
"text": "Here are the few unseen samples were given to the model and the results are :"
}
] |
Number of n digit stepping numbers - GeeksforGeeks
|
22 Apr, 2021
Given n, find count of n digit Stepping numbers. A number is called stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not.
Examples :
Input : 2
Output : 17
Explanation: The numbers are 10, 12, 21,
23, 32, 34, 43, 45, 54, 56, 65, 67, 76,
78, 87, 89, 98.
Input : 1
Output : 10
Explanation: the numbers are 0, 1, 2, 3,
4, 5, 6, 7, 8, 9.
A naive approach is to run a loop for all n digit numbers and check for every number if it is Stepping.
An efficient approach is to use dynamic programming.
In dp[i][j], i denotes number of
digits and j denotes last digit.
// If there is only one digit
if (i == 1)
dp(i, j) = 1;
// If last digit is 0.
if (j == 0)
dp(i, j) = dp(i-1, j+1)
// If last digit is 9
else if (j == 9)
dp(i, j) = dp(i-1, j-1)
// If last digit is neither 0
// nor 9.
else
dp(i, j) = dp(i-1, j-1) +
dp(i-1, j+1)
Result is ∑dp(n, j) where j varies
from 1 to 9.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to calculate the number of// n digit stepping numbers.#include <bits/stdc++.h>using namespace std; // function that calculates the answerlong long answer(int n){ // dp[i][j] stores count of i digit // stepping numbers ending with digit // j. int dp[n + 1][10]; // if n is 1 then answer will be 10. if (n == 1) return 10; // Initialize values for count of // digits equal to 1. for (int j = 0; j <= 9; j++) dp[1][j] = 1; // Compute values for count of digits // more than 1. for (int i = 2; i <= n; i++) { for (int j = 0; j <= 9; j++) { // If ending digit is 0 if (j == 0) dp[i][j] = dp[i - 1][j + 1]; // If ending digit is 9 else if (j == 9) dp[i][j] = dp[i - 1][j - 1]; // For other digits. else dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1]; } } // stores the final answer long long sum = 0; for (int j = 1; j <= 9; j++) sum += dp[n][j]; return sum;} // driver program to test the above functionint main(){ int n = 2; cout << answer(n); return 0;}
// Java program to calculate the number of// n digit stepping numbers. class GFG { // function that calculates the answer static long answer(int n) { // dp[i][j] stores count of i // digit stepping numbers ending // with digit j. int dp[][] = new int[n+1][10]; // if n is 1 then answer will be 10. if (n == 1) return 10; // Initialize values for count of // digits equal to 1. for (int j = 0; j <= 9; j++) dp[1][j] = 1; // Compute values for count of // digits more than 1. for (int i = 2; i <= n; i++) { for (int j = 0; j <= 9; j++) { // If ending digit is 0 if (j == 0) dp[i][j] = dp[i - 1][j + 1]; // If ending digit is 9 else if (j == 9) dp[i][j] = dp[i - 1][j - 1]; // For other digits. else dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1]; } } // stores the final answer long sum = 0; for (int j = 1; j <= 9; j++) sum += dp[n][j]; return sum; } // driver program to test the above function public static void main(String args[]) { int n = 2; System.out.println(answer(n)); }} /*This code is contributed by Nikita tiwari.*/
# Python3 program to calculate# the number of n digit# stepping numbers. # function that calculates# the answerdef answer(n): # dp[i][j] stores count of # i digit stepping numbers # ending with digit j. dp = [[0 for x in range(10)] for y in range(n + 1)]; # if n is 1 then answer # will be 10. if (n == 1): return 10; for j in range(10): dp[1][j] = 1; # Compute values for count # of digits more than 1. for i in range(2, n + 1): for j in range(10): # If ending digit is 0 if (j == 0): dp[i][j] = dp[i - 1][j + 1]; # If ending digit is 9 elif (j == 9): dp[i][j] = dp[i - 1][j - 1]; # For other digits. else: dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]); # stores the final answer sum = 0; for j in range(1, 10): sum = sum + dp[n][j]; return sum; # Driver Coden = 2;print(answer(n)); # This code is contributed# by mits
// C# program to calculate the number of// n digit stepping numbers.using System; class GFG { // function that calculates the answer static long answer(int n) { // dp[i][j] stores count of i // digit stepping numbers ending // with digit j. int [,]dp = new int[n+1,10]; // if n is 1 then answer will be 10. if (n == 1) return 10; // Initialize values for count of // digits equal to 1. for (int j = 0; j <= 9; j++) dp[1,j] = 1; // Compute values for count of // digits more than 1. for (int i = 2; i <= n; i++) { for (int j = 0; j <= 9; j++) { // If ending digit is 0 if (j == 0) dp[i,j] = dp[i - 1,j + 1]; // If ending digit is 9 else if (j == 9) dp[i,j] = dp[i - 1,j - 1]; // For other digits. else dp[i,j] = dp[i - 1,j - 1] + dp[i - 1,j + 1]; } } // stores the final answer long sum = 0; for (int j = 1; j <= 9; j++) sum += dp[n,j]; return sum; } // driver program to test the above function public static void Main() { int n = 2; Console.WriteLine(answer(n)); }} /*This code is contributed by vt_m.*/
<?php// PHP program to calculate// the number of n digit// stepping numbers. // function that calculates// the answerfunction answer($n){ // dp[i][j] stores count of // i digit stepping numbers // ending with digit j. // if n is 1 then answer // will be 10. if ($n == 1) return 10; for ( $j = 0; $j <= 9; $j++) $dp[1][$j] = 1; // Compute values for count // of digits more than 1. for ($i = 2; $i <= $n; $i++) { for ($j = 0; $j <= 9; $j++) { // If ending digit is 0 if ($j == 0) $dp[$i][$j] = $dp[$i - 1][$j + 1]; // If ending digit is 9 else if ($j == 9) $dp[$i][$j] = $dp[$i - 1][$j - 1]; // For other digits. else $dp[$i][$j] = $dp[$i - 1][$j - 1] + $dp[$i - 1][$j + 1]; } } // stores the final answer $sum = 0; for ($j = 1; $j <= 9; $j++) $sum += $dp[$n][$j]; return $sum;} // Driver Code$n = 2;echo answer($n); // This code is contributed by aj_36?>
<script> // JavaScript program to calculate the number of// n digit stepping numbers. // Function that calculates the answerfunction answer(n){ // dp[i][j] stores count of i // digit stepping numbers ending // with digit j. let dp = new Array(n + 1); // Loop to create 2D array using 1D array for(var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } // If n is 1 then answer will be 10. if (n == 1) return 10; // Initialize values for count of // digits equal to 1. for(let j = 0; j <= 9; j++) dp[1][j] = 1; // Compute values for count of // digits more than 1. for(let i = 2; i <= n; i++) { for(let j = 0; j <= 9; j++) { // If ending digit is 0 if (j == 0) dp[i][j] = dp[i - 1][j + 1]; // If ending digit is 9 else if (j == 9) dp[i][j] = dp[i - 1][j - 1]; // For other digits. else dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1]; } } // Stores the final answer let sum = 0; for(let j = 1; j <= 9; j++) sum += dp[n][j]; return sum;} // Driver Codelet n = 2; document.write(answer(n)); // This code is contributed by code_hunt </script>
Output :
17
Time Complexity: O(n) Auxiliary Space: O(n)Number of n digit stepping numbers | Space optimized solution
jit_t
Mithun Kumar
code_hunt
number-digits
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Coin Change | DP-7
Longest Palindromic Substring | Set 1
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays
|
[
{
"code": null,
"e": 24939,
"s": 24911,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 25123,
"s": 24939,
"text": "Given n, find count of n digit Stepping numbers. A number is called stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not."
},
{
"code": null,
"e": 25136,
"s": 25123,
"text": "Examples : "
},
{
"code": null,
"e": 25341,
"s": 25136,
"text": "Input : 2 \nOutput : 17\nExplanation: The numbers are 10, 12, 21, \n23, 32, 34, 43, 45, 54, 56, 65, 67, 76, \n78, 87, 89, 98.\n\nInput : 1\nOutput : 10\nExplanation: the numbers are 0, 1, 2, 3, \n4, 5, 6, 7, 8, 9."
},
{
"code": null,
"e": 25445,
"s": 25341,
"text": "A naive approach is to run a loop for all n digit numbers and check for every number if it is Stepping."
},
{
"code": null,
"e": 25500,
"s": 25445,
"text": "An efficient approach is to use dynamic programming. "
},
{
"code": null,
"e": 25912,
"s": 25500,
"text": "In dp[i][j], i denotes number of\ndigits and j denotes last digit.\n\n// If there is only one digit\nif (i == 1)\n dp(i, j) = 1;\n\n// If last digit is 0.\nif (j == 0) \n dp(i, j) = dp(i-1, j+1)\n\n// If last digit is 9\nelse if (j == 9) \n dp(i, j) = dp(i-1, j-1)\n\n// If last digit is neither 0\n// nor 9.\nelse \n dp(i, j) = dp(i-1, j-1) + \n dp(i-1, j+1)\n\nResult is ∑dp(n, j) where j varies\nfrom 1 to 9. "
},
{
"code": null,
"e": 25916,
"s": 25912,
"text": "C++"
},
{
"code": null,
"e": 25921,
"s": 25916,
"text": "Java"
},
{
"code": null,
"e": 25929,
"s": 25921,
"text": "Python3"
},
{
"code": null,
"e": 25932,
"s": 25929,
"text": "C#"
},
{
"code": null,
"e": 25936,
"s": 25932,
"text": "PHP"
},
{
"code": null,
"e": 25947,
"s": 25936,
"text": "Javascript"
},
{
"code": "// CPP program to calculate the number of// n digit stepping numbers.#include <bits/stdc++.h>using namespace std; // function that calculates the answerlong long answer(int n){ // dp[i][j] stores count of i digit // stepping numbers ending with digit // j. int dp[n + 1][10]; // if n is 1 then answer will be 10. if (n == 1) return 10; // Initialize values for count of // digits equal to 1. for (int j = 0; j <= 9; j++) dp[1][j] = 1; // Compute values for count of digits // more than 1. for (int i = 2; i <= n; i++) { for (int j = 0; j <= 9; j++) { // If ending digit is 0 if (j == 0) dp[i][j] = dp[i - 1][j + 1]; // If ending digit is 9 else if (j == 9) dp[i][j] = dp[i - 1][j - 1]; // For other digits. else dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1]; } } // stores the final answer long long sum = 0; for (int j = 1; j <= 9; j++) sum += dp[n][j]; return sum;} // driver program to test the above functionint main(){ int n = 2; cout << answer(n); return 0;}",
"e": 27152,
"s": 25947,
"text": null
},
{
"code": "// Java program to calculate the number of// n digit stepping numbers. class GFG { // function that calculates the answer static long answer(int n) { // dp[i][j] stores count of i // digit stepping numbers ending // with digit j. int dp[][] = new int[n+1][10]; // if n is 1 then answer will be 10. if (n == 1) return 10; // Initialize values for count of // digits equal to 1. for (int j = 0; j <= 9; j++) dp[1][j] = 1; // Compute values for count of // digits more than 1. for (int i = 2; i <= n; i++) { for (int j = 0; j <= 9; j++) { // If ending digit is 0 if (j == 0) dp[i][j] = dp[i - 1][j + 1]; // If ending digit is 9 else if (j == 9) dp[i][j] = dp[i - 1][j - 1]; // For other digits. else dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1]; } } // stores the final answer long sum = 0; for (int j = 1; j <= 9; j++) sum += dp[n][j]; return sum; } // driver program to test the above function public static void main(String args[]) { int n = 2; System.out.println(answer(n)); }} /*This code is contributed by Nikita tiwari.*/",
"e": 28626,
"s": 27152,
"text": null
},
{
"code": "# Python3 program to calculate# the number of n digit# stepping numbers. # function that calculates# the answerdef answer(n): # dp[i][j] stores count of # i digit stepping numbers # ending with digit j. dp = [[0 for x in range(10)] for y in range(n + 1)]; # if n is 1 then answer # will be 10. if (n == 1): return 10; for j in range(10): dp[1][j] = 1; # Compute values for count # of digits more than 1. for i in range(2, n + 1): for j in range(10): # If ending digit is 0 if (j == 0): dp[i][j] = dp[i - 1][j + 1]; # If ending digit is 9 elif (j == 9): dp[i][j] = dp[i - 1][j - 1]; # For other digits. else: dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]); # stores the final answer sum = 0; for j in range(1, 10): sum = sum + dp[n][j]; return sum; # Driver Coden = 2;print(answer(n)); # This code is contributed# by mits",
"e": 29743,
"s": 28626,
"text": null
},
{
"code": "// C# program to calculate the number of// n digit stepping numbers.using System; class GFG { // function that calculates the answer static long answer(int n) { // dp[i][j] stores count of i // digit stepping numbers ending // with digit j. int [,]dp = new int[n+1,10]; // if n is 1 then answer will be 10. if (n == 1) return 10; // Initialize values for count of // digits equal to 1. for (int j = 0; j <= 9; j++) dp[1,j] = 1; // Compute values for count of // digits more than 1. for (int i = 2; i <= n; i++) { for (int j = 0; j <= 9; j++) { // If ending digit is 0 if (j == 0) dp[i,j] = dp[i - 1,j + 1]; // If ending digit is 9 else if (j == 9) dp[i,j] = dp[i - 1,j - 1]; // For other digits. else dp[i,j] = dp[i - 1,j - 1] + dp[i - 1,j + 1]; } } // stores the final answer long sum = 0; for (int j = 1; j <= 9; j++) sum += dp[n,j]; return sum; } // driver program to test the above function public static void Main() { int n = 2; Console.WriteLine(answer(n)); }} /*This code is contributed by vt_m.*/",
"e": 31217,
"s": 29743,
"text": null
},
{
"code": "<?php// PHP program to calculate// the number of n digit// stepping numbers. // function that calculates// the answerfunction answer($n){ // dp[i][j] stores count of // i digit stepping numbers // ending with digit j. // if n is 1 then answer // will be 10. if ($n == 1) return 10; for ( $j = 0; $j <= 9; $j++) $dp[1][$j] = 1; // Compute values for count // of digits more than 1. for ($i = 2; $i <= $n; $i++) { for ($j = 0; $j <= 9; $j++) { // If ending digit is 0 if ($j == 0) $dp[$i][$j] = $dp[$i - 1][$j + 1]; // If ending digit is 9 else if ($j == 9) $dp[$i][$j] = $dp[$i - 1][$j - 1]; // For other digits. else $dp[$i][$j] = $dp[$i - 1][$j - 1] + $dp[$i - 1][$j + 1]; } } // stores the final answer $sum = 0; for ($j = 1; $j <= 9; $j++) $sum += $dp[$n][$j]; return $sum;} // Driver Code$n = 2;echo answer($n); // This code is contributed by aj_36?>",
"e": 32309,
"s": 31217,
"text": null
},
{
"code": "<script> // JavaScript program to calculate the number of// n digit stepping numbers. // Function that calculates the answerfunction answer(n){ // dp[i][j] stores count of i // digit stepping numbers ending // with digit j. let dp = new Array(n + 1); // Loop to create 2D array using 1D array for(var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } // If n is 1 then answer will be 10. if (n == 1) return 10; // Initialize values for count of // digits equal to 1. for(let j = 0; j <= 9; j++) dp[1][j] = 1; // Compute values for count of // digits more than 1. for(let i = 2; i <= n; i++) { for(let j = 0; j <= 9; j++) { // If ending digit is 0 if (j == 0) dp[i][j] = dp[i - 1][j + 1]; // If ending digit is 9 else if (j == 9) dp[i][j] = dp[i - 1][j - 1]; // For other digits. else dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1]; } } // Stores the final answer let sum = 0; for(let j = 1; j <= 9; j++) sum += dp[n][j]; return sum;} // Driver Codelet n = 2; document.write(answer(n)); // This code is contributed by code_hunt </script>",
"e": 33650,
"s": 32309,
"text": null
},
{
"code": null,
"e": 33660,
"s": 33650,
"text": "Output : "
},
{
"code": null,
"e": 33663,
"s": 33660,
"text": "17"
},
{
"code": null,
"e": 33769,
"s": 33663,
"text": "Time Complexity: O(n) Auxiliary Space: O(n)Number of n digit stepping numbers | Space optimized solution "
},
{
"code": null,
"e": 33775,
"s": 33769,
"text": "jit_t"
},
{
"code": null,
"e": 33788,
"s": 33775,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 33798,
"s": 33788,
"text": "code_hunt"
},
{
"code": null,
"e": 33812,
"s": 33798,
"text": "number-digits"
},
{
"code": null,
"e": 33832,
"s": 33812,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33845,
"s": 33832,
"text": "Mathematical"
},
{
"code": null,
"e": 33865,
"s": 33845,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33878,
"s": 33865,
"text": "Mathematical"
},
{
"code": null,
"e": 33976,
"s": 33878,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33985,
"s": 33976,
"text": "Comments"
},
{
"code": null,
"e": 33998,
"s": 33985,
"text": "Old Comments"
},
{
"code": null,
"e": 34029,
"s": 33998,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 34062,
"s": 34029,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 34089,
"s": 34062,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 34108,
"s": 34089,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 34146,
"s": 34108,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 34206,
"s": 34146,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34221,
"s": 34206,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34264,
"s": 34221,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 34283,
"s": 34264,
"text": "Coin Change | DP-7"
}
] |
How to Search and Download Data using Kaggle API? | by Satyam Kumar | Towards Data Science
|
Kaggle is the world’s largest data science community with powerful tools, datasets, and other resources to help you achieve your data science goals. Kaggle contains tons of freely available datasets used for educational purposes. It also hosts competitions and has freely available notebook to explore and run data science and machine learning models.
To use Kaggle resources and participate in Kaggle competitions you need to log in to the Kaggle website and search correspondingly. To download a dataset from Kaggle one needs to search for the dataset and download it manually and move to the desired folder to further explore.
All interactions with Kaggle can be done using a Kaggle API via the command-line tool (CLI) implemented in Python.
To install the Kaggle library using pip:
pip install kaggle
To use Kaggle’s publicly available API to interact with Kaggle resources, firstly you need to authenticate using an API token. Follow the steps to download a new authentication token onto your machine to complete the authentication:
Click on your profile picture and click on Account from the drop-down menu.
Scroll down to the API section.
Click on the ‘Create New API Token’ button to download a fresh token as a JSON file having a username and API key.
Copy the JSON file to ~/.kaggle/ the directory. In the windows system, go to the root directory, then to .kaggle folder, and copy the downloaded file to this directory.
If you are using the Kaggle API directly, where you keep the token doesn’t matter, so long as you can provide your credentials at runtime.
You can interact using Kaggle API to use its resources without login into its website now and then, below is the list of interactions available using API via command line statement:
Searching for the dataset
Download the dataset
Creating and maintaining the dataset
Searching for published notebook
Download a published notebook
Creating and Running a notebook
Interacting with competitions
Submitting to a competition
Using CLI arguments you can search for any keyword to find the corresponding datasets. CLI statement to get the list of datasets using search statement:
kaggle datasets list -s [KEYWORD]
After you have searched for the appropriate dataset using CLI arguments for searching, this API provides an advantage to download any datasets from Kaggle to your local machine. Commands to download the files associated with the datasets using CLI:
kaggle datasets download -d [DATASET]
Kaggle API can be used to upload new datasets and versions of datasets using CLI arguments. This can ease the sharing of datasets and projects on Kaggle.
To create a new dataset follow the below steps:
Assemble the dataset files in a folder to upload on Kaggle.
To generate metadata, run: kaggle datasets init -p /path/to/dataset
Add the metadata to the generated file: datapackage.json
To finally create the dataset run: kaggle datasets create -p /path/to/dataset
To upload a new version of the existing dataset follows the below steps:
To generate metadata, run: kaggle datasets init -p /path/to/dataset
Make sure the id field in the metadata file datapackage.json points to your dataset.
To finally create the dataset run:kaggle datasets version -p /path/to/dataset -m "MESSAGE"
Using Kaggle API you can search using a keyword to find corresponding published notebooks. It enables to search for published Notebooks and their metadata as well as workflows for creating and running Notebooks.
CLI statement to get the list of published notebooks using search keyword:
kaggle kernels list -s [KEYWORD]
Kaggle API provides the advantage to download any published notebooks from Kaggle to your local machine. Commands to download the files associated with the notebooks using CLI:
kaggle kernels pull -k [KERNEL] -p /path/to/download -m
Kaggle API can be used to upload new notebooks and maintain versions of notebooks using CLI arguments. This can ease sharing notebooks and projects on Kaggle.
To create new notebooks follow the below steps:
Assemble the code files (notebooks) in a folder to upload on Kaggle.
To generate metadata, run: kaggle kernels init -p /path/to/kernel
Add the metadata to the generated file: kernel-metadata.json
To finally create the dataset run: kaggle kernels push -p /path/to/kernel
To upload a new version of the existing dataset follows the below steps:
Download the last version of your notebook and corresponding metadata to your local machine: kaggle kernels pull -k [KERNEL] -p /path/to/download -m
Make sure the id field in the metadata file kernel-metadata.json points to your notebook.
To finally push the new version of the notebook run:kaggle kernels version -p /path/to/kernel
Kaggle API tools provide an easy way to interact with the competitions hosted on Kaggle. To accept the rules for any competition, you need to login to the competition site and accept the rules to download the dataset and make the submission. You need to visit the Kaggle website and accept the rules there, as it is not possible through the API.
Commands to interact with the competition hosted on Kaggle:
List of all ongoing competitions: kaggle competitions list
Download the files associated with a competition: kaggle competitions download -c [COMPETITION]
Submitting to any competition is only possible after you have accepted the submission rules by visiting the Kaggle competition website page.
CLI arguments to submit to competition and get yourself scored:
kaggle competitions submit -c [COMPETITION NAME] -f [FILE PATH]
To list all the previous submission to a competition run:
kaggle competitions submissions -c [COMPETITION NAME]
In this article, we have discussed how to use Kaggle API to use Kaggle resources via CLI arguments. Using CLI commands we can interact with datasets, interact with notebooks, or interact with any competitions.
To explore additional CLI arguments, you can always append -h after any call to see the help menu for that command.
[1] Kaggle API Documentation: https://www.kaggle.com/docs/api
[2] Kaggle API GitHub Repo: https://github.com/Kaggle/kaggle-api
Thank You for Reading
|
[
{
"code": null,
"e": 523,
"s": 171,
"text": "Kaggle is the world’s largest data science community with powerful tools, datasets, and other resources to help you achieve your data science goals. Kaggle contains tons of freely available datasets used for educational purposes. It also hosts competitions and has freely available notebook to explore and run data science and machine learning models."
},
{
"code": null,
"e": 801,
"s": 523,
"text": "To use Kaggle resources and participate in Kaggle competitions you need to log in to the Kaggle website and search correspondingly. To download a dataset from Kaggle one needs to search for the dataset and download it manually and move to the desired folder to further explore."
},
{
"code": null,
"e": 916,
"s": 801,
"text": "All interactions with Kaggle can be done using a Kaggle API via the command-line tool (CLI) implemented in Python."
},
{
"code": null,
"e": 957,
"s": 916,
"text": "To install the Kaggle library using pip:"
},
{
"code": null,
"e": 976,
"s": 957,
"text": "pip install kaggle"
},
{
"code": null,
"e": 1209,
"s": 976,
"text": "To use Kaggle’s publicly available API to interact with Kaggle resources, firstly you need to authenticate using an API token. Follow the steps to download a new authentication token onto your machine to complete the authentication:"
},
{
"code": null,
"e": 1285,
"s": 1209,
"text": "Click on your profile picture and click on Account from the drop-down menu."
},
{
"code": null,
"e": 1317,
"s": 1285,
"text": "Scroll down to the API section."
},
{
"code": null,
"e": 1432,
"s": 1317,
"text": "Click on the ‘Create New API Token’ button to download a fresh token as a JSON file having a username and API key."
},
{
"code": null,
"e": 1601,
"s": 1432,
"text": "Copy the JSON file to ~/.kaggle/ the directory. In the windows system, go to the root directory, then to .kaggle folder, and copy the downloaded file to this directory."
},
{
"code": null,
"e": 1740,
"s": 1601,
"text": "If you are using the Kaggle API directly, where you keep the token doesn’t matter, so long as you can provide your credentials at runtime."
},
{
"code": null,
"e": 1922,
"s": 1740,
"text": "You can interact using Kaggle API to use its resources without login into its website now and then, below is the list of interactions available using API via command line statement:"
},
{
"code": null,
"e": 1948,
"s": 1922,
"text": "Searching for the dataset"
},
{
"code": null,
"e": 1969,
"s": 1948,
"text": "Download the dataset"
},
{
"code": null,
"e": 2006,
"s": 1969,
"text": "Creating and maintaining the dataset"
},
{
"code": null,
"e": 2039,
"s": 2006,
"text": "Searching for published notebook"
},
{
"code": null,
"e": 2069,
"s": 2039,
"text": "Download a published notebook"
},
{
"code": null,
"e": 2101,
"s": 2069,
"text": "Creating and Running a notebook"
},
{
"code": null,
"e": 2131,
"s": 2101,
"text": "Interacting with competitions"
},
{
"code": null,
"e": 2159,
"s": 2131,
"text": "Submitting to a competition"
},
{
"code": null,
"e": 2312,
"s": 2159,
"text": "Using CLI arguments you can search for any keyword to find the corresponding datasets. CLI statement to get the list of datasets using search statement:"
},
{
"code": null,
"e": 2346,
"s": 2312,
"text": "kaggle datasets list -s [KEYWORD]"
},
{
"code": null,
"e": 2595,
"s": 2346,
"text": "After you have searched for the appropriate dataset using CLI arguments for searching, this API provides an advantage to download any datasets from Kaggle to your local machine. Commands to download the files associated with the datasets using CLI:"
},
{
"code": null,
"e": 2633,
"s": 2595,
"text": "kaggle datasets download -d [DATASET]"
},
{
"code": null,
"e": 2787,
"s": 2633,
"text": "Kaggle API can be used to upload new datasets and versions of datasets using CLI arguments. This can ease the sharing of datasets and projects on Kaggle."
},
{
"code": null,
"e": 2835,
"s": 2787,
"text": "To create a new dataset follow the below steps:"
},
{
"code": null,
"e": 2895,
"s": 2835,
"text": "Assemble the dataset files in a folder to upload on Kaggle."
},
{
"code": null,
"e": 2963,
"s": 2895,
"text": "To generate metadata, run: kaggle datasets init -p /path/to/dataset"
},
{
"code": null,
"e": 3020,
"s": 2963,
"text": "Add the metadata to the generated file: datapackage.json"
},
{
"code": null,
"e": 3098,
"s": 3020,
"text": "To finally create the dataset run: kaggle datasets create -p /path/to/dataset"
},
{
"code": null,
"e": 3171,
"s": 3098,
"text": "To upload a new version of the existing dataset follows the below steps:"
},
{
"code": null,
"e": 3239,
"s": 3171,
"text": "To generate metadata, run: kaggle datasets init -p /path/to/dataset"
},
{
"code": null,
"e": 3324,
"s": 3239,
"text": "Make sure the id field in the metadata file datapackage.json points to your dataset."
},
{
"code": null,
"e": 3415,
"s": 3324,
"text": "To finally create the dataset run:kaggle datasets version -p /path/to/dataset -m \"MESSAGE\""
},
{
"code": null,
"e": 3627,
"s": 3415,
"text": "Using Kaggle API you can search using a keyword to find corresponding published notebooks. It enables to search for published Notebooks and their metadata as well as workflows for creating and running Notebooks."
},
{
"code": null,
"e": 3702,
"s": 3627,
"text": "CLI statement to get the list of published notebooks using search keyword:"
},
{
"code": null,
"e": 3735,
"s": 3702,
"text": "kaggle kernels list -s [KEYWORD]"
},
{
"code": null,
"e": 3912,
"s": 3735,
"text": "Kaggle API provides the advantage to download any published notebooks from Kaggle to your local machine. Commands to download the files associated with the notebooks using CLI:"
},
{
"code": null,
"e": 3968,
"s": 3912,
"text": "kaggle kernels pull -k [KERNEL] -p /path/to/download -m"
},
{
"code": null,
"e": 4127,
"s": 3968,
"text": "Kaggle API can be used to upload new notebooks and maintain versions of notebooks using CLI arguments. This can ease sharing notebooks and projects on Kaggle."
},
{
"code": null,
"e": 4175,
"s": 4127,
"text": "To create new notebooks follow the below steps:"
},
{
"code": null,
"e": 4244,
"s": 4175,
"text": "Assemble the code files (notebooks) in a folder to upload on Kaggle."
},
{
"code": null,
"e": 4310,
"s": 4244,
"text": "To generate metadata, run: kaggle kernels init -p /path/to/kernel"
},
{
"code": null,
"e": 4371,
"s": 4310,
"text": "Add the metadata to the generated file: kernel-metadata.json"
},
{
"code": null,
"e": 4445,
"s": 4371,
"text": "To finally create the dataset run: kaggle kernels push -p /path/to/kernel"
},
{
"code": null,
"e": 4518,
"s": 4445,
"text": "To upload a new version of the existing dataset follows the below steps:"
},
{
"code": null,
"e": 4667,
"s": 4518,
"text": "Download the last version of your notebook and corresponding metadata to your local machine: kaggle kernels pull -k [KERNEL] -p /path/to/download -m"
},
{
"code": null,
"e": 4757,
"s": 4667,
"text": "Make sure the id field in the metadata file kernel-metadata.json points to your notebook."
},
{
"code": null,
"e": 4851,
"s": 4757,
"text": "To finally push the new version of the notebook run:kaggle kernels version -p /path/to/kernel"
},
{
"code": null,
"e": 5197,
"s": 4851,
"text": "Kaggle API tools provide an easy way to interact with the competitions hosted on Kaggle. To accept the rules for any competition, you need to login to the competition site and accept the rules to download the dataset and make the submission. You need to visit the Kaggle website and accept the rules there, as it is not possible through the API."
},
{
"code": null,
"e": 5257,
"s": 5197,
"text": "Commands to interact with the competition hosted on Kaggle:"
},
{
"code": null,
"e": 5316,
"s": 5257,
"text": "List of all ongoing competitions: kaggle competitions list"
},
{
"code": null,
"e": 5412,
"s": 5316,
"text": "Download the files associated with a competition: kaggle competitions download -c [COMPETITION]"
},
{
"code": null,
"e": 5553,
"s": 5412,
"text": "Submitting to any competition is only possible after you have accepted the submission rules by visiting the Kaggle competition website page."
},
{
"code": null,
"e": 5617,
"s": 5553,
"text": "CLI arguments to submit to competition and get yourself scored:"
},
{
"code": null,
"e": 5681,
"s": 5617,
"text": "kaggle competitions submit -c [COMPETITION NAME] -f [FILE PATH]"
},
{
"code": null,
"e": 5739,
"s": 5681,
"text": "To list all the previous submission to a competition run:"
},
{
"code": null,
"e": 5793,
"s": 5739,
"text": "kaggle competitions submissions -c [COMPETITION NAME]"
},
{
"code": null,
"e": 6003,
"s": 5793,
"text": "In this article, we have discussed how to use Kaggle API to use Kaggle resources via CLI arguments. Using CLI commands we can interact with datasets, interact with notebooks, or interact with any competitions."
},
{
"code": null,
"e": 6119,
"s": 6003,
"text": "To explore additional CLI arguments, you can always append -h after any call to see the help menu for that command."
},
{
"code": null,
"e": 6181,
"s": 6119,
"text": "[1] Kaggle API Documentation: https://www.kaggle.com/docs/api"
},
{
"code": null,
"e": 6246,
"s": 6181,
"text": "[2] Kaggle API GitHub Repo: https://github.com/Kaggle/kaggle-api"
}
] |
Sass - Installation
|
In this chapter, we will learn the step-by-step procedure to install Ruby, which is used for executing the SASS files.
Operating System − Cross-platform
Operating System − Cross-platform
Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera
Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera
Programming Language − Ruby
Programming Language − Ruby
Step 1 − Open the link https://www.ruby-lang.org/en/downloads/, you will see a screen as shown below −
Download the Current stable version of the zip file.
Step 2 − Next, run the setup to install Ruby on the System.
Step 3 − Next, add Ruby bin folder to your PATH User Variable and System Variable to work with gem command.
Path User Variable −
Right Click the My Computer icon.
Right Click the My Computer icon.
Select Properties.
Select Properties.
Next, click the Advanced tab and click Environment Variables.
Next, click the Advanced tab and click Environment Variables.
In the Environment Variables window, double click the PATH as shown in the screenshot given below −
You will get an Edit User Variable box as shown. Add ruby bin folder path in the Variable value field as C:\Ruby\bin. If path is already set for other files, then put semicolon after that and add the Ruby folder path as shown below.
Click the OK button.
System Variable −
Click the New button.
Click the New button.
Next, the New System Variable block is displayed as shown below.
Enter RubyOpt in the Variable name field and rubygems in the Variable value field. After writing the Variable name and value, click the OK button.
Enter RubyOpt in the Variable name field and rubygems in the Variable value field. After writing the Variable name and value, click the OK button.
Step 4 − Open the command prompt in your system and enter the following line −
gem install sass
Step 5 − Next, you will see the following screen after installing SASS successfully.
The following is a simple example of SASS.
<html>
<head>
<title> Import example of sass</title>
<link rel = "stylesheet" type = "text/css" href = "style.css"/>
</head>
<body>
<h1>Simple Example</h1>
<h3>Welcome to TutorialsPoint</h3>
</body>
</html>
Now, we will create file as style.scss, which is quite similar to CSS and the only one difference is that it will be saved with .scss extension. Both, .htm and .scss files should be created inside the folder ruby. You can save your .scss file in the folder ruby\lib\sass\ (before this process, create a folder as sass in lib directory).
h1{
color: #AF80ED;
}
h3{
color: #DE5E85;
}
You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −
sass --watch C:\ruby\lib\sass\style.scss:style.css
When you run the above command, it will create the style.css file automatically. Whenever you change the SCSS file, the style.css file will be updated automatically.
The style.css file will have the following code when you run the above given command −
h1 {
color: #AF80ED;
}
h3 {
color: #DE5E85;
}
Let us carry out the following steps to see how the above given code works −
Save the above given code in hello.html file.
Save the above given code in hello.html file.
Open this HTML file in a browser.
Open this HTML file in a browser.
50 Lectures
5.5 hours
Code And Create
124 Lectures
30 hours
Juan Galvan
162 Lectures
31.5 hours
Yossef Ayman Zedan
167 Lectures
45.5 hours
Muslim Helalee
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1971,
"s": 1852,
"text": "In this chapter, we will learn the step-by-step procedure to install Ruby, which is used for executing the SASS files."
},
{
"code": null,
"e": 2005,
"s": 1971,
"text": "Operating System − Cross-platform"
},
{
"code": null,
"e": 2039,
"s": 2005,
"text": "Operating System − Cross-platform"
},
{
"code": null,
"e": 2122,
"s": 2039,
"text": "Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera"
},
{
"code": null,
"e": 2205,
"s": 2122,
"text": "Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera"
},
{
"code": null,
"e": 2233,
"s": 2205,
"text": "Programming Language − Ruby"
},
{
"code": null,
"e": 2261,
"s": 2233,
"text": "Programming Language − Ruby"
},
{
"code": null,
"e": 2364,
"s": 2261,
"text": "Step 1 − Open the link https://www.ruby-lang.org/en/downloads/, you will see a screen as shown below −"
},
{
"code": null,
"e": 2417,
"s": 2364,
"text": "Download the Current stable version of the zip file."
},
{
"code": null,
"e": 2477,
"s": 2417,
"text": "Step 2 − Next, run the setup to install Ruby on the System."
},
{
"code": null,
"e": 2585,
"s": 2477,
"text": "Step 3 − Next, add Ruby bin folder to your PATH User Variable and System Variable to work with gem command."
},
{
"code": null,
"e": 2606,
"s": 2585,
"text": "Path User Variable −"
},
{
"code": null,
"e": 2640,
"s": 2606,
"text": "Right Click the My Computer icon."
},
{
"code": null,
"e": 2674,
"s": 2640,
"text": "Right Click the My Computer icon."
},
{
"code": null,
"e": 2693,
"s": 2674,
"text": "Select Properties."
},
{
"code": null,
"e": 2712,
"s": 2693,
"text": "Select Properties."
},
{
"code": null,
"e": 2774,
"s": 2712,
"text": "Next, click the Advanced tab and click Environment Variables."
},
{
"code": null,
"e": 2836,
"s": 2774,
"text": "Next, click the Advanced tab and click Environment Variables."
},
{
"code": null,
"e": 2936,
"s": 2836,
"text": "In the Environment Variables window, double click the PATH as shown in the screenshot given below −"
},
{
"code": null,
"e": 3169,
"s": 2936,
"text": "You will get an Edit User Variable box as shown. Add ruby bin folder path in the Variable value field as C:\\Ruby\\bin. If path is already set for other files, then put semicolon after that and add the Ruby folder path as shown below."
},
{
"code": null,
"e": 3190,
"s": 3169,
"text": "Click the OK button."
},
{
"code": null,
"e": 3208,
"s": 3190,
"text": "System Variable −"
},
{
"code": null,
"e": 3230,
"s": 3208,
"text": "Click the New button."
},
{
"code": null,
"e": 3252,
"s": 3230,
"text": "Click the New button."
},
{
"code": null,
"e": 3317,
"s": 3252,
"text": "Next, the New System Variable block is displayed as shown below."
},
{
"code": null,
"e": 3464,
"s": 3317,
"text": "Enter RubyOpt in the Variable name field and rubygems in the Variable value field. After writing the Variable name and value, click the OK button."
},
{
"code": null,
"e": 3611,
"s": 3464,
"text": "Enter RubyOpt in the Variable name field and rubygems in the Variable value field. After writing the Variable name and value, click the OK button."
},
{
"code": null,
"e": 3690,
"s": 3611,
"text": "Step 4 − Open the command prompt in your system and enter the following line −"
},
{
"code": null,
"e": 3708,
"s": 3690,
"text": "gem install sass\n"
},
{
"code": null,
"e": 3793,
"s": 3708,
"text": "Step 5 − Next, you will see the following screen after installing SASS successfully."
},
{
"code": null,
"e": 3836,
"s": 3793,
"text": "The following is a simple example of SASS."
},
{
"code": null,
"e": 4080,
"s": 3836,
"text": "<html>\n <head>\n <title> Import example of sass</title>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"style.css\"/>\n </head>\n\n <body>\n <h1>Simple Example</h1>\n <h3>Welcome to TutorialsPoint</h3>\n </body>\n</html>"
},
{
"code": null,
"e": 4417,
"s": 4080,
"text": "Now, we will create file as style.scss, which is quite similar to CSS and the only one difference is that it will be saved with .scss extension. Both, .htm and .scss files should be created inside the folder ruby. You can save your .scss file in the folder ruby\\lib\\sass\\ (before this process, create a folder as sass in lib directory)."
},
{
"code": null,
"e": 4468,
"s": 4417,
"text": "h1{\n color: #AF80ED;\n}\n\nh3{\n color: #DE5E85;\n}"
},
{
"code": null,
"e": 4584,
"s": 4468,
"text": "You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −"
},
{
"code": null,
"e": 4636,
"s": 4584,
"text": "sass --watch C:\\ruby\\lib\\sass\\style.scss:style.css\n"
},
{
"code": null,
"e": 4802,
"s": 4636,
"text": "When you run the above command, it will create the style.css file automatically. Whenever you change the SCSS file, the style.css file will be updated automatically."
},
{
"code": null,
"e": 4889,
"s": 4802,
"text": "The style.css file will have the following code when you run the above given command −"
},
{
"code": null,
"e": 4941,
"s": 4889,
"text": "h1 {\n color: #AF80ED;\n}\nh3 {\n color: #DE5E85;\n}"
},
{
"code": null,
"e": 5018,
"s": 4941,
"text": "Let us carry out the following steps to see how the above given code works −"
},
{
"code": null,
"e": 5064,
"s": 5018,
"text": "Save the above given code in hello.html file."
},
{
"code": null,
"e": 5110,
"s": 5064,
"text": "Save the above given code in hello.html file."
},
{
"code": null,
"e": 5144,
"s": 5110,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5178,
"s": 5144,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5213,
"s": 5178,
"text": "\n 50 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5230,
"s": 5213,
"text": " Code And Create"
},
{
"code": null,
"e": 5265,
"s": 5230,
"text": "\n 124 Lectures \n 30 hours \n"
},
{
"code": null,
"e": 5278,
"s": 5265,
"text": " Juan Galvan"
},
{
"code": null,
"e": 5315,
"s": 5278,
"text": "\n 162 Lectures \n 31.5 hours \n"
},
{
"code": null,
"e": 5335,
"s": 5315,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 5372,
"s": 5335,
"text": "\n 167 Lectures \n 45.5 hours \n"
},
{
"code": null,
"e": 5388,
"s": 5372,
"text": " Muslim Helalee"
},
{
"code": null,
"e": 5395,
"s": 5388,
"text": " Print"
},
{
"code": null,
"e": 5406,
"s": 5395,
"text": " Add Notes"
}
] |
gdb - Unix, Linux Command
|
gdb The GNU Debugger
gdb [-help] [-nx] [-q] [-batch] [-cd=dir] [-f] [-b bps] [-tty=dev] [-s symfile] [-e prog] [-se prog] [-c core] [-x cmds] [-d dir] [prog[core|procID]]
Example-1:
To Starting GDB
# gdb `which python` /var/cores/core.python.30520
output:
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
.
Find the GDB manual and other documentation resources online at:
.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from /usr/bin/python...(no debugging symbols found)...done.
warning: core file may not match specified executable file.
[New LWP 30520]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
warning: JITed object file architecture unknown is not compatible with target architecture i386:x86-64.
Core was generated by `python ./cachetop.py'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x00007f0a37aac40d in doupdate () from /lib/x86_64-linux-gnu/libncursesw.so.5
Example-2:
To Back Trace:
$(gdb) bt
output:
#0 0x00007f0a37aac40d in doupdate () from /lib/x86_64-linux-gnu/libncursesw.so.5
#1 0x00007f0a37aa07e6 in wrefresh () from /lib/x86_64-linux-gnu/libncursesw.so.5
#2 0x00007f0a37a99616 in ?? () from /lib/x86_64-linux-gnu/libncursesw.so.5
#3 0x00007f0a37a9a325 in wgetch () from /lib/x86_64-linux-gnu/libncursesw.so.5
#4 0x00007f0a37cc6ec3 in ?? () from /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so
#5 0x00000000004c4d5a in PyEval_EvalFrameEx ()
#6 0x00000000004c2e05 in PyEval_EvalCodeEx ()
#7 0x00000000004def08 in ?? ()
#8 0x00000000004b1153 in PyObject_Call ()
#9 0x00000000004c73ec in PyEval_EvalFrameEx ()
#10 0x00000000004c2e05 in PyEval_EvalCodeEx ()
#11 0x00000000004caf42 in PyEval_EvalFrameEx ()
#12 0x00000000004c2e05 in PyEval_EvalCodeEx ()
#13 0x00000000004c2ba9 in PyEval_EvalCode ()
#14 0x00000000004f20ef in ?? ()
#15 0x00000000004eca72 in PyRun_FileExFlags ()
#16 0x00000000004eb1f1 in PyRun_SimpleFileExFlags ()
#17 0x000000000049e18a in Py_Main ()
#18 0x00007f0a3be10830 in __libc_start_main (main=0x49daf0 , argc=2, argv=0x7ffd33d94838, init=, fini=, rtld_fini=,
stack_end=0x7ffd33d94828) at ../csu/libc-start.c:291
#19 0x000000000049da19 in _start ()
Example-3:
To Disassembly:
$ (gdb) disas doupdate
output:
Dump of assembler code for function doupdate:
0x00007f0a37aac2e0 <+0>: push %r15
0x00007f0a37aac2e2 <+2>: push %r14
0x00007f0a37aac2e4 <+4>: push %r13
0x00007f0a37aac2e6 <+6>: push %r12
0x00007f0a37aac2e8 <+8>: push %rbp
0x00007f0a37aac2e9 <+9>: push %rbx
0x00007f0a37aac2ea <+10>: sub $0xc8,%rsp
[...]
---Type to continue, or q to quit---
[...]
0x00007f0a37aac3f7 <+279>: cmpb $0x0,0x21(%rcx)
0x00007f0a37aac3fb <+283>: je 0x7f0a37aacc3b <doupdate+2395>
0x00007f0a37aac401 <+289>: mov 0x20cb68(%rip),%rax # 0x7f0a37cb8f70
0x00007f0a37aac408 <+296>: mov (%rax),%rsi
0x00007f0a37aac40b <+299>: xor %eax,%eax
=> 0x00007f0a37aac40d <+301>: mov 0x10(%rsi),%rdi
0x00007f0a37aac411 <+305>: cmpb $0x0,0x1c(%rdi)
0x00007f0a37aac415 <+309>: jne 0x7f0a37aac6f7 <doupdate+1047>
0x00007f0a37aac41b <+315>: movswl 0x4(%rcx),%ecx
0x00007f0a37aac41f <+319>: movswl 0x74(%rdx),%edi
0x00007f0a37aac423 <+323>: mov %rax,0x40(%rsp)
[...]
Example-4:
To Check Registers
$(gdb) i r
output:
rax 0x0 0
rbx 0x1993060 26816608
rcx 0x19902a0 26804896
rdx 0x19ce7d0 27060176
rsi 0x0 0
rdi 0x19ce7d0 27060176
rbp 0x7f0a3848eb10 0x7f0a3848eb10
rsp 0x7ffd33d93c00 0x7ffd33d93c00
r8 0x7f0a37cb93e0 139681862489056
r9 0x0 0
r10 0x8 8
r11 0x202 514
r12 0x0 0
r13 0x0 0
r14 0x7f0a3848eb10 139681870703376
r15 0x19ce7d0 27060176
rip 0x7f0a37aac40d 0x7f0a37aac40d <doupdate+301>
eflags 0x10246 [ PF ZF IF RF ]
cs 0x33 51
ss 0x2b 43
ds 0x0 0
es 0x0 0
fs 0x0 0
gs 0x0 0
Example-5:
To Memory Mappings
$(gdb) i proc m
output:
Mapped address spaces:
Start Addr End Addr Size Offset objfile
0x400000 0x6e7000 0x2e7000 0x0 /usr/bin/python2.7
0x8e6000 0x8e8000 0x2000 0x2e6000 /usr/bin/python2.7
0x8e8000 0x95f000 0x77000 0x2e8000 /usr/bin/python2.7
0x7f0a37a8b000 0x7f0a37ab8000 0x2d000 0x0 /lib/x86_64-linux-gnu/libncursesw.so.5.9
0x7f0a37ab8000 0x7f0a37cb8000 0x200000 0x2d000 /lib/x86_64-linux-gnu/libncursesw.so.5.9
0x7f0a37cb8000 0x7f0a37cb9000 0x1000 0x2d000 /lib/x86_64-linux-gnu/libncursesw.so.5.9
0x7f0a37cb9000 0x7f0a37cba000 0x1000 0x2e000 /lib/x86_64-linux-gnu/libncursesw.so.5.9
0x7f0a37cba000 0x7f0a37ccd000 0x13000 0x0 /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so
0x7f0a37ccd000 0x7f0a37ecc000 0x1ff000 0x13000 /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so
0x7f0a37ecc000 0x7f0a37ecd000 0x1000 0x12000 /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so
0x7f0a37ecd000 0x7f0a37ecf000 0x2000 0x13000 /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so
0x7f0a38050000 0x7f0a38066000 0x16000 0x0 /lib/x86_64-linux-gnu/libgcc_s.so.1
0x7f0a38066000 0x7f0a38265000 0x1ff000 0x16000 /lib/x86_64-linux-gnu/libgcc_s.so.1
0x7f0a38265000 0x7f0a38266000 0x1000 0x15000 /lib/x86_64-linux-gnu/libgcc_s.so.1
0x7f0a38266000 0x7f0a3828b000 0x25000 0x0 /lib/x86_64-linux-gnu/libtinfo.so.5.9
0x7f0a3828b000 0x7f0a3848a000 0x1ff000 0x25000 /lib/x86_64-linux-gnu/libtinfo.so.5.9
[...]
Example-6:
To apply Breakpoints
$(gdb) b *doupdate + 289
output:No symbol table is loaded. Use the "file" command.
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10599,
"s": 10577,
"text": "gdb The GNU Debugger"
},
{
"code": null,
"e": 10749,
"s": 10599,
"text": "gdb [-help] [-nx] [-q] [-batch] [-cd=dir] [-f] [-b bps] [-tty=dev] [-s symfile] [-e prog] [-se prog] [-c core] [-x cmds] [-d dir] [prog[core|procID]]"
},
{
"code": null,
"e": 10760,
"s": 10749,
"text": "Example-1:"
},
{
"code": null,
"e": 10776,
"s": 10760,
"text": "To Starting GDB"
},
{
"code": null,
"e": 10826,
"s": 10776,
"text": "# gdb `which python` /var/cores/core.python.30520"
},
{
"code": null,
"e": 10834,
"s": 10826,
"text": "output:"
},
{
"code": null,
"e": 12017,
"s": 10834,
"text": "GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1\nCopyright (C) 2016 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later \nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law. Type \"show copying\"\nand \"show warranty\" for details.\nThis GDB was configured as \"x86_64-linux-gnu\".\nType \"show configuration\" for configuration details.\nFor bug reporting instructions, please see:\n.\nFind the GDB manual and other documentation resources online at:\n.\nFor help, type \"help\".\nType \"apropos word\" to search for commands related to \"word\"...\nReading symbols from /usr/bin/python...(no debugging symbols found)...done.\n\nwarning: core file may not match specified executable file.\n[New LWP 30520]\n[Thread debugging using libthread_db enabled]\nUsing host libthread_db library \"/lib/x86_64-linux-gnu/libthread_db.so.1\".\n\nwarning: JITed object file architecture unknown is not compatible with target architecture i386:x86-64.\nCore was generated by `python ./cachetop.py'.\nProgram terminated with signal SIGSEGV, Segmentation fault.\n#0 0x00007f0a37aac40d in doupdate () from /lib/x86_64-linux-gnu/libncursesw.so.5\n"
},
{
"code": null,
"e": 12028,
"s": 12017,
"text": "Example-2:"
},
{
"code": null,
"e": 12043,
"s": 12028,
"text": "To Back Trace:"
},
{
"code": null,
"e": 12053,
"s": 12043,
"text": "$(gdb) bt"
},
{
"code": null,
"e": 12061,
"s": 12053,
"text": "output:"
},
{
"code": null,
"e": 13262,
"s": 12061,
"text": "#0 0x00007f0a37aac40d in doupdate () from /lib/x86_64-linux-gnu/libncursesw.so.5\n#1 0x00007f0a37aa07e6 in wrefresh () from /lib/x86_64-linux-gnu/libncursesw.so.5\n#2 0x00007f0a37a99616 in ?? () from /lib/x86_64-linux-gnu/libncursesw.so.5\n#3 0x00007f0a37a9a325 in wgetch () from /lib/x86_64-linux-gnu/libncursesw.so.5\n#4 0x00007f0a37cc6ec3 in ?? () from /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so\n#5 0x00000000004c4d5a in PyEval_EvalFrameEx ()\n#6 0x00000000004c2e05 in PyEval_EvalCodeEx ()\n#7 0x00000000004def08 in ?? ()\n#8 0x00000000004b1153 in PyObject_Call ()\n#9 0x00000000004c73ec in PyEval_EvalFrameEx ()\n#10 0x00000000004c2e05 in PyEval_EvalCodeEx ()\n#11 0x00000000004caf42 in PyEval_EvalFrameEx ()\n#12 0x00000000004c2e05 in PyEval_EvalCodeEx ()\n#13 0x00000000004c2ba9 in PyEval_EvalCode ()\n#14 0x00000000004f20ef in ?? ()\n#15 0x00000000004eca72 in PyRun_FileExFlags ()\n#16 0x00000000004eb1f1 in PyRun_SimpleFileExFlags ()\n#17 0x000000000049e18a in Py_Main ()\n#18 0x00007f0a3be10830 in __libc_start_main (main=0x49daf0 , argc=2, argv=0x7ffd33d94838, init=, fini=, rtld_fini=, \n stack_end=0x7ffd33d94828) at ../csu/libc-start.c:291\n#19 0x000000000049da19 in _start ()\n"
},
{
"code": null,
"e": 13273,
"s": 13262,
"text": "Example-3:"
},
{
"code": null,
"e": 13289,
"s": 13273,
"text": "To Disassembly:"
},
{
"code": null,
"e": 13312,
"s": 13289,
"text": "$ (gdb) disas doupdate"
},
{
"code": null,
"e": 13320,
"s": 13312,
"text": "output:"
},
{
"code": null,
"e": 14354,
"s": 13320,
"text": "Dump of assembler code for function doupdate:\n 0x00007f0a37aac2e0 <+0>: push %r15\n 0x00007f0a37aac2e2 <+2>: push %r14\n 0x00007f0a37aac2e4 <+4>: push %r13\n 0x00007f0a37aac2e6 <+6>: push %r12\n 0x00007f0a37aac2e8 <+8>: push %rbp\n 0x00007f0a37aac2e9 <+9>: push %rbx\n 0x00007f0a37aac2ea <+10>: sub $0xc8,%rsp\n[...]\n---Type to continue, or q to quit---\n[...]\n 0x00007f0a37aac3f7 <+279>: cmpb $0x0,0x21(%rcx)\n 0x00007f0a37aac3fb <+283>: je 0x7f0a37aacc3b <doupdate+2395>\n 0x00007f0a37aac401 <+289>: mov 0x20cb68(%rip),%rax # 0x7f0a37cb8f70\n 0x00007f0a37aac408 <+296>: mov (%rax),%rsi\n 0x00007f0a37aac40b <+299>: xor %eax,%eax\n=> 0x00007f0a37aac40d <+301>: mov 0x10(%rsi),%rdi\n 0x00007f0a37aac411 <+305>: cmpb $0x0,0x1c(%rdi)\n 0x00007f0a37aac415 <+309>: jne 0x7f0a37aac6f7 <doupdate+1047>\n 0x00007f0a37aac41b <+315>: movswl 0x4(%rcx),%ecx\n 0x00007f0a37aac41f <+319>: movswl 0x74(%rdx),%edi\n 0x00007f0a37aac423 <+323>: mov %rax,0x40(%rsp)\n[...]\n"
},
{
"code": null,
"e": 14365,
"s": 14354,
"text": "Example-4:"
},
{
"code": null,
"e": 14384,
"s": 14365,
"text": "To Check Registers"
},
{
"code": null,
"e": 14395,
"s": 14384,
"text": "$(gdb) i r"
},
{
"code": null,
"e": 14403,
"s": 14395,
"text": "output:"
},
{
"code": null,
"e": 15176,
"s": 14403,
"text": "rax 0x0 0\nrbx 0x1993060 26816608\nrcx 0x19902a0 26804896\nrdx 0x19ce7d0 27060176\nrsi 0x0 0\nrdi 0x19ce7d0 27060176\nrbp 0x7f0a3848eb10 0x7f0a3848eb10 \nrsp 0x7ffd33d93c00 0x7ffd33d93c00\nr8 0x7f0a37cb93e0 139681862489056\nr9 0x0 0\nr10 0x8 8\nr11 0x202 514\nr12 0x0 0\nr13 0x0 0\nr14 0x7f0a3848eb10 139681870703376\nr15 0x19ce7d0 27060176\nrip 0x7f0a37aac40d 0x7f0a37aac40d <doupdate+301>\neflags 0x10246 [ PF ZF IF RF ]\ncs 0x33 51\nss 0x2b 43\nds 0x0 0\nes 0x0 0\nfs 0x0 0\ngs 0x0 0\n"
},
{
"code": null,
"e": 15187,
"s": 15176,
"text": "Example-5:"
},
{
"code": null,
"e": 15206,
"s": 15187,
"text": "To Memory Mappings"
},
{
"code": null,
"e": 15222,
"s": 15206,
"text": "$(gdb) i proc m"
},
{
"code": null,
"e": 15230,
"s": 15222,
"text": "output:"
},
{
"code": null,
"e": 16896,
"s": 15230,
"text": "Mapped address spaces:\n\n Start Addr End Addr Size Offset objfile\n 0x400000 0x6e7000 0x2e7000 0x0 /usr/bin/python2.7\n 0x8e6000 0x8e8000 0x2000 0x2e6000 /usr/bin/python2.7\n 0x8e8000 0x95f000 0x77000 0x2e8000 /usr/bin/python2.7\n 0x7f0a37a8b000 0x7f0a37ab8000 0x2d000 0x0 /lib/x86_64-linux-gnu/libncursesw.so.5.9\n 0x7f0a37ab8000 0x7f0a37cb8000 0x200000 0x2d000 /lib/x86_64-linux-gnu/libncursesw.so.5.9\n 0x7f0a37cb8000 0x7f0a37cb9000 0x1000 0x2d000 /lib/x86_64-linux-gnu/libncursesw.so.5.9\n 0x7f0a37cb9000 0x7f0a37cba000 0x1000 0x2e000 /lib/x86_64-linux-gnu/libncursesw.so.5.9\n 0x7f0a37cba000 0x7f0a37ccd000 0x13000 0x0 /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so\n 0x7f0a37ccd000 0x7f0a37ecc000 0x1ff000 0x13000 /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so\n 0x7f0a37ecc000 0x7f0a37ecd000 0x1000 0x12000 /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so\n 0x7f0a37ecd000 0x7f0a37ecf000 0x2000 0x13000 /usr/lib/python2.7/lib-dynload/_curses.x86_64-linux-gnu.so\n 0x7f0a38050000 0x7f0a38066000 0x16000 0x0 /lib/x86_64-linux-gnu/libgcc_s.so.1\n 0x7f0a38066000 0x7f0a38265000 0x1ff000 0x16000 /lib/x86_64-linux-gnu/libgcc_s.so.1\n 0x7f0a38265000 0x7f0a38266000 0x1000 0x15000 /lib/x86_64-linux-gnu/libgcc_s.so.1\n 0x7f0a38266000 0x7f0a3828b000 0x25000 0x0 /lib/x86_64-linux-gnu/libtinfo.so.5.9\n 0x7f0a3828b000 0x7f0a3848a000 0x1ff000 0x25000 /lib/x86_64-linux-gnu/libtinfo.so.5.9\n[...]\n"
},
{
"code": null,
"e": 16907,
"s": 16896,
"text": "Example-6:"
},
{
"code": null,
"e": 16928,
"s": 16907,
"text": "To apply Breakpoints"
},
{
"code": null,
"e": 16953,
"s": 16928,
"text": "$(gdb) b *doupdate + 289"
},
{
"code": null,
"e": 17013,
"s": 16953,
"text": "output:No symbol table is loaded. Use the \"file\" command.\n"
},
{
"code": null,
"e": 17048,
"s": 17013,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 17076,
"s": 17048,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 17110,
"s": 17076,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 17127,
"s": 17110,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 17160,
"s": 17127,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 17171,
"s": 17160,
"text": " Pradeep D"
},
{
"code": null,
"e": 17206,
"s": 17171,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 17222,
"s": 17206,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 17255,
"s": 17222,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 17267,
"s": 17255,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 17299,
"s": 17267,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 17307,
"s": 17299,
"text": " Uplatz"
},
{
"code": null,
"e": 17314,
"s": 17307,
"text": " Print"
},
{
"code": null,
"e": 17325,
"s": 17314,
"text": " Add Notes"
}
] |
Machine Learning in production: Keras, Flask, Docker and Heroku | by Aissam Outchakoucht | Towards Data Science
|
In this tutorial we will try to walk together through all the building blocks of a Machine/Deep Learning project in production, i.e. a model that people can actually interact with.
Broadly speaking, we’ll create a web interface in which a user could upload an image, then a bit of Deep Learning magic comes into play, and Bingo! 🎉 we get a text revealing what does that image represent.
I KNOW, it’s not rocket science, it’s just image recognition, I haven’t reinvented the wheel. In fact I’m going to be even lazier and .. guess what ! .. I will be using an already trained model 😜
Keep in mind that the idea behind this tutorial is not to teach you Deep Leaning but rather to explore the pipeline of DL in production. What really matters is when we’ll be creating an API to interact with our model, “Dockerizing” it and deploying it.
The codes used in this tutorial are available on my GitHub [here].
GO ! GO ! GO !
As I’ve said before, we’re going to use a pretrained (and effective) Convolutional Neural Network model for image classification : VGG-19.
You can download a version of this model trained on more than a million images from the ImageNet database. The pretrained network can classify images into 1000 object categories, such as keyboard, car, orange, and many animals.
If you have a specific task of -say- classifying images in healthcare or in a factory, you can use this model as a starting point of a bigger model. In this case, the weights of the pretrained can be frozen so that they are not updated during training. This technique is called Transfer Learning. For the sake of simplicity, we are just using VGG19 as it is.
Let’s start coding .. 🤓
First, we have to import Tensorflow, Keras, as well as some functions to pre-process input images. Note that the default input size for this model is 224x224.
You can download VGG19 model from this [link] and then use tf.keras.models.load_model() to load it.
The following are two functions for preparing the input images and predicting the right class based on the pretrained model.
Now, you can even test your model by adding these lines to the bottom of your file (⚠️ pay attention to the path)
Now, let’s create an API to interact with this model. To do so we will use Flask: a micro web framework written in Python, it provides functionalities for building web applications, managing HTTP requests, rendering templates and so on.
We are also using Flask-Uploads which allows your application to flexibly and efficiently handle file uploading and serving the uploaded files.
Some set ups :
⚠️ Do not forget that before importing any library, first #pip install it !
⚠️ If you encounter some dependency problems when using Flask-Uploads installation, try to #pip install Flask-Reuploaded instead.
Note that we imported the two functions we created in the first step (they are located in another file named model.py)
Now let’s get down to business ..
At this stage, we need a new /upload route; but before going any further we first need a web page where the user will upload his image for us to process it.
Now that you are dazzled by my exceptional gift and expertise in web design 😅, let’s go back to our upload.py file.
So on the route /upload we expect to receive an HTTP POST request with an attached image, we’ll save this image in the path we specified before and we’ll use the two functions we’ve defined earlier in order to recognize the content of the image. Finally we render our prediction back to the user.
You can test your application by running the file using #python upload.py then go to the browser and type http://localhost:5000/upload .. and enjoy !
⚠️ Make sure your files’ locations correspond to the paths you use. You can check my project structure in my GitHub Repository
Your application is now up and running on your machine, and you reached the stage where you want to be able to distribute it.
However, just because the code works well on a specific machine doesn’t mean it’s going to work on other machines. So, it would be helpful if we could create an environment that contains our code as well as all the dependencies it requires for running, regardless of the host specs. In Docker’s language, we call this container .. well .. “a container” 😊
Okay, let’s be clear, this isn’t an advanced docker tutorial, but it contains basic and crucial things that took me long time to understand when I just started working with Docker.
In short, Docker allows us to create reproducible environments. So if you’re moving your application to a Cloud resource -and generally you will- then you can easily and surely deploy it without worrying about the dependencies, versions or recipient system.
Let’s go back to work ..
The first thing to do, obviously, is to download and install Docker, don’t worry it’s pretty straightforwardCreate a file requirements.txt in your main directory and fill it with the packages that we have installed for this project:
The first thing to do, obviously, is to download and install Docker, don’t worry it’s pretty straightforward
Create a file requirements.txt in your main directory and fill it with the packages that we have installed for this project:
Flask==1.1.2Flask-Reuploaded==0.3.2tensorflow==2.3.1Keras==2.4.3Keras-Preprocessing==1.1.2
3. Create a Dockerfile (without extension) which contains the instructions for building your Docker image.
For further information about the commands of Dockerfile, check the documentation
4. In a terminal, run the following command to build the Docker image:
#docker build -f Dockerfile -t recog_container:api .
5. Run container in background and print container ID using:
#docker run -p 5000:5000 -d recog_container:api
Once this is running, you should be able to view your app running in your browser at http://localhost:5000/upload
In case you need to install more libraries in this container, just run #docker ps and get the CONTAINER ID of your container.
Next, connect to this container using #docker exec -it <CONTAINER_ID> bash
Once connected, you can install whatever you want, for instance #pip install pillow and exit through #exit command
If you’re interested, you can find lots of others Docker commands [in this link]
Thanks to Heroku we will be able to deploy our application in the Cloud, thus everyone can be able to use it and recognize what’s in their images 😎
Create a new Heroku account if you don’t have one. Then download Heroku Command Line Interface (CLI) which makes it easy to create and manage your Heroku apps directly from the terminal.Login to your Heroku account using #heroku loginLog in to Container Registry: #heroku container:loginCreate a new Heroku app: #heroku create <app-name>Build the image based on your Dockefile and push it to this particular app in Heroku #heroku container:push web --app <app-name>You can finally open up your Heroku application through the command #heroku open --app <app-name>
Create a new Heroku account if you don’t have one. Then download Heroku Command Line Interface (CLI) which makes it easy to create and manage your Heroku apps directly from the terminal.
Login to your Heroku account using #heroku login
Log in to Container Registry: #heroku container:login
Create a new Heroku app: #heroku create <app-name>
Build the image based on your Dockefile and push it to this particular app in Heroku #heroku container:push web --app <app-name>
You can finally open up your Heroku application through the command #heroku open --app <app-name>
In this tutorial, we discovered that there are a lot of steps that have to be taken before an ML/DL model can be used by the customers.
The first step is to actually build your model 😅, and we have seen that there are lots of pretrained models that can be used as a starting point for your project. The second step was about building a Flask API in order to be able to interact with your ML-based backend. Then, we used Docker to package up this application with all of the requirements it depends on. Finally, we made the app available to everyone thanks to the Cloud Platform Heroku.
Link to GitHub repository [HERE]
Link to Twitter account [HERE]
|
[
{
"code": null,
"e": 353,
"s": 172,
"text": "In this tutorial we will try to walk together through all the building blocks of a Machine/Deep Learning project in production, i.e. a model that people can actually interact with."
},
{
"code": null,
"e": 559,
"s": 353,
"text": "Broadly speaking, we’ll create a web interface in which a user could upload an image, then a bit of Deep Learning magic comes into play, and Bingo! 🎉 we get a text revealing what does that image represent."
},
{
"code": null,
"e": 755,
"s": 559,
"text": "I KNOW, it’s not rocket science, it’s just image recognition, I haven’t reinvented the wheel. In fact I’m going to be even lazier and .. guess what ! .. I will be using an already trained model 😜"
},
{
"code": null,
"e": 1008,
"s": 755,
"text": "Keep in mind that the idea behind this tutorial is not to teach you Deep Leaning but rather to explore the pipeline of DL in production. What really matters is when we’ll be creating an API to interact with our model, “Dockerizing” it and deploying it."
},
{
"code": null,
"e": 1075,
"s": 1008,
"text": "The codes used in this tutorial are available on my GitHub [here]."
},
{
"code": null,
"e": 1090,
"s": 1075,
"text": "GO ! GO ! GO !"
},
{
"code": null,
"e": 1229,
"s": 1090,
"text": "As I’ve said before, we’re going to use a pretrained (and effective) Convolutional Neural Network model for image classification : VGG-19."
},
{
"code": null,
"e": 1457,
"s": 1229,
"text": "You can download a version of this model trained on more than a million images from the ImageNet database. The pretrained network can classify images into 1000 object categories, such as keyboard, car, orange, and many animals."
},
{
"code": null,
"e": 1816,
"s": 1457,
"text": "If you have a specific task of -say- classifying images in healthcare or in a factory, you can use this model as a starting point of a bigger model. In this case, the weights of the pretrained can be frozen so that they are not updated during training. This technique is called Transfer Learning. For the sake of simplicity, we are just using VGG19 as it is."
},
{
"code": null,
"e": 1840,
"s": 1816,
"text": "Let’s start coding .. 🤓"
},
{
"code": null,
"e": 1999,
"s": 1840,
"text": "First, we have to import Tensorflow, Keras, as well as some functions to pre-process input images. Note that the default input size for this model is 224x224."
},
{
"code": null,
"e": 2099,
"s": 1999,
"text": "You can download VGG19 model from this [link] and then use tf.keras.models.load_model() to load it."
},
{
"code": null,
"e": 2224,
"s": 2099,
"text": "The following are two functions for preparing the input images and predicting the right class based on the pretrained model."
},
{
"code": null,
"e": 2338,
"s": 2224,
"text": "Now, you can even test your model by adding these lines to the bottom of your file (⚠️ pay attention to the path)"
},
{
"code": null,
"e": 2575,
"s": 2338,
"text": "Now, let’s create an API to interact with this model. To do so we will use Flask: a micro web framework written in Python, it provides functionalities for building web applications, managing HTTP requests, rendering templates and so on."
},
{
"code": null,
"e": 2719,
"s": 2575,
"text": "We are also using Flask-Uploads which allows your application to flexibly and efficiently handle file uploading and serving the uploaded files."
},
{
"code": null,
"e": 2734,
"s": 2719,
"text": "Some set ups :"
},
{
"code": null,
"e": 2810,
"s": 2734,
"text": "⚠️ Do not forget that before importing any library, first #pip install it !"
},
{
"code": null,
"e": 2940,
"s": 2810,
"text": "⚠️ If you encounter some dependency problems when using Flask-Uploads installation, try to #pip install Flask-Reuploaded instead."
},
{
"code": null,
"e": 3059,
"s": 2940,
"text": "Note that we imported the two functions we created in the first step (they are located in another file named model.py)"
},
{
"code": null,
"e": 3093,
"s": 3059,
"text": "Now let’s get down to business .."
},
{
"code": null,
"e": 3250,
"s": 3093,
"text": "At this stage, we need a new /upload route; but before going any further we first need a web page where the user will upload his image for us to process it."
},
{
"code": null,
"e": 3366,
"s": 3250,
"text": "Now that you are dazzled by my exceptional gift and expertise in web design 😅, let’s go back to our upload.py file."
},
{
"code": null,
"e": 3663,
"s": 3366,
"text": "So on the route /upload we expect to receive an HTTP POST request with an attached image, we’ll save this image in the path we specified before and we’ll use the two functions we’ve defined earlier in order to recognize the content of the image. Finally we render our prediction back to the user."
},
{
"code": null,
"e": 3813,
"s": 3663,
"text": "You can test your application by running the file using #python upload.py then go to the browser and type http://localhost:5000/upload .. and enjoy !"
},
{
"code": null,
"e": 3940,
"s": 3813,
"text": "⚠️ Make sure your files’ locations correspond to the paths you use. You can check my project structure in my GitHub Repository"
},
{
"code": null,
"e": 4066,
"s": 3940,
"text": "Your application is now up and running on your machine, and you reached the stage where you want to be able to distribute it."
},
{
"code": null,
"e": 4421,
"s": 4066,
"text": "However, just because the code works well on a specific machine doesn’t mean it’s going to work on other machines. So, it would be helpful if we could create an environment that contains our code as well as all the dependencies it requires for running, regardless of the host specs. In Docker’s language, we call this container .. well .. “a container” 😊"
},
{
"code": null,
"e": 4602,
"s": 4421,
"text": "Okay, let’s be clear, this isn’t an advanced docker tutorial, but it contains basic and crucial things that took me long time to understand when I just started working with Docker."
},
{
"code": null,
"e": 4860,
"s": 4602,
"text": "In short, Docker allows us to create reproducible environments. So if you’re moving your application to a Cloud resource -and generally you will- then you can easily and surely deploy it without worrying about the dependencies, versions or recipient system."
},
{
"code": null,
"e": 4885,
"s": 4860,
"text": "Let’s go back to work .."
},
{
"code": null,
"e": 5118,
"s": 4885,
"text": "The first thing to do, obviously, is to download and install Docker, don’t worry it’s pretty straightforwardCreate a file requirements.txt in your main directory and fill it with the packages that we have installed for this project:"
},
{
"code": null,
"e": 5227,
"s": 5118,
"text": "The first thing to do, obviously, is to download and install Docker, don’t worry it’s pretty straightforward"
},
{
"code": null,
"e": 5352,
"s": 5227,
"text": "Create a file requirements.txt in your main directory and fill it with the packages that we have installed for this project:"
},
{
"code": null,
"e": 5443,
"s": 5352,
"text": "Flask==1.1.2Flask-Reuploaded==0.3.2tensorflow==2.3.1Keras==2.4.3Keras-Preprocessing==1.1.2"
},
{
"code": null,
"e": 5550,
"s": 5443,
"text": "3. Create a Dockerfile (without extension) which contains the instructions for building your Docker image."
},
{
"code": null,
"e": 5632,
"s": 5550,
"text": "For further information about the commands of Dockerfile, check the documentation"
},
{
"code": null,
"e": 5703,
"s": 5632,
"text": "4. In a terminal, run the following command to build the Docker image:"
},
{
"code": null,
"e": 5756,
"s": 5703,
"text": "#docker build -f Dockerfile -t recog_container:api ."
},
{
"code": null,
"e": 5817,
"s": 5756,
"text": "5. Run container in background and print container ID using:"
},
{
"code": null,
"e": 5865,
"s": 5817,
"text": "#docker run -p 5000:5000 -d recog_container:api"
},
{
"code": null,
"e": 5979,
"s": 5865,
"text": "Once this is running, you should be able to view your app running in your browser at http://localhost:5000/upload"
},
{
"code": null,
"e": 6105,
"s": 5979,
"text": "In case you need to install more libraries in this container, just run #docker ps and get the CONTAINER ID of your container."
},
{
"code": null,
"e": 6180,
"s": 6105,
"text": "Next, connect to this container using #docker exec -it <CONTAINER_ID> bash"
},
{
"code": null,
"e": 6295,
"s": 6180,
"text": "Once connected, you can install whatever you want, for instance #pip install pillow and exit through #exit command"
},
{
"code": null,
"e": 6376,
"s": 6295,
"text": "If you’re interested, you can find lots of others Docker commands [in this link]"
},
{
"code": null,
"e": 6524,
"s": 6376,
"text": "Thanks to Heroku we will be able to deploy our application in the Cloud, thus everyone can be able to use it and recognize what’s in their images 😎"
},
{
"code": null,
"e": 7087,
"s": 6524,
"text": "Create a new Heroku account if you don’t have one. Then download Heroku Command Line Interface (CLI) which makes it easy to create and manage your Heroku apps directly from the terminal.Login to your Heroku account using #heroku loginLog in to Container Registry: #heroku container:loginCreate a new Heroku app: #heroku create <app-name>Build the image based on your Dockefile and push it to this particular app in Heroku #heroku container:push web --app <app-name>You can finally open up your Heroku application through the command #heroku open --app <app-name>"
},
{
"code": null,
"e": 7274,
"s": 7087,
"text": "Create a new Heroku account if you don’t have one. Then download Heroku Command Line Interface (CLI) which makes it easy to create and manage your Heroku apps directly from the terminal."
},
{
"code": null,
"e": 7323,
"s": 7274,
"text": "Login to your Heroku account using #heroku login"
},
{
"code": null,
"e": 7377,
"s": 7323,
"text": "Log in to Container Registry: #heroku container:login"
},
{
"code": null,
"e": 7428,
"s": 7377,
"text": "Create a new Heroku app: #heroku create <app-name>"
},
{
"code": null,
"e": 7557,
"s": 7428,
"text": "Build the image based on your Dockefile and push it to this particular app in Heroku #heroku container:push web --app <app-name>"
},
{
"code": null,
"e": 7655,
"s": 7557,
"text": "You can finally open up your Heroku application through the command #heroku open --app <app-name>"
},
{
"code": null,
"e": 7791,
"s": 7655,
"text": "In this tutorial, we discovered that there are a lot of steps that have to be taken before an ML/DL model can be used by the customers."
},
{
"code": null,
"e": 8241,
"s": 7791,
"text": "The first step is to actually build your model 😅, and we have seen that there are lots of pretrained models that can be used as a starting point for your project. The second step was about building a Flask API in order to be able to interact with your ML-based backend. Then, we used Docker to package up this application with all of the requirements it depends on. Finally, we made the app available to everyone thanks to the Cloud Platform Heroku."
},
{
"code": null,
"e": 8274,
"s": 8241,
"text": "Link to GitHub repository [HERE]"
}
] |
Python Keras | keras.utils.to_categorical() - GeeksforGeeks
|
23 Jun, 2021
Keras provides numpy utility library, which provides functions to perform actions on numpy arrays. Using the method to_categorical(), a numpy array (or) a vector which has integers that represent different categories, can be converted into a numpy array (or) a matrix which has binary values and has columns equal to the number of categories in the data.
Syntax: tf.keras.utils.to_categorical(y, num_classes=None, dtype=”float32′′)
Parameters:
y (input vector): A vector which has integers representing various classes in the data.
num_classes: Total number of classes. If nothing is mentioned, it considers the largest number of the input vector and adds 1, to get the number of classes.
Its default value is "None".
dtype: It is the desired data type of the output values.
By default, it's value is 'float32'.
Output: This function returns a matrix of binary values (either ‘1’ or ‘0’). It has number of rows equal to the length of the input vector and number of columns equal to the number of classes.
Code: Converting Cifar10 dataset labels vector to categorical data matrix:
Python3
# Loading the dataset from keras.datasets import cifar10(train_images, train_labels), (test_images, test_labels)= cifar10.load_data() # Labels before applying the function# Training set labelsprint(train_labels)print(train_labels.shape) # Testing set labelsprint(test_labels)print(test_labels.shape) # Applying the function to training set labels and testing set labelsfrom keras.utils import to_categoricaltrain_labels = to_categorical(train_labels, dtype ="uint8")test_labels = to_categorical(test_labels, dtype ="uint8") # Labels after applying the function# Training set labelsprint(train_labels)print(train_labels.shape) # Testing set labelsprint(test_labels)print(test_labels.shape)
Output:
#Labels before applying the function
#Training set labels
array([[6],
[9],
[9],
...,
[9],
[1],
[1]], dtype=uint8)
#Training set labels shape
(50000, 1)
#Testing set labels
array([[3],
[8],
[8],
...,
[5],
[1],
[7]], dtype=uint8)
#Testing set labels shape
(10000, 1)
#Labels after applying the function
#Training set labels
[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 1]
[0 0 0 ... 0 0 1]
...
[0 0 0 ... 0 0 1]
[0 1 0 ... 0 0 0]
[0 1 0 ... 0 0 0]]
#Training set labels shape
(50000, 10)
#Testing set labels
[[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 1. 0.]
[0. 0. 0. ... 0. 1. 0.]
...
[0. 0. 0. ... 0. 0. 0.]
[0. 1. 0. ... 0. 0. 0.]
[0. 0. 0. ... 1. 0. 0.]]
#Testing set labels shape
(10000, 10)
Code: Considering an input vector with 7 classes. (It can have values ranging from 0 to 6(n-1)).
Python3
# Initializing Input vectorclass_vector =[2, 5, 6, 1, 4, 2, 3, 2]print(class_vector) # Applying the function on input class vectorfrom keras.utils import to_categoricaloutput_matrix = to_categorical(class_vector, num_classes = 7, dtype ="int32") print(output_matrix)
Output:
[[0 0 1 0 0 0 0]
[0 0 0 0 0 1 0]
[0 0 0 0 0 0 1]
[0 1 0 0 0 0 0]
[0 0 0 0 1 0 0]
[0 0 1 0 0 0 0]
[0 0 0 1 0 0 0]
[0 0 1 0 0 0 0]]
adnanirshad158
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Reinforcement learning
Decision Tree Introduction with example
Python | Decision tree implementation
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 26077,
"s": 26049,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 26432,
"s": 26077,
"text": "Keras provides numpy utility library, which provides functions to perform actions on numpy arrays. Using the method to_categorical(), a numpy array (or) a vector which has integers that represent different categories, can be converted into a numpy array (or) a matrix which has binary values and has columns equal to the number of categories in the data."
},
{
"code": null,
"e": 26509,
"s": 26432,
"text": "Syntax: tf.keras.utils.to_categorical(y, num_classes=None, dtype=”float32′′)"
},
{
"code": null,
"e": 26522,
"s": 26509,
"text": "Parameters: "
},
{
"code": null,
"e": 26893,
"s": 26522,
"text": "y (input vector): A vector which has integers representing various classes in the data.\n\nnum_classes: Total number of classes. If nothing is mentioned, it considers the largest number of the input vector and adds 1, to get the number of classes.\nIts default value is \"None\".\n\ndtype: It is the desired data type of the output values. \nBy default, it's value is 'float32'."
},
{
"code": null,
"e": 27086,
"s": 26893,
"text": "Output: This function returns a matrix of binary values (either ‘1’ or ‘0’). It has number of rows equal to the length of the input vector and number of columns equal to the number of classes."
},
{
"code": null,
"e": 27162,
"s": 27086,
"text": "Code: Converting Cifar10 dataset labels vector to categorical data matrix: "
},
{
"code": null,
"e": 27170,
"s": 27162,
"text": "Python3"
},
{
"code": "# Loading the dataset from keras.datasets import cifar10(train_images, train_labels), (test_images, test_labels)= cifar10.load_data() # Labels before applying the function# Training set labelsprint(train_labels)print(train_labels.shape) # Testing set labelsprint(test_labels)print(test_labels.shape) # Applying the function to training set labels and testing set labelsfrom keras.utils import to_categoricaltrain_labels = to_categorical(train_labels, dtype =\"uint8\")test_labels = to_categorical(test_labels, dtype =\"uint8\") # Labels after applying the function# Training set labelsprint(train_labels)print(train_labels.shape) # Testing set labelsprint(test_labels)print(test_labels.shape)",
"e": 27859,
"s": 27170,
"text": null
},
{
"code": null,
"e": 27868,
"s": 27859,
"text": "Output: "
},
{
"code": null,
"e": 28654,
"s": 27868,
"text": "#Labels before applying the function\n#Training set labels\narray([[6],\n [9],\n [9],\n ...,\n [9],\n [1],\n [1]], dtype=uint8)\n\n#Training set labels shape\n(50000, 1)\n\n#Testing set labels\narray([[3],\n [8],\n [8],\n ...,\n [5],\n [1],\n [7]], dtype=uint8)\n\n#Testing set labels shape\n(10000, 1)\n\n#Labels after applying the function\n#Training set labels\n[[0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 1]\n [0 0 0 ... 0 0 1]\n ...\n [0 0 0 ... 0 0 1]\n [0 1 0 ... 0 0 0]\n [0 1 0 ... 0 0 0]]\n\n#Training set labels shape\n(50000, 10)\n\n#Testing set labels\n[[0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 1. 0.]\n [0. 0. 0. ... 0. 1. 0.]\n ...\n [0. 0. 0. ... 0. 0. 0.]\n [0. 1. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 1. 0. 0.]]\n\n#Testing set labels shape\n(10000, 10)"
},
{
"code": null,
"e": 28751,
"s": 28654,
"text": "Code: Considering an input vector with 7 classes. (It can have values ranging from 0 to 6(n-1))."
},
{
"code": null,
"e": 28759,
"s": 28751,
"text": "Python3"
},
{
"code": "# Initializing Input vectorclass_vector =[2, 5, 6, 1, 4, 2, 3, 2]print(class_vector) # Applying the function on input class vectorfrom keras.utils import to_categoricaloutput_matrix = to_categorical(class_vector, num_classes = 7, dtype =\"int32\") print(output_matrix)",
"e": 29026,
"s": 28759,
"text": null
},
{
"code": null,
"e": 29035,
"s": 29026,
"text": "Output: "
},
{
"code": null,
"e": 29172,
"s": 29035,
"text": "[[0 0 1 0 0 0 0]\n [0 0 0 0 0 1 0]\n [0 0 0 0 0 0 1]\n [0 1 0 0 0 0 0]\n [0 0 0 0 1 0 0]\n [0 0 1 0 0 0 0]\n [0 0 0 1 0 0 0]\n [0 0 1 0 0 0 0]]"
},
{
"code": null,
"e": 29189,
"s": 29174,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29206,
"s": 29189,
"text": "Machine Learning"
},
{
"code": null,
"e": 29213,
"s": 29206,
"text": "Python"
},
{
"code": null,
"e": 29230,
"s": 29213,
"text": "Machine Learning"
},
{
"code": null,
"e": 29328,
"s": 29230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29351,
"s": 29328,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 29365,
"s": 29351,
"text": "Decision Tree"
},
{
"code": null,
"e": 29388,
"s": 29365,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 29428,
"s": 29388,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 29466,
"s": 29428,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 29494,
"s": 29466,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29544,
"s": 29494,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29566,
"s": 29544,
"text": "Python map() function"
}
] |
Android UI Layouts - GeeksforGeeks
|
21 Feb, 2022
Android Layout is used to define the user interface that holds the UI controls or widgets that will appear on the screen of an android application or activity screen. Generally, every application is a combination of View and ViewGroup. As we know, an android application contains a large number of activities and we can say each activity is one page of the application. So, each activity contains multiple user interface components and those components are the instances of the View and ViewGroup. All the elements in a layout are built using a hierarchy of View and ViewGroup objects.
A View is defined as the user interface which is used to create interactive UI components such as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event handling and drawing. They are Generally Called Widgets.
View
A ViewGroup act as a base class for layouts and layouts parameters that hold other Views or ViewGroups and to define the layout properties. They are Generally Called layouts.
ViewGroup
The Android framework will allow us to use UI elements or widgets in two ways:
Use UI elements in the XML file
Create elements in the Kotlin file dynamically
Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View elements one by one either in a particular direction either horizontally or vertically based on the orientation property.
Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the position of child View elements relative to each other like (A to the right of B) or relative to the parent (fix to the top of the parent).
Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the position of layout constraints for every child View relative to other views present. A ConstraintLayout is similar to a RelativeLayout, but having more power.
Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of View elements it contains on the top of each other to display only a single View inside the FrameLayout.
Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View elements in rows and columns.
Android Web View: WebView is a browser that is used to display the web pages in our activity layout.
Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single column.
Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of items in a grid view of rows and columns.
Here, we can create a layout similar to web pages. The XML layout file contains at least one root element in which additional layout elements or widgets can be added to build a View hierarchy. Following is the example:
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http:// schemas.android.com/apk/res/android" xmlns:tools="http:// schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--EditText with id editText--> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:hint="Input" android:inputType="text"/> <!--Button with id showInput--> <Button android:id="@+id/showInput" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="show" android:backgroundTint="@color/colorPrimary" android:textColor="@android:color/white"/> </LinearLayout>
When we have created the layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element from the XML using findViewById.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// finding the button
val showButton = findViewById<Button>(R.id.showInput)
// finding the edit text
val editText = findViewById<EditText>(R.id.editText)
Here, we can observe the above code and finds out that we are calling our layout using the setContentView method in the form of R.layout.activity_main. Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.
We can create or instantiate UI elements or widgets during runtime by using the custom View and ViewGroup objects programmatically in the Kotlin file. Below is the example of creating a layout using LinearLayout to hold an EditText and a Button in an activity programmatically.
Kotlin
import android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.LinearLayoutimport android.widget.Toastimport android.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // create the button val showButton = Button(this) showButton.setText("Submit") // create the editText val editText = EditText(this) val linearLayout = findViewById<LinearLayout>(R.id.l_layout) linearLayout.addView(editText) linearLayout.addView(showButton) // Setting On Click Listener showButton.setOnClickListener { // Getting the user input val text = editText.text // Showing the user input Toast.makeText(this, text, Toast.LENGTH_SHORT).show() } }}
XML attributes
Description
bhartik021
rkbhola5
android
Kotlin Android
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
Kotlin Android Tutorial
Kotlin when expression
How to Change the Color of Status Bar in an Android App?
|
[
{
"code": null,
"e": 25745,
"s": 25717,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 26331,
"s": 25745,
"text": "Android Layout is used to define the user interface that holds the UI controls or widgets that will appear on the screen of an android application or activity screen. Generally, every application is a combination of View and ViewGroup. As we know, an android application contains a large number of activities and we can say each activity is one page of the application. So, each activity contains multiple user interface components and those components are the instances of the View and ViewGroup. All the elements in a layout are built using a hierarchy of View and ViewGroup objects."
},
{
"code": null,
"e": 26565,
"s": 26331,
"text": "A View is defined as the user interface which is used to create interactive UI components such as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event handling and drawing. They are Generally Called Widgets."
},
{
"code": null,
"e": 26570,
"s": 26565,
"text": "View"
},
{
"code": null,
"e": 26745,
"s": 26570,
"text": "A ViewGroup act as a base class for layouts and layouts parameters that hold other Views or ViewGroups and to define the layout properties. They are Generally Called layouts."
},
{
"code": null,
"e": 26755,
"s": 26745,
"text": "ViewGroup"
},
{
"code": null,
"e": 26836,
"s": 26755,
"text": "The Android framework will allow us to use UI elements or widgets in two ways: "
},
{
"code": null,
"e": 26868,
"s": 26836,
"text": "Use UI elements in the XML file"
},
{
"code": null,
"e": 26915,
"s": 26868,
"text": "Create elements in the Kotlin file dynamically"
},
{
"code": null,
"e": 27125,
"s": 26915,
"text": "Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View elements one by one either in a particular direction either horizontally or vertically based on the orientation property."
},
{
"code": null,
"e": 27350,
"s": 27125,
"text": "Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the position of child View elements relative to each other like (A to the right of B) or relative to the parent (fix to the top of the parent)."
},
{
"code": null,
"e": 27598,
"s": 27350,
"text": "Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the position of layout constraints for every child View relative to other views present. A ConstraintLayout is similar to a RelativeLayout, but having more power."
},
{
"code": null,
"e": 27794,
"s": 27598,
"text": "Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of View elements it contains on the top of each other to display only a single View inside the FrameLayout."
},
{
"code": null,
"e": 27914,
"s": 27794,
"text": "Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View elements in rows and columns."
},
{
"code": null,
"e": 28015,
"s": 27914,
"text": "Android Web View: WebView is a browser that is used to display the web pages in our activity layout."
},
{
"code": null,
"e": 28120,
"s": 28015,
"text": "Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single column."
},
{
"code": null,
"e": 28250,
"s": 28120,
"text": "Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of items in a grid view of rows and columns."
},
{
"code": null,
"e": 28471,
"s": 28250,
"text": "Here, we can create a layout similar to web pages. The XML layout file contains at least one root element in which additional layout elements or widgets can be added to build a View hierarchy. Following is the example: "
},
{
"code": null,
"e": 28475,
"s": 28471,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http:// schemas.android.com/apk/res/android\" xmlns:tools=\"http:// schemas.android.com/tools\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--EditText with id editText--> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"16dp\" android:hint=\"Input\" android:inputType=\"text\"/> <!--Button with id showInput--> <Button android:id=\"@+id/showInput\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:text=\"show\" android:backgroundTint=\"@color/colorPrimary\" android:textColor=\"@android:color/white\"/> </LinearLayout>",
"e": 29421,
"s": 28475,
"text": null
},
{
"code": null,
"e": 29599,
"s": 29421,
"text": "When we have created the layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element from the XML using findViewById. "
},
{
"code": null,
"e": 29930,
"s": 29599,
"text": "override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n\n // finding the button\n val showButton = findViewById<Button>(R.id.showInput)\n\n // finding the edit text\n val editText = findViewById<EditText>(R.id.editText)"
},
{
"code": null,
"e": 30244,
"s": 29930,
"text": "Here, we can observe the above code and finds out that we are calling our layout using the setContentView method in the form of R.layout.activity_main. Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity. "
},
{
"code": null,
"e": 30523,
"s": 30244,
"text": "We can create or instantiate UI elements or widgets during runtime by using the custom View and ViewGroup objects programmatically in the Kotlin file. Below is the example of creating a layout using LinearLayout to hold an EditText and a Button in an activity programmatically. "
},
{
"code": null,
"e": 30530,
"s": 30523,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.LinearLayoutimport android.widget.Toastimport android.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // create the button val showButton = Button(this) showButton.setText(\"Submit\") // create the editText val editText = EditText(this) val linearLayout = findViewById<LinearLayout>(R.id.l_layout) linearLayout.addView(editText) linearLayout.addView(showButton) // Setting On Click Listener showButton.setOnClickListener { // Getting the user input val text = editText.text // Showing the user input Toast.makeText(this, text, Toast.LENGTH_SHORT).show() } }}",
"e": 31499,
"s": 30530,
"text": null
},
{
"code": null,
"e": 31514,
"s": 31499,
"text": "XML attributes"
},
{
"code": null,
"e": 31526,
"s": 31514,
"text": "Description"
},
{
"code": null,
"e": 31537,
"s": 31526,
"text": "bhartik021"
},
{
"code": null,
"e": 31546,
"s": 31537,
"text": "rkbhola5"
},
{
"code": null,
"e": 31554,
"s": 31546,
"text": "android"
},
{
"code": null,
"e": 31569,
"s": 31554,
"text": "Kotlin Android"
},
{
"code": null,
"e": 31576,
"s": 31569,
"text": "Kotlin"
},
{
"code": null,
"e": 31674,
"s": 31576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31717,
"s": 31674,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 31748,
"s": 31717,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 31790,
"s": 31748,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 31832,
"s": 31790,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31872,
"s": 31832,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 31899,
"s": 31872,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 31962,
"s": 31899,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 31986,
"s": 31962,
"text": "Kotlin Android Tutorial"
},
{
"code": null,
"e": 32009,
"s": 31986,
"text": "Kotlin when expression"
}
] |
Final static variable in Java - GeeksforGeeks
|
22 Sep, 2017
Prerequisite : static variables, final keyword
Static variable: When the value of a variable is not varied, then it is a not good choice to go for instance variable. At that time we can add static modifier to that variable. Whenever we declare variable as static, then at the class level a single variable is created which is shared with the objects. Any change in that static variable reflect to the other objects operations. If we won’t initialize a static variable, then by default JVM will provide a default value for static variable.
But when we declare a static variable with final modifier then we should take care of the following conventions:
Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared.
Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists which can’t be reinitialize.
Important points about final static variable:
Initialization of variable Mandatory : If the static variable declared as final, then we have to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the final static variable.// Java program to illustrate the behavior of// final static variableclass Test { final static int x; public static void main(String[] args) { }}Output:error: variable x not initialized in the default constructor
Initialization before class loading : For final static variable, it is compulsory that we should perform initialization before class loading completion. We can initialize a final static variable at the time of declaration.// Java program to illustrate that final// static variable can be initialized// at the time of declarationclass Test { final static int x = 10; public static void main(String[] args) { System.out.println(x); }}Output:10
Initialize inside a static block : We can also initialize a final static variable inside a static block because we should initialize a final static variable before class and we know that static block is executed before main() method.// Java program to illustrate that final// static variable can be initialized// inside static blockclass Test { final static int x; static { x = 10; } public static void main(String[] args) { System.out.println(x); }}Output:10
Initialization of variable Mandatory : If the static variable declared as final, then we have to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the final static variable.// Java program to illustrate the behavior of// final static variableclass Test { final static int x; public static void main(String[] args) { }}Output:error: variable x not initialized in the default constructor
// Java program to illustrate the behavior of// final static variableclass Test { final static int x; public static void main(String[] args) { }}
Output:
error: variable x not initialized in the default constructor
Initialization before class loading : For final static variable, it is compulsory that we should perform initialization before class loading completion. We can initialize a final static variable at the time of declaration.// Java program to illustrate that final// static variable can be initialized// at the time of declarationclass Test { final static int x = 10; public static void main(String[] args) { System.out.println(x); }}Output:10
// Java program to illustrate that final// static variable can be initialized// at the time of declarationclass Test { final static int x = 10; public static void main(String[] args) { System.out.println(x); }}
Output:
10
Initialize inside a static block : We can also initialize a final static variable inside a static block because we should initialize a final static variable before class and we know that static block is executed before main() method.// Java program to illustrate that final// static variable can be initialized// inside static blockclass Test { final static int x; static { x = 10; } public static void main(String[] args) { System.out.println(x); }}Output:10
// Java program to illustrate that final// static variable can be initialized// inside static blockclass Test { final static int x; static { x = 10; } public static void main(String[] args) { System.out.println(x); }}
Output:
10
Apart from the above mentioned methods, if we try to initialize a final static variable anywhere else then we will get compile time error.
// Java program to illustrate// that we can't declare// final static variable// within any non-static blocks or methodsclass Test { final static int x; public static void m() { x = 10; } public static void main(String[] args) { System.out.println(x); }}
Output:
error: cannot assign a value to final variable x
Implementation of final static variable
class MainClass { final static String company = "GFG"; String name; int rollno;public static void main(String[] args) { MainClass ob = new MainClass(); // If we create a database for GFG org // then the company name should be constant // It can’t be changed by programmer. ob.company = "Geeksforgeeks"; ob.name = "Bishal"; ob.rollno = 007; System.out.println(ob.company); System.out.println(ob.name); System.out.println(ob.rollno); }}
Output:
error: cannot assign a value to final variable company
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-final keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Overriding in Java
Set in Java
|
[
{
"code": null,
"e": 24190,
"s": 24162,
"text": "\n22 Sep, 2017"
},
{
"code": null,
"e": 24237,
"s": 24190,
"text": "Prerequisite : static variables, final keyword"
},
{
"code": null,
"e": 24729,
"s": 24237,
"text": "Static variable: When the value of a variable is not varied, then it is a not good choice to go for instance variable. At that time we can add static modifier to that variable. Whenever we declare variable as static, then at the class level a single variable is created which is shared with the objects. Any change in that static variable reflect to the other objects operations. If we won’t initialize a static variable, then by default JVM will provide a default value for static variable."
},
{
"code": null,
"e": 24842,
"s": 24729,
"text": "But when we declare a static variable with final modifier then we should take care of the following conventions:"
},
{
"code": null,
"e": 24973,
"s": 24842,
"text": "Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared."
},
{
"code": null,
"e": 25102,
"s": 24973,
"text": "Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists which can’t be reinitialize."
},
{
"code": null,
"e": 25148,
"s": 25102,
"text": "Important points about final static variable:"
},
{
"code": null,
"e": 26562,
"s": 25148,
"text": "Initialization of variable Mandatory : If the static variable declared as final, then we have to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the final static variable.// Java program to illustrate the behavior of// final static variableclass Test { final static int x; public static void main(String[] args) { }}Output:error: variable x not initialized in the default constructor\nInitialization before class loading : For final static variable, it is compulsory that we should perform initialization before class loading completion. We can initialize a final static variable at the time of declaration.// Java program to illustrate that final// static variable can be initialized// at the time of declarationclass Test { final static int x = 10; public static void main(String[] args) { System.out.println(x); }}Output:10\nInitialize inside a static block : We can also initialize a final static variable inside a static block because we should initialize a final static variable before class and we know that static block is executed before main() method.// Java program to illustrate that final// static variable can be initialized// inside static blockclass Test { final static int x; static { x = 10; } public static void main(String[] args) { System.out.println(x); }}Output:10\n"
},
{
"code": null,
"e": 27020,
"s": 26562,
"text": "Initialization of variable Mandatory : If the static variable declared as final, then we have to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the final static variable.// Java program to illustrate the behavior of// final static variableclass Test { final static int x; public static void main(String[] args) { }}Output:error: variable x not initialized in the default constructor\n"
},
{
"code": "// Java program to illustrate the behavior of// final static variableclass Test { final static int x; public static void main(String[] args) { }}",
"e": 27178,
"s": 27020,
"text": null
},
{
"code": null,
"e": 27186,
"s": 27178,
"text": "Output:"
},
{
"code": null,
"e": 27248,
"s": 27186,
"text": "error: variable x not initialized in the default constructor\n"
},
{
"code": null,
"e": 27710,
"s": 27248,
"text": "Initialization before class loading : For final static variable, it is compulsory that we should perform initialization before class loading completion. We can initialize a final static variable at the time of declaration.// Java program to illustrate that final// static variable can be initialized// at the time of declarationclass Test { final static int x = 10; public static void main(String[] args) { System.out.println(x); }}Output:10\n"
},
{
"code": "// Java program to illustrate that final// static variable can be initialized// at the time of declarationclass Test { final static int x = 10; public static void main(String[] args) { System.out.println(x); }}",
"e": 27940,
"s": 27710,
"text": null
},
{
"code": null,
"e": 27948,
"s": 27940,
"text": "Output:"
},
{
"code": null,
"e": 27952,
"s": 27948,
"text": "10\n"
},
{
"code": null,
"e": 28448,
"s": 27952,
"text": "Initialize inside a static block : We can also initialize a final static variable inside a static block because we should initialize a final static variable before class and we know that static block is executed before main() method.// Java program to illustrate that final// static variable can be initialized// inside static blockclass Test { final static int x; static { x = 10; } public static void main(String[] args) { System.out.println(x); }}Output:10\n"
},
{
"code": "// Java program to illustrate that final// static variable can be initialized// inside static blockclass Test { final static int x; static { x = 10; } public static void main(String[] args) { System.out.println(x); }}",
"e": 28701,
"s": 28448,
"text": null
},
{
"code": null,
"e": 28709,
"s": 28701,
"text": "Output:"
},
{
"code": null,
"e": 28713,
"s": 28709,
"text": "10\n"
},
{
"code": null,
"e": 28852,
"s": 28713,
"text": "Apart from the above mentioned methods, if we try to initialize a final static variable anywhere else then we will get compile time error."
},
{
"code": "// Java program to illustrate// that we can't declare// final static variable// within any non-static blocks or methodsclass Test { final static int x; public static void m() { x = 10; } public static void main(String[] args) { System.out.println(x); }}",
"e": 29141,
"s": 28852,
"text": null
},
{
"code": null,
"e": 29149,
"s": 29141,
"text": "Output:"
},
{
"code": null,
"e": 29199,
"s": 29149,
"text": "error: cannot assign a value to final variable x\n"
},
{
"code": null,
"e": 29239,
"s": 29199,
"text": "Implementation of final static variable"
},
{
"code": "class MainClass { final static String company = \"GFG\"; String name; int rollno;public static void main(String[] args) { MainClass ob = new MainClass(); // If we create a database for GFG org // then the company name should be constant // It can’t be changed by programmer. ob.company = \"Geeksforgeeks\"; ob.name = \"Bishal\"; ob.rollno = 007; System.out.println(ob.company); System.out.println(ob.name); System.out.println(ob.rollno); }}",
"e": 29766,
"s": 29239,
"text": null
},
{
"code": null,
"e": 29774,
"s": 29766,
"text": "Output:"
},
{
"code": null,
"e": 29830,
"s": 29774,
"text": "error: cannot assign a value to final variable company\n"
},
{
"code": null,
"e": 30136,
"s": 29830,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30261,
"s": 30136,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30280,
"s": 30261,
"text": "Java-final keyword"
},
{
"code": null,
"e": 30285,
"s": 30280,
"text": "Java"
},
{
"code": null,
"e": 30290,
"s": 30285,
"text": "Java"
},
{
"code": null,
"e": 30388,
"s": 30290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30397,
"s": 30388,
"text": "Comments"
},
{
"code": null,
"e": 30410,
"s": 30397,
"text": "Old Comments"
},
{
"code": null,
"e": 30442,
"s": 30410,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30472,
"s": 30442,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30523,
"s": 30472,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30541,
"s": 30523,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30572,
"s": 30541,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30604,
"s": 30572,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30623,
"s": 30604,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 30643,
"s": 30623,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30662,
"s": 30643,
"text": "Overriding in Java"
}
] |
Get max and min values of an array in Arduino
|
In order to get the max/ min values of an array in Arduino, we can run a simple for loop. Two implementations are shown below. One uses the max() and min() functions of Arduino, and the other uses the > and < operators.
The max and min functions have the following syntax: max(a,b) and min(a,b), and they return the max and min values out of a and b respectively.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
int myArray[6] = {1, 5, -6, 4, -2, 7};
int maxVal = myArray[0];
int minVal = myArray[0];
Serial.print("Size of myArray is: "); Serial.println(sizeof(myArray));
for (int i = 0; i < (sizeof(myArray) / sizeof(myArray[0])); i++) {
if (myArray[i] > maxVal) {
maxVal = myArray[i];
}
if (myArray[i] < minVal) {
minVal = myArray[i];
}
}
Serial.print("The maximum value of the array is: "); Serial.println(maxVal);
Serial.print("The minimum value of the array is: "); Serial.println(minVal);
}
void loop() {
// put your main code here, to run repeatedly:
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
int myArray[6] = {1, 5, -6, 4, -2, 7};
int maxVal = myArray[0];
int minVal = myArray[0];
Serial.print("Size of myArray is: "); Serial.println(sizeof(myArray));
for (int i = 0; i < (sizeof(myArray) / sizeof(myArray[0])); i++) {
maxVal = max(myArray[i],maxVal);
minVal = min(myArray[i],minVal);
}
Serial.print("The maximum value of the array is: ");
Serial.println(maxVal);
Serial.print("The minimum value of the array is: ");
Serial.println(minVal);
}
void loop() {
// put your main code here, to run repeatedly:
}
The Serial Monitor output in both the cases is −
As you can see, the sizeof() function is returning the total number of bytes and not the number of elements in the array (I’m using a board which stores int in 4 bytes). Therefore, within the for loop, the condition has been kept as −
i < (sizeof(myArray) / sizeof(myArray[0]))
|
[
{
"code": null,
"e": 1282,
"s": 1062,
"text": "In order to get the max/ min values of an array in Arduino, we can run a simple for loop. Two implementations are shown below. One uses the max() and min() functions of Arduino, and the other uses the > and < operators."
},
{
"code": null,
"e": 1426,
"s": 1282,
"text": "The max and min functions have the following syntax: max(a,b) and min(a,b), and they return the max and min values out of a and b respectively."
},
{
"code": null,
"e": 2150,
"s": 1426,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n int myArray[6] = {1, 5, -6, 4, -2, 7};\n\n int maxVal = myArray[0];\n int minVal = myArray[0];\n Serial.print(\"Size of myArray is: \"); Serial.println(sizeof(myArray));\n\n for (int i = 0; i < (sizeof(myArray) / sizeof(myArray[0])); i++) {\n if (myArray[i] > maxVal) {\n maxVal = myArray[i];\n }\n if (myArray[i] < minVal) {\n minVal = myArray[i];\n }\n }\n Serial.print(\"The maximum value of the array is: \"); Serial.println(maxVal);\n Serial.print(\"The minimum value of the array is: \"); Serial.println(minVal);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 2811,
"s": 2150,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n int myArray[6] = {1, 5, -6, 4, -2, 7};\n\n int maxVal = myArray[0];\n int minVal = myArray[0];\n Serial.print(\"Size of myArray is: \"); Serial.println(sizeof(myArray));\n\n for (int i = 0; i < (sizeof(myArray) / sizeof(myArray[0])); i++) {\n maxVal = max(myArray[i],maxVal);\n minVal = min(myArray[i],minVal);\n }\n\n Serial.print(\"The maximum value of the array is: \");\nSerial.println(maxVal);\n Serial.print(\"The minimum value of the array is: \");\nSerial.println(minVal);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 2860,
"s": 2811,
"text": "The Serial Monitor output in both the cases is −"
},
{
"code": null,
"e": 3095,
"s": 2860,
"text": "As you can see, the sizeof() function is returning the total number of bytes and not the number of elements in the array (I’m using a board which stores int in 4 bytes). Therefore, within the for loop, the condition has been kept as −"
},
{
"code": null,
"e": 3138,
"s": 3095,
"text": "i < (sizeof(myArray) / sizeof(myArray[0]))"
}
] |
CouchDB - Deleting a Document
|
You can delete a document in CouchDB by sending an HTTP request to the server using DELETE method through cURL utility. Following is the syntax to delete a document.
curl -X DELETE http : // 127.0.0.1:5984 / database name/database id?_rev id
Using −X, we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using Delete method. To delete a database /database_name/database_id/ is not enough. You have to pass the recent revision id through the url. To mention attributes of any data structure "?" is used.
Suppose there is a document in database named my_database with document id 001. To delete this document, you have to get the rev id of the document. Get the document data as shown below.
$ curl -X GET http://127.0.0.1:5984/my_database/001
{
" _id " : " 001 ",
" _rev " : " 2-04d8eac1680d237ca25b68b36b8899d3 " ,
" age " : " 23 "
}
Now specify the revision id of the document to be deleted, id of the document, and database name the document belongs to, as shown below −
$ curl -X DELETE http://127.0.0.1:5984/my_database/001?rev=1-
3fcc78daac7a90803f0a5e383f4f1e1e
{"ok":true,"id":"001","rev":"2-3a561d56de1ce3305d693bd15630bf96"}
To verify whether the document is deleted, try to fetch the document by using the GET method. Since you are fetching a deleted document, this will give you an error message as shown below −
$ curl -X GET http://127.0.0.1:5984/my_database/001
{"error":"not_found","reason":"deleted"}
First of all, verify the documents in the database. Following is the snapshot of the database named tutorials_point.
Here you can observe, the database consists of three documents. To delete any of the documents say 003, do the following −
Click on the document, you will get a page showing the contents of selected document in the form of field-value pairs.
Click on the document, you will get a page showing the contents of selected document in the form of field-value pairs.
This page also contains four options namely Save Document, Add Field, Upload Attachment, Delete Document.
This page also contains four options namely Save Document, Add Field, Upload Attachment, Delete Document.
Click on Delete Document option.
Click on Delete Document option.
You will get a dialog box saying "Are you sure you want to delete this document?" Click on delete, to delete the document.
You will get a dialog box saying "Are you sure you want to delete this document?" Click on delete, to delete the document.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2004,
"s": 1838,
"text": "You can delete a document in CouchDB by sending an HTTP request to the server using DELETE method through cURL utility. Following is the syntax to delete a document."
},
{
"code": null,
"e": 2080,
"s": 2004,
"text": "curl -X DELETE http : // 127.0.0.1:5984 / database name/database id?_rev id"
},
{
"code": null,
"e": 2413,
"s": 2080,
"text": "Using −X, we can specify a custom request method of HTTP we are using, while communicating with the HTTP server. In this case, we are using Delete method. To delete a database /database_name/database_id/ is not enough. You have to pass the recent revision id through the url. To mention attributes of any data structure \"?\" is used."
},
{
"code": null,
"e": 2600,
"s": 2413,
"text": "Suppose there is a document in database named my_database with document id 001. To delete this document, you have to get the rev id of the document. Get the document data as shown below."
},
{
"code": null,
"e": 2753,
"s": 2600,
"text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \" _id \" : \" 001 \",\n \" _rev \" : \" 2-04d8eac1680d237ca25b68b36b8899d3 \" ,\n \" age \" : \" 23 \"\n}"
},
{
"code": null,
"e": 2892,
"s": 2753,
"text": "Now specify the revision id of the document to be deleted, id of the document, and database name the document belongs to, as shown below −"
},
{
"code": null,
"e": 3054,
"s": 2892,
"text": "$ curl -X DELETE http://127.0.0.1:5984/my_database/001?rev=1-\n3fcc78daac7a90803f0a5e383f4f1e1e\n\n{\"ok\":true,\"id\":\"001\",\"rev\":\"2-3a561d56de1ce3305d693bd15630bf96\"}"
},
{
"code": null,
"e": 3244,
"s": 3054,
"text": "To verify whether the document is deleted, try to fetch the document by using the GET method. Since you are fetching a deleted document, this will give you an error message as shown below −"
},
{
"code": null,
"e": 3338,
"s": 3244,
"text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\"error\":\"not_found\",\"reason\":\"deleted\"}\n"
},
{
"code": null,
"e": 3455,
"s": 3338,
"text": "First of all, verify the documents in the database. Following is the snapshot of the database named tutorials_point."
},
{
"code": null,
"e": 3578,
"s": 3455,
"text": "Here you can observe, the database consists of three documents. To delete any of the documents say 003, do the following −"
},
{
"code": null,
"e": 3697,
"s": 3578,
"text": "Click on the document, you will get a page showing the contents of selected document in the form of field-value pairs."
},
{
"code": null,
"e": 3816,
"s": 3697,
"text": "Click on the document, you will get a page showing the contents of selected document in the form of field-value pairs."
},
{
"code": null,
"e": 3922,
"s": 3816,
"text": "This page also contains four options namely Save Document, Add Field, Upload Attachment, Delete Document."
},
{
"code": null,
"e": 4028,
"s": 3922,
"text": "This page also contains four options namely Save Document, Add Field, Upload Attachment, Delete Document."
},
{
"code": null,
"e": 4061,
"s": 4028,
"text": "Click on Delete Document option."
},
{
"code": null,
"e": 4094,
"s": 4061,
"text": "Click on Delete Document option."
},
{
"code": null,
"e": 4217,
"s": 4094,
"text": "You will get a dialog box saying \"Are you sure you want to delete this document?\" Click on delete, to delete the document."
},
{
"code": null,
"e": 4340,
"s": 4217,
"text": "You will get a dialog box saying \"Are you sure you want to delete this document?\" Click on delete, to delete the document."
},
{
"code": null,
"e": 4347,
"s": 4340,
"text": " Print"
},
{
"code": null,
"e": 4358,
"s": 4347,
"text": " Add Notes"
}
] |
How to connect Azure Account using PowerShell?
|
To connect the azure account with PowerShell, we can use the Connect-AZAccount command. If we check the command parameters from the below URL, there are multiple methods we can connect to the azure account but in this article, we will use the simple methods to connect.
Using the Interactive console to connect portal
Using the Interactive console to connect portal
Using DeviceLogin method.
Using DeviceLogin method.
Using Credentials method.
Using Credentials method.
When we use the Connect-AZAccount directly without any parameter, it will open a popup for the azure portal credential.
You need to enter your Azure credentials there.
In this method, Connect-AZAccount uses the parameter -DeviceLogin. Once you run the command, it will show the code on the console window and that code we need to enter on the website,
Connect-AzAccount -DeviceCode
WARNING: To sign in, use a web browser to open the page
https://microsoft.com/devicelogin and enter the code SAYX4512 to authenticate.
As shown in the above output, you need to enter display code on the website,https://Microsoft.com/DeviceLogin and if you are not already authenticated you need to enter Azure credentials there.
You can direct provide Azure user credentials in the Get-Credentials command and use those credentials in Connect-AZAccount .
$creds = Get-Credential
Connect-AZAccount -Credential $creds
Once you enter the correct credentials, your account will be connected. But if your organization has configured the multi-factor authentication this method won’t work and likely it will produce an error.
|
[
{
"code": null,
"e": 1332,
"s": 1062,
"text": "To connect the azure account with PowerShell, we can use the Connect-AZAccount command. If we check the command parameters from the below URL, there are multiple methods we can connect to the azure account but in this article, we will use the simple methods to connect."
},
{
"code": null,
"e": 1380,
"s": 1332,
"text": "Using the Interactive console to connect portal"
},
{
"code": null,
"e": 1428,
"s": 1380,
"text": "Using the Interactive console to connect portal"
},
{
"code": null,
"e": 1454,
"s": 1428,
"text": "Using DeviceLogin method."
},
{
"code": null,
"e": 1480,
"s": 1454,
"text": "Using DeviceLogin method."
},
{
"code": null,
"e": 1506,
"s": 1480,
"text": "Using Credentials method."
},
{
"code": null,
"e": 1532,
"s": 1506,
"text": "Using Credentials method."
},
{
"code": null,
"e": 1652,
"s": 1532,
"text": "When we use the Connect-AZAccount directly without any parameter, it will open a popup for the azure portal credential."
},
{
"code": null,
"e": 1700,
"s": 1652,
"text": "You need to enter your Azure credentials there."
},
{
"code": null,
"e": 1884,
"s": 1700,
"text": "In this method, Connect-AZAccount uses the parameter -DeviceLogin. Once you run the command, it will show the code on the console window and that code we need to enter on the website,"
},
{
"code": null,
"e": 1914,
"s": 1884,
"text": "Connect-AzAccount -DeviceCode"
},
{
"code": null,
"e": 2049,
"s": 1914,
"text": "WARNING: To sign in, use a web browser to open the page\nhttps://microsoft.com/devicelogin and enter the code SAYX4512 to authenticate."
},
{
"code": null,
"e": 2243,
"s": 2049,
"text": "As shown in the above output, you need to enter display code on the website,https://Microsoft.com/DeviceLogin and if you are not already authenticated you need to enter Azure credentials there."
},
{
"code": null,
"e": 2370,
"s": 2243,
"text": "You can direct provide Azure user credentials in the Get-Credentials command and use those credentials in Connect-AZAccount . "
},
{
"code": null,
"e": 2431,
"s": 2370,
"text": "$creds = Get-Credential\nConnect-AZAccount -Credential $creds"
},
{
"code": null,
"e": 2635,
"s": 2431,
"text": "Once you enter the correct credentials, your account will be connected. But if your organization has configured the multi-factor authentication this method won’t work and likely it will produce an error."
}
] |
Practice Questions for Recursion | Set 3 - GeeksforGeeks
|
09 Apr, 2021
Explain the functionality of below recursive functions.
Question 1
C++
C
Java
Python3
C#
Javascript
void fun1(int n){ int i = 0; if (n > 1) fun1(n - 1); for (i = 0; i < n; i++) cout << " * ";} // This code is contributed by shubhamsingh10
void fun1(int n){ int i = 0; if (n > 1) fun1(n-1); for (i = 0; i < n; i++) printf(" * ");}
static void fun1(int n){ int i = 0; if (n > 1) fun1(n - 1); for (i = 0; i < n; i++) System.out.print(" * ");} // This code is contributed by shubhamsingh10
def fun1(n): i = 0 if (n > 1): fun1(n - 1) for i in range(n): print(" * ",end="") # This code is contributed by shubhamsingh10
static void fun1(int n){ int i = 0; if (n > 1) fun1(n-1); for (i = 0; i < n; i++) Console.Write(" * ");} // This code is contributed by shubhamsingh10
<script> function fun1(n){ let i = 0; if (n > 1) fun1(n - 1); for(i = 0; i < n; i++) document.write(" * ");} // This code is contributed by gottumukkalabobby </script>
Answer: Total numbers of stars printed is equal to 1 + 2 + .... (n-2) + (n-1) + n, which is n(n+1)/2.
Question 2
C++
C
Java
Python3
C#
Javascript
#define LIMIT 1000void fun2(int n){ if (n <= 0) return; if (n > LIMIT) return; cout << n <<" "; fun2(2*n); cout << n <<" ";} // This code is contributed by shubhamsingh10
#define LIMIT 1000void fun2(int n){ if (n <= 0) return; if (n > LIMIT) return; printf("%d ", n); fun2(2*n); printf("%d ", n);}
int LIMIT = 1000;void fun2(int n){ if (n <= 0) return; if (n > LIMIT) return; System.out.print(String.format("%d ", n)); fun2(2 * n); System.out.print(String.format("%d ", n));}
LIMIT = 1000def fun2(n): if (n <= 0): return if (n > LIMIT): return print(n, end=" ") fun2(2 * n) print(n, end=" ") # This code is contributed by shubhamsingh10
int LIMIT = 1000void fun2(int n){ if (n <= 0) return; if (n > LIMIT) return; Console.Write(n+" "); fun2(2*n); Console.Write(n+" ");} // This code is contributed by Shubhamsingh10
<script> let LIMIT = 1000;function fun2(n){ if (n <= 0) return; if (n > LIMIT) return; document.write(n + " ")); fun2(2 * n); document.write(n + " "));} // This code is contributed by gottumukkalabobby </script>
Answer: For a positive n, fun2(n) prints the values of n, 2n, 4n, 8n ... while the value is smaller than LIMIT. After printing values in increasing order, it prints same numbers again in reverse order. For example fun2(100) prints 100, 200, 400, 800, 800, 400, 200, 100. If n is negative, the function is returned immediately. Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above.
hoangdang
SHUBHAMSINGH10
ahmadpayan71
gottumukkalabobby
Misc
Recursion
Misc
Recursion
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
Association Rule
Recursive Functions
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Tower of Hanoi
Program for Sum of the digits of a given number
Backtracking | Introduction
|
[
{
"code": null,
"e": 24665,
"s": 24637,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 24722,
"s": 24665,
"text": "Explain the functionality of below recursive functions. "
},
{
"code": null,
"e": 24734,
"s": 24722,
"text": "Question 1 "
},
{
"code": null,
"e": 24738,
"s": 24734,
"text": "C++"
},
{
"code": null,
"e": 24740,
"s": 24738,
"text": "C"
},
{
"code": null,
"e": 24745,
"s": 24740,
"text": "Java"
},
{
"code": null,
"e": 24753,
"s": 24745,
"text": "Python3"
},
{
"code": null,
"e": 24756,
"s": 24753,
"text": "C#"
},
{
"code": null,
"e": 24767,
"s": 24756,
"text": "Javascript"
},
{
"code": "void fun1(int n){ int i = 0; if (n > 1) fun1(n - 1); for (i = 0; i < n; i++) cout << \" * \";} // This code is contributed by shubhamsingh10",
"e": 24922,
"s": 24767,
"text": null
},
{
"code": "void fun1(int n){ int i = 0; if (n > 1) fun1(n-1); for (i = 0; i < n; i++) printf(\" * \");}",
"e": 25028,
"s": 24922,
"text": null
},
{
"code": "static void fun1(int n){ int i = 0; if (n > 1) fun1(n - 1); for (i = 0; i < n; i++) System.out.print(\" * \");} // This code is contributed by shubhamsingh10",
"e": 25201,
"s": 25028,
"text": null
},
{
"code": "def fun1(n): i = 0 if (n > 1): fun1(n - 1) for i in range(n): print(\" * \",end=\"\") # This code is contributed by shubhamsingh10",
"e": 25352,
"s": 25201,
"text": null
},
{
"code": "static void fun1(int n){ int i = 0; if (n > 1) fun1(n-1); for (i = 0; i < n; i++) Console.Write(\" * \");} // This code is contributed by shubhamsingh10",
"e": 25526,
"s": 25352,
"text": null
},
{
"code": "<script> function fun1(n){ let i = 0; if (n > 1) fun1(n - 1); for(i = 0; i < n; i++) document.write(\" * \");} // This code is contributed by gottumukkalabobby </script>",
"e": 25729,
"s": 25526,
"text": null
},
{
"code": null,
"e": 25832,
"s": 25729,
"text": "Answer: Total numbers of stars printed is equal to 1 + 2 + .... (n-2) + (n-1) + n, which is n(n+1)/2. "
},
{
"code": null,
"e": 25843,
"s": 25832,
"text": "Question 2"
},
{
"code": null,
"e": 25847,
"s": 25843,
"text": "C++"
},
{
"code": null,
"e": 25849,
"s": 25847,
"text": "C"
},
{
"code": null,
"e": 25854,
"s": 25849,
"text": "Java"
},
{
"code": null,
"e": 25862,
"s": 25854,
"text": "Python3"
},
{
"code": null,
"e": 25865,
"s": 25862,
"text": "C#"
},
{
"code": null,
"e": 25876,
"s": 25865,
"text": "Javascript"
},
{
"code": "#define LIMIT 1000void fun2(int n){ if (n <= 0) return; if (n > LIMIT) return; cout << n <<\" \"; fun2(2*n); cout << n <<\" \";} // This code is contributed by shubhamsingh10",
"e": 26059,
"s": 25876,
"text": null
},
{
"code": "#define LIMIT 1000void fun2(int n){ if (n <= 0) return; if (n > LIMIT) return; printf(\"%d \", n); fun2(2*n); printf(\"%d \", n);} ",
"e": 26200,
"s": 26059,
"text": null
},
{
"code": "int LIMIT = 1000;void fun2(int n){ if (n <= 0) return; if (n > LIMIT) return; System.out.print(String.format(\"%d \", n)); fun2(2 * n); System.out.print(String.format(\"%d \", n));}",
"e": 26394,
"s": 26200,
"text": null
},
{
"code": "LIMIT = 1000def fun2(n): if (n <= 0): return if (n > LIMIT): return print(n, end=\" \") fun2(2 * n) print(n, end=\" \") # This code is contributed by shubhamsingh10",
"e": 26584,
"s": 26394,
"text": null
},
{
"code": "int LIMIT = 1000void fun2(int n){ if (n <= 0) return; if (n > LIMIT) return; Console.Write(n+\" \"); fun2(2*n); Console.Write(n+\" \");} // This code is contributed by Shubhamsingh10",
"e": 26792,
"s": 26584,
"text": null
},
{
"code": "<script> let LIMIT = 1000;function fun2(n){ if (n <= 0) return; if (n > LIMIT) return; document.write(n + \" \")); fun2(2 * n); document.write(n + \" \"));} // This code is contributed by gottumukkalabobby </script>",
"e": 27034,
"s": 26792,
"text": null
},
{
"code": null,
"e": 27504,
"s": 27034,
"text": "Answer: For a positive n, fun2(n) prints the values of n, 2n, 4n, 8n ... while the value is smaller than LIMIT. After printing values in increasing order, it prints same numbers again in reverse order. For example fun2(100) prints 100, 200, 400, 800, 800, 400, 200, 100. If n is negative, the function is returned immediately. Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above. "
},
{
"code": null,
"e": 27514,
"s": 27504,
"text": "hoangdang"
},
{
"code": null,
"e": 27529,
"s": 27514,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 27542,
"s": 27529,
"text": "ahmadpayan71"
},
{
"code": null,
"e": 27560,
"s": 27542,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 27565,
"s": 27560,
"text": "Misc"
},
{
"code": null,
"e": 27575,
"s": 27565,
"text": "Recursion"
},
{
"code": null,
"e": 27580,
"s": 27575,
"text": "Misc"
},
{
"code": null,
"e": 27590,
"s": 27580,
"text": "Recursion"
},
{
"code": null,
"e": 27595,
"s": 27590,
"text": "Misc"
},
{
"code": null,
"e": 27693,
"s": 27595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27702,
"s": 27693,
"text": "Comments"
},
{
"code": null,
"e": 27715,
"s": 27702,
"text": "Old Comments"
},
{
"code": null,
"e": 27760,
"s": 27715,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 27794,
"s": 27760,
"text": "How to write Regular Expressions?"
},
{
"code": null,
"e": 27875,
"s": 27794,
"text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)"
},
{
"code": null,
"e": 27892,
"s": 27875,
"text": "Association Rule"
},
{
"code": null,
"e": 27912,
"s": 27892,
"text": "Recursive Functions"
},
{
"code": null,
"e": 27972,
"s": 27912,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 28057,
"s": 27972,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 28084,
"s": 28057,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 28132,
"s": 28084,
"text": "Program for Sum of the digits of a given number"
}
] |
Count frequencies of all elements in array in Python using collections module - GeeksforGeeks
|
19 Feb, 2021
Given an unsorted array of n integers which can contains n integers. Count frequency of all elements that are present in array.Examples:
Input : arr[] = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5]
Output : 1 -> 4
2 -> 4
3 -> 2
4 -> 1
5 -> 2
This problem can be solved in many ways, refer Count frequencies of all elements in array link. In Python, we can quickly solve this problem in using Collections module.
# Function to count frequency of each element import collections # it returns a dictionary data structure whose # keys are array elements and values are their # corresponding frequencies {1: 4, 2: 4, 3: 2, # 5: 2, 4: 1}def CountFrequency(arr): return collections.Counter(arr) # Driver functionif __name__ == "__main__": arr = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5] freq = CountFrequency(arr) # iterate dictionary named as freq to print # count of each element for (key, value) in freq.items(): print (key, " -> ", value)
Output:
1 -> 4
2 -> 4
3 -> 2
4 -> 1
5 -> 2
YouTubeGeeksforGeeks502K subscribersCount frequencies of all elements in array in Python using collections module | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:12•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=NT8vn-c81E0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Related Article :Counting the frequencies in a list using dictionary in Python
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anandshaw0101
frequency-counting
Arrays
Python
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24800,
"s": 24772,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 24937,
"s": 24800,
"text": "Given an unsorted array of n integers which can contains n integers. Count frequency of all elements that are present in array.Examples:"
},
{
"code": null,
"e": 25074,
"s": 24937,
"text": "Input : arr[] = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5]\nOutput : 1 -> 4\n 2 -> 4\n 3 -> 2\n 4 -> 1\n 5 -> 2\n"
},
{
"code": null,
"e": 25244,
"s": 25074,
"text": "This problem can be solved in many ways, refer Count frequencies of all elements in array link. In Python, we can quickly solve this problem in using Collections module."
},
{
"code": "# Function to count frequency of each element import collections # it returns a dictionary data structure whose # keys are array elements and values are their # corresponding frequencies {1: 4, 2: 4, 3: 2, # 5: 2, 4: 1}def CountFrequency(arr): return collections.Counter(arr) # Driver functionif __name__ == \"__main__\": arr = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5] freq = CountFrequency(arr) # iterate dictionary named as freq to print # count of each element for (key, value) in freq.items(): print (key, \" -> \", value)",
"e": 25799,
"s": 25244,
"text": null
},
{
"code": null,
"e": 25807,
"s": 25799,
"text": "Output:"
},
{
"code": null,
"e": 25843,
"s": 25807,
"text": "1 -> 4\n2 -> 4\n3 -> 2\n4 -> 1\n5 -> 2\n"
},
{
"code": null,
"e": 26719,
"s": 25843,
"text": "YouTubeGeeksforGeeks502K subscribersCount frequencies of all elements in array in Python using collections module | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:12•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=NT8vn-c81E0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 26798,
"s": 26719,
"text": "Related Article :Counting the frequencies in a list using dictionary in Python"
},
{
"code": null,
"e": 27109,
"s": 26798,
"text": "This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27234,
"s": 27109,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27248,
"s": 27234,
"text": "anandshaw0101"
},
{
"code": null,
"e": 27267,
"s": 27248,
"text": "frequency-counting"
},
{
"code": null,
"e": 27274,
"s": 27267,
"text": "Arrays"
},
{
"code": null,
"e": 27281,
"s": 27274,
"text": "Python"
},
{
"code": null,
"e": 27288,
"s": 27281,
"text": "Arrays"
},
{
"code": null,
"e": 27386,
"s": 27288,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27434,
"s": 27386,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 27478,
"s": 27434,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 27510,
"s": 27478,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27533,
"s": 27510,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 27547,
"s": 27533,
"text": "Linear Search"
},
{
"code": null,
"e": 27575,
"s": 27547,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27625,
"s": 27575,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27647,
"s": 27625,
"text": "Python map() function"
}
] |
Working of Compiler Phases with Example - GeeksforGeeks
|
24 Aug, 2020
In this article, we are going to cover an overview that how we can each compiler phase works individually with the help of an example. Let’s discuss one by one.
Pre-requisite – Introduction to compiler phases
You will see how compiler phases like lexical analyzer, Syntax analyzer, Semantic Analyzer, Intermediate code generator, code Optimizer, and Target code generation. let’s consider an example.
x = a+b*50
The symbol table for the above example is given below. In symbol table are clearly mentions the variable name and variable types.
Now, here you will see how you can execute the compiler phase at each level and how it works.
Lexical Analyzer : In this phase, you will see how you can tokenize the expression.x -> Identifier- (id, 1)
= -> Operator - Assignment
a -> Identifier- (id, 2)
+ -> Operator - Binary Addition
b -> Identifier- (id, 3)
* -> Operator - Multiplication
50 -> Constant - IntegerNow, the final tokenized expression is given below.(id, 1) = (id, 2) + (Id, 3)*50Syntax Analyzer :In this phase, you will see how you can check the syntax after tokenized the expression.S -> Id = E
E -> E+T | T
T -> T*F | F
F -> Id | Integer constantSDT for the above expression is given below.Semantic Analyzer :In this phase, you will see how you can check the type and semantic action for the syntax tree. Given below is the diagram of the semantic analyzer.Intermediate Code Generator :In this phase as an input, you will give a modified parse tree and as output after converting into Intermediate code will generate 3 -Address Code. Given below is an expression of the above-modified parse tree.3 Address Code –t1 = b * 50.0
t2 = a+t1
x = t2Code Optimizer :In this phase, you will see as an input will give 3 address code and as an output, you will see optimize code. Let’s see how it will be converted.t1 = b* 50.0
x = a+ t1Target Code Generator :It is the last phase and In this, you will see how you can convert the final expression into assembly code. so, that it will be easy to understand for the processor.Mul
Add
Store
Lexical Analyzer : In this phase, you will see how you can tokenize the expression.x -> Identifier- (id, 1)
= -> Operator - Assignment
a -> Identifier- (id, 2)
+ -> Operator - Binary Addition
b -> Identifier- (id, 3)
* -> Operator - Multiplication
50 -> Constant - IntegerNow, the final tokenized expression is given below.(id, 1) = (id, 2) + (Id, 3)*50
In this phase, you will see how you can tokenize the expression.
x -> Identifier- (id, 1)
= -> Operator - Assignment
a -> Identifier- (id, 2)
+ -> Operator - Binary Addition
b -> Identifier- (id, 3)
* -> Operator - Multiplication
50 -> Constant - Integer
Now, the final tokenized expression is given below.
(id, 1) = (id, 2) + (Id, 3)*50
Syntax Analyzer :In this phase, you will see how you can check the syntax after tokenized the expression.S -> Id = E
E -> E+T | T
T -> T*F | F
F -> Id | Integer constantSDT for the above expression is given below.
In this phase, you will see how you can check the syntax after tokenized the expression.
S -> Id = E
E -> E+T | T
T -> T*F | F
F -> Id | Integer constant
SDT for the above expression is given below.
Semantic Analyzer :In this phase, you will see how you can check the type and semantic action for the syntax tree. Given below is the diagram of the semantic analyzer.
Intermediate Code Generator :In this phase as an input, you will give a modified parse tree and as output after converting into Intermediate code will generate 3 -Address Code. Given below is an expression of the above-modified parse tree.3 Address Code –t1 = b * 50.0
t2 = a+t1
x = t2
3 Address Code –
t1 = b * 50.0
t2 = a+t1
x = t2
Code Optimizer :In this phase, you will see as an input will give 3 address code and as an output, you will see optimize code. Let’s see how it will be converted.t1 = b* 50.0
x = a+ t1
t1 = b* 50.0
x = a+ t1
Target Code Generator :It is the last phase and In this, you will see how you can convert the final expression into assembly code. so, that it will be easy to understand for the processor.Mul
Add
Store
Mul
Add
Store
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Top down parsing and Bottom up parsing
Loop Optimization in Compiler Design
Why FIRST and FOLLOW in Compiler Design?
Compiler construction tools
Issues in the design of a code generator
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 24445,
"s": 24417,
"text": "\n24 Aug, 2020"
},
{
"code": null,
"e": 24606,
"s": 24445,
"text": "In this article, we are going to cover an overview that how we can each compiler phase works individually with the help of an example. Let’s discuss one by one."
},
{
"code": null,
"e": 24654,
"s": 24606,
"text": "Pre-requisite – Introduction to compiler phases"
},
{
"code": null,
"e": 24846,
"s": 24654,
"text": "You will see how compiler phases like lexical analyzer, Syntax analyzer, Semantic Analyzer, Intermediate code generator, code Optimizer, and Target code generation. let’s consider an example."
},
{
"code": null,
"e": 24857,
"s": 24846,
"text": "x = a+b*50"
},
{
"code": null,
"e": 24987,
"s": 24857,
"text": "The symbol table for the above example is given below. In symbol table are clearly mentions the variable name and variable types."
},
{
"code": null,
"e": 25081,
"s": 24987,
"text": "Now, here you will see how you can execute the compiler phase at each level and how it works."
},
{
"code": null,
"e": 26509,
"s": 25081,
"text": "Lexical Analyzer : In this phase, you will see how you can tokenize the expression.x -> Identifier- (id, 1)\n= -> Operator - Assignment\na -> Identifier- (id, 2)\n+ -> Operator - Binary Addition\nb -> Identifier- (id, 3)\n* -> Operator - Multiplication\n50 -> Constant - IntegerNow, the final tokenized expression is given below.(id, 1) = (id, 2) + (Id, 3)*50Syntax Analyzer :In this phase, you will see how you can check the syntax after tokenized the expression.S -> Id = E\nE -> E+T | T\nT -> T*F | F\nF -> Id | Integer constantSDT for the above expression is given below.Semantic Analyzer :In this phase, you will see how you can check the type and semantic action for the syntax tree. Given below is the diagram of the semantic analyzer.Intermediate Code Generator :In this phase as an input, you will give a modified parse tree and as output after converting into Intermediate code will generate 3 -Address Code. Given below is an expression of the above-modified parse tree.3 Address Code –t1 = b * 50.0\nt2 = a+t1\nx = t2Code Optimizer :In this phase, you will see as an input will give 3 address code and as an output, you will see optimize code. Let’s see how it will be converted.t1 = b* 50.0\nx = a+ t1Target Code Generator :It is the last phase and In this, you will see how you can convert the final expression into assembly code. so, that it will be easy to understand for the processor.Mul\nAdd\nStore"
},
{
"code": null,
"e": 26887,
"s": 26509,
"text": "Lexical Analyzer : In this phase, you will see how you can tokenize the expression.x -> Identifier- (id, 1)\n= -> Operator - Assignment\na -> Identifier- (id, 2)\n+ -> Operator - Binary Addition\nb -> Identifier- (id, 3)\n* -> Operator - Multiplication\n50 -> Constant - IntegerNow, the final tokenized expression is given below.(id, 1) = (id, 2) + (Id, 3)*50"
},
{
"code": null,
"e": 26953,
"s": 26887,
"text": " In this phase, you will see how you can tokenize the expression."
},
{
"code": null,
"e": 27167,
"s": 26953,
"text": "x -> Identifier- (id, 1)\n= -> Operator - Assignment\na -> Identifier- (id, 2)\n+ -> Operator - Binary Addition\nb -> Identifier- (id, 3)\n* -> Operator - Multiplication\n50 -> Constant - Integer"
},
{
"code": null,
"e": 27219,
"s": 27167,
"text": "Now, the final tokenized expression is given below."
},
{
"code": null,
"e": 27250,
"s": 27219,
"text": "(id, 1) = (id, 2) + (Id, 3)*50"
},
{
"code": null,
"e": 27464,
"s": 27250,
"text": "Syntax Analyzer :In this phase, you will see how you can check the syntax after tokenized the expression.S -> Id = E\nE -> E+T | T\nT -> T*F | F\nF -> Id | Integer constantSDT for the above expression is given below."
},
{
"code": null,
"e": 27553,
"s": 27464,
"text": "In this phase, you will see how you can check the syntax after tokenized the expression."
},
{
"code": null,
"e": 27618,
"s": 27553,
"text": "S -> Id = E\nE -> E+T | T\nT -> T*F | F\nF -> Id | Integer constant"
},
{
"code": null,
"e": 27663,
"s": 27618,
"text": "SDT for the above expression is given below."
},
{
"code": null,
"e": 27831,
"s": 27663,
"text": "Semantic Analyzer :In this phase, you will see how you can check the type and semantic action for the syntax tree. Given below is the diagram of the semantic analyzer."
},
{
"code": null,
"e": 28117,
"s": 27831,
"text": "Intermediate Code Generator :In this phase as an input, you will give a modified parse tree and as output after converting into Intermediate code will generate 3 -Address Code. Given below is an expression of the above-modified parse tree.3 Address Code –t1 = b * 50.0\nt2 = a+t1\nx = t2"
},
{
"code": null,
"e": 28134,
"s": 28117,
"text": "3 Address Code –"
},
{
"code": null,
"e": 28165,
"s": 28134,
"text": "t1 = b * 50.0\nt2 = a+t1\nx = t2"
},
{
"code": null,
"e": 28350,
"s": 28165,
"text": "Code Optimizer :In this phase, you will see as an input will give 3 address code and as an output, you will see optimize code. Let’s see how it will be converted.t1 = b* 50.0\nx = a+ t1"
},
{
"code": null,
"e": 28373,
"s": 28350,
"text": "t1 = b* 50.0\nx = a+ t1"
},
{
"code": null,
"e": 28575,
"s": 28373,
"text": "Target Code Generator :It is the last phase and In this, you will see how you can convert the final expression into assembly code. so, that it will be easy to understand for the processor.Mul\nAdd\nStore"
},
{
"code": null,
"e": 28589,
"s": 28575,
"text": "Mul\nAdd\nStore"
},
{
"code": null,
"e": 28605,
"s": 28589,
"text": "Compiler Design"
},
{
"code": null,
"e": 28613,
"s": 28605,
"text": "GATE CS"
},
{
"code": null,
"e": 28711,
"s": 28613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28720,
"s": 28711,
"text": "Comments"
},
{
"code": null,
"e": 28733,
"s": 28720,
"text": "Old Comments"
},
{
"code": null,
"e": 28791,
"s": 28733,
"text": "Difference between Top down parsing and Bottom up parsing"
},
{
"code": null,
"e": 28828,
"s": 28791,
"text": "Loop Optimization in Compiler Design"
},
{
"code": null,
"e": 28869,
"s": 28828,
"text": "Why FIRST and FOLLOW in Compiler Design?"
},
{
"code": null,
"e": 28897,
"s": 28869,
"text": "Compiler construction tools"
},
{
"code": null,
"e": 28938,
"s": 28897,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 28958,
"s": 28938,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 28982,
"s": 28958,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 29009,
"s": 28982,
"text": "Types of Operating Systems"
}
] |
PHP mysqli_refresh() Function
|
The mysqli_refresh() function refreshes the tables, flushes the logs, flushes the caches.
mysqli_refresh($con, options);
con(Mandatory)
This is an object representing a connection to MySQL Server.
options(Mandatory)
This represents the options of the MYSQL refresh command, you can specify multiple options by separating them with commas.
MYSQLI_REFRESH_GRANT
MYSQLI_REFRESH_GRANT
MYSQLI_REFRESH_LOG
MYSQLI_REFRESH_LOG
MYSQLI_REFRESH_TABLES
MYSQLI_REFRESH_TABLES
MYSQLI_REFRESH_HOSTS
MYSQLI_REFRESH_HOSTS
MYSQLI_REFRESH_STATUS
MYSQLI_REFRESH_STATUS
MYSQLI_REFRESH_THREADS
MYSQLI_REFRESH_THREADS
MYSQLI_REFRESH_SLAVE
MYSQLI_REFRESH_SLAVE
MYSQLI_REFRESH_MASTER
MYSQLI_REFRESH_MASTER
The PHP mysqli_refresh() function returns a boolean value which is, true if the refresh operation is successful and, false if not.
This function was first introduced in PHP Version 5 and works works in all the later versions.
Following example demonstrates the usage of the mysqli_refresh() function (in procedural style) −
Assume we have created a table named my_team in the database mydb, as follows −
CREATE TABLE my_team(
ID INT PRIMARY KEY AUTO_INCREMENT,
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
Following example turn the auto commit option off and tries to insert records into this table −
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
//Setting auto commit to true
mysqli_autocommit($con, False);
//Inserting a records into the my_team table
mysqli_query($con, "insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')");
mysqli_query($con, "insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')");
mysqli_query($con, "insert into my_team values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')");
mysqli_query($con, "insert into my_team values(4, 'Virat', 'Kohli', 'Delhi', 'India')");
//Closing the connection
mysqli_close($con);
?>
Since we have turned the auto-commit option off, The records add will not be saved in the database and, if you verify the contents of the table in MySQL, it will be empty as shown below $minus;
mysql> select * from my_team;
Empty set (0.00 sec)
You can flush the records into the table by using the mysqli_query function as shown below $minus;
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
//Setting auto commit to true
mysqli_autocommit($con, False);
//Inserting a records into the my_team table
mysqli_query($con, "insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')");
mysqli_query($con, "insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')");
mysqli_query($con, "insert into my_team values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')");
mysqli_query($con, "insert into my_team values(4, 'Virat', 'Kohli', 'Delhi', 'India')");
mysqli_refresh($con, MYSQLI_REFRESH_TABLES);
//Closing the connection
mysqli_close($con);
Now, if you and verify the contents of the table my_team then, you can see the inserted records as shown below −
mysql> select * from my_team;
+----+------------+------------+----------------+-------------+
| ID | First_Name | Last_Name | Place_Of_Birth | Country |
+----+------------+------------+----------------+-------------+
| 1 | Shikhar | Dhawan | Delhi | India |
| 2 | Jonathan | Trott | CapeTown | SouthAfrica |
| 3 | Kumara | Sangakkara | Matale | Srilanka |
| 4 | Virat | Kohli | Delhi | India |
+----+------------+------------+----------------+-------------+
4 rows in set (0.00 sec)
In object oriented style the syntax of this function is $con->refresh(); Following is the example of this function in object oriented style $minus;
<?php
$con = new mysqli("localhost", "root", "password", "mydb");
//Inserting a records into the players table
$con->query("CREATE TABLE IF NOT EXISTS players(First_Name VARCHAR(255), Last_Name VARCHAR(255), Country VARCHAR(255))");
//Turning the auto-commit false
$con->autocommit(FALSE);
$con->query("insert into players values('Shikhar', 'Dhawan', 'India')");
$con->query("insert into players values('Jonathan', 'Trott', 'SouthAfrica')");
//refreshing the table
$con->refresh(MYSQLI_REFRESH_TABLES);
//Closing the connection
$res = $con -> close();
?>
This will produce following result −
Data Created......
If you observe the contents of the table in the database you can see the inserted records as shown below −
mysql> select * from players;
+------------+-----------+-------------+
| First_Name | Last_Name | Country |
+------------+-----------+-------------+
| Shikhar | Dhawan | India |
| Jonathan | Trott | SouthAfrica |
+------------+-----------+-------------+
2 rows in set (0.00 sec)
<?php
$connection_mysql = mysqli_connect("localhost","username","password","db");
if (mysqli_connect_errno($connection_mysql)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_refresh($connection_mysql,MYSQLI_REFRESH_LOG);
mysqli_close($connection_mysql);
?>
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2847,
"s": 2757,
"text": "The mysqli_refresh() function refreshes the tables, flushes the logs, flushes the caches."
},
{
"code": null,
"e": 2879,
"s": 2847,
"text": "mysqli_refresh($con, options);\n"
},
{
"code": null,
"e": 2894,
"s": 2879,
"text": "con(Mandatory)"
},
{
"code": null,
"e": 2955,
"s": 2894,
"text": "This is an object representing a connection to MySQL Server."
},
{
"code": null,
"e": 2974,
"s": 2955,
"text": "options(Mandatory)"
},
{
"code": null,
"e": 3097,
"s": 2974,
"text": "This represents the options of the MYSQL refresh command, you can specify multiple options by separating them with commas."
},
{
"code": null,
"e": 3118,
"s": 3097,
"text": "MYSQLI_REFRESH_GRANT"
},
{
"code": null,
"e": 3139,
"s": 3118,
"text": "MYSQLI_REFRESH_GRANT"
},
{
"code": null,
"e": 3158,
"s": 3139,
"text": "MYSQLI_REFRESH_LOG"
},
{
"code": null,
"e": 3177,
"s": 3158,
"text": "MYSQLI_REFRESH_LOG"
},
{
"code": null,
"e": 3199,
"s": 3177,
"text": "MYSQLI_REFRESH_TABLES"
},
{
"code": null,
"e": 3221,
"s": 3199,
"text": "MYSQLI_REFRESH_TABLES"
},
{
"code": null,
"e": 3242,
"s": 3221,
"text": "MYSQLI_REFRESH_HOSTS"
},
{
"code": null,
"e": 3263,
"s": 3242,
"text": "MYSQLI_REFRESH_HOSTS"
},
{
"code": null,
"e": 3285,
"s": 3263,
"text": "MYSQLI_REFRESH_STATUS"
},
{
"code": null,
"e": 3307,
"s": 3285,
"text": "MYSQLI_REFRESH_STATUS"
},
{
"code": null,
"e": 3330,
"s": 3307,
"text": "MYSQLI_REFRESH_THREADS"
},
{
"code": null,
"e": 3353,
"s": 3330,
"text": "MYSQLI_REFRESH_THREADS"
},
{
"code": null,
"e": 3374,
"s": 3353,
"text": "MYSQLI_REFRESH_SLAVE"
},
{
"code": null,
"e": 3395,
"s": 3374,
"text": "MYSQLI_REFRESH_SLAVE"
},
{
"code": null,
"e": 3417,
"s": 3395,
"text": "MYSQLI_REFRESH_MASTER"
},
{
"code": null,
"e": 3439,
"s": 3417,
"text": "MYSQLI_REFRESH_MASTER"
},
{
"code": null,
"e": 3570,
"s": 3439,
"text": "The PHP mysqli_refresh() function returns a boolean value which is, true if the refresh operation is successful and, false if not."
},
{
"code": null,
"e": 3665,
"s": 3570,
"text": "This function was first introduced in PHP Version 5 and works works in all the later versions."
},
{
"code": null,
"e": 3763,
"s": 3665,
"text": "Following example demonstrates the usage of the mysqli_refresh() function (in procedural style) −"
},
{
"code": null,
"e": 3844,
"s": 3763,
"text": "Assume we have created a table named my_team in the database mydb, as follows − "
},
{
"code": null,
"e": 4021,
"s": 3844,
"text": "CREATE TABLE my_team(\n ID INT PRIMARY KEY AUTO_INCREMENT,\n First_Name VARCHAR(255), \n Last_Name VARCHAR(255), \n Place_Of_Birth VARCHAR(255), \n Country VARCHAR(255)\n);"
},
{
"code": null,
"e": 4117,
"s": 4021,
"text": "Following example turn the auto commit option off and tries to insert records into this table −"
},
{
"code": null,
"e": 4783,
"s": 4117,
"text": "<?php\n //Creating a connection\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n //Setting auto commit to true\n mysqli_autocommit($con, False);\n\n //Inserting a records into the my_team table\n mysqli_query($con, \"insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')\");\n mysqli_query($con, \"insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')\");\n mysqli_query($con, \"insert into my_team values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')\");\n mysqli_query($con, \"insert into my_team values(4, 'Virat', 'Kohli', 'Delhi', 'India')\");\n\n //Closing the connection\n mysqli_close($con);\n?>"
},
{
"code": null,
"e": 4977,
"s": 4783,
"text": "Since we have turned the auto-commit option off, The records add will not be saved in the database and, if you verify the contents of the table in MySQL, it will be empty as shown below $minus;"
},
{
"code": null,
"e": 5029,
"s": 4977,
"text": "mysql> select * from my_team;\nEmpty set (0.00 sec)\n"
},
{
"code": null,
"e": 5129,
"s": 5029,
"text": "You can flush the records into the table by using the mysqli_query function as shown below $minus; "
},
{
"code": null,
"e": 5839,
"s": 5129,
"text": "<?php\n //Creating a connection\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n //Setting auto commit to true\n mysqli_autocommit($con, False);\n //Inserting a records into the my_team table\n mysqli_query($con, \"insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')\");\n mysqli_query($con, \"insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')\");\n mysqli_query($con, \"insert into my_team values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')\");\n mysqli_query($con, \"insert into my_team values(4, 'Virat', 'Kohli', 'Delhi', 'India')\");\n\n mysqli_refresh($con, MYSQLI_REFRESH_TABLES);\n\n //Closing the connection\n mysqli_close($con);"
},
{
"code": null,
"e": 5952,
"s": 5839,
"text": "Now, if you and verify the contents of the table my_team then, you can see the inserted records as shown below −"
},
{
"code": null,
"e": 6520,
"s": 5952,
"text": "mysql> select * from my_team;\n+----+------------+------------+----------------+-------------+\n| ID | First_Name | Last_Name | Place_Of_Birth | Country |\n+----+------------+------------+----------------+-------------+\n| 1 | Shikhar | Dhawan | Delhi | India |\n| 2 | Jonathan | Trott | CapeTown | SouthAfrica |\n| 3 | Kumara | Sangakkara | Matale | Srilanka |\n| 4 | Virat | Kohli | Delhi | India |\n+----+------------+------------+----------------+-------------+\n4 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 6668,
"s": 6520,
"text": "In object oriented style the syntax of this function is $con->refresh(); Following is the example of this function in object oriented style $minus;"
},
{
"code": null,
"e": 7261,
"s": 6668,
"text": "<?php\n $con = new mysqli(\"localhost\", \"root\", \"password\", \"mydb\");\n\n //Inserting a records into the players table\n $con->query(\"CREATE TABLE IF NOT EXISTS players(First_Name VARCHAR(255), Last_Name VARCHAR(255), Country VARCHAR(255))\");\n\n //Turning the auto-commit false\n $con->autocommit(FALSE);\n\n $con->query(\"insert into players values('Shikhar', 'Dhawan', 'India')\");\n $con->query(\"insert into players values('Jonathan', 'Trott', 'SouthAfrica')\");\n\n //refreshing the table\n $con->refresh(MYSQLI_REFRESH_TABLES);\n\n //Closing the connection\n $res = $con -> close();\n?>"
},
{
"code": null,
"e": 7298,
"s": 7261,
"text": "This will produce following result −"
},
{
"code": null,
"e": 7318,
"s": 7298,
"text": "Data Created......\n"
},
{
"code": null,
"e": 7425,
"s": 7318,
"text": "If you observe the contents of the table in the database you can see the inserted records as shown below −"
},
{
"code": null,
"e": 7726,
"s": 7425,
"text": "mysql> select * from players;\n+------------+-----------+-------------+\n| First_Name | Last_Name | Country |\n+------------+-----------+-------------+\n| Shikhar | Dhawan | India |\n| Jonathan | Trott | SouthAfrica |\n+------------+-----------+-------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 8035,
"s": 7726,
"text": "<?php\n $connection_mysql = mysqli_connect(\"localhost\",\"username\",\"password\",\"db\");\n \n if (mysqli_connect_errno($connection_mysql)){\n echo \"Failed to connect to MySQL: \" . mysqli_connect_error();\n } \n mysqli_refresh($connection_mysql,MYSQLI_REFRESH_LOG);\n mysqli_close($connection_mysql);\n?>"
},
{
"code": null,
"e": 8068,
"s": 8035,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 8084,
"s": 8068,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8117,
"s": 8084,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8128,
"s": 8117,
"text": " Syed Raza"
},
{
"code": null,
"e": 8163,
"s": 8128,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8180,
"s": 8163,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8213,
"s": 8180,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8228,
"s": 8213,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 8263,
"s": 8228,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 8275,
"s": 8263,
"text": " Azaz Patel"
},
{
"code": null,
"e": 8310,
"s": 8275,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8338,
"s": 8310,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 8345,
"s": 8338,
"text": " Print"
},
{
"code": null,
"e": 8356,
"s": 8345,
"text": " Add Notes"
}
] |
Cross Platform NLP GUI on Flutter | by Doug Foo | Towards Data Science
|
I started a project to build a Killer Chat App that leverages a NLP Sentiment Analyzer to perform realtime chat analysis in live chats as per my last article [2]. This article is the R&D phase of the project:
Backend REST service for Sentiment Analysis
Front end Visualizer to see what the model produces
While I could have done this easier in a Python notebook, I will eventually be building the Chat GUI in Flutter anyways so consider it good practice!
After pouring thru a lot of research on variants of NLP Sentiment Analyzers [4], I pulled out a few simple ones to cross-compare:
Vader
TextBlob
Azure Text Analytics (Cognitive Services)
Google Cloud Natural Language API
There are a dozen other libraries and I plan to build my own “Foo NLP”(for the experience) which I will detail in another blog. Eventually, I will add the holy grail BERT [5] but that requires some strategy on how to fine-tune and operate w/o costing me $$$ compute time on Azure.
My REST API has a simple interface:
Input: Text String
Output: Sentiment Score (-1 to +1, ie Negative to Positive scale)
The URL GET format is “http://nlp.foostack.ai/nlp/sa/all?textinput=I love you” which you can test live and see the REST JSON results:
The Python implementation uses the Flask web framework and exposes a single REST API which in turn calls some NLP Sentiment Analyzer libraries or webservices and aggregates the results into the JSON response. Easy and cheap hosting on Azure.
Most everyone knows Flutter is a great Android+iOS cross platform development system, but it also does Web as of mid-2019. The Web support works really well, though has its quirks:
Some 3rd party controls may not work. (Url Launcher, for example, did not work on web until a recent upgrade)
Copy-paste does not work in the Web. Text etc appear like unclickable images or something odd (I need to investigate further)
Dev cycle is a little clunky building & testing web separately
Adding custom web controls or HTML/JS appears difficult
In the end, the Flutter Web is more than enough for FooStack’s customers.
Flutter nests everything in sub-Widgets. Ie, a Column widget to stack items vertically, Padding widgets to add space, Text widget for labels, etc. Makes for an easy lego-like interchangeable system. Just figure out the component to grab and stack it above, below, or inside another widget.
- <Widget build> - Scaffold # shortcut with top,body,footer areas - appBar: - body:Center # centers all subcomponents - Column # aligns subcomponents down the col - Padding - Text # title (Foo Sentiment Analyzer) - ContrainedBox # width controlling container - TextFormField # input box for text to analyze - FlatButton # submit button - Text # title (Results) - Wrap # wrap n-results across and down - Container - Column # single column result table - DataTable # formatted results table - DataColumns # headers - DataCells # rows - floatingButton: # bottom right help button
The other interesting bit of code is how we call the REST service from the GUI. On the Go button, we have an event handler “onPressed” which is mapped to the _submit function.
FlatButton ( child: Text('Go'), color: Colors.blue, textColor: Colors.white, onPressed: _submit,),
We define _submit() as a method that makes an HTTP request to our REST service which returns a JSON. The JSON is remapped to a List of Maps for the GUI to process. There is more to how GUI updates are done automatically that I won’t get into (StatefulWidgets etc).
void _submit() async { // call REST service and extract JSON body var host = 'http://flaskmli.azurewebsites.net/nlp/sa/alldata='; var response = await http.get(host+inputController.text); var resp = response.body; // extract JSON "results" array to a Map (dictionary) // push it onto the new dataList array (list of Maps) Map<String, dynamic> nlps = jsonDecode(resp); List<dynamic> results = nlps['results']; List<Map<String, dynamic>> dataList = []; results.forEach((result) { dataList.add(result); }); // bit of hack here, add input text to _rawContentList _rawContentList.insert(0,[dataList, inputController.text]) inputController.text = ''; // reset focus (clears keyboard on mobile devices) FocusScope.of(context).requestFocus(FocusNode()); setState(() {}); // make GUI refresh from _rawContentList}
All Done! I’m getting better at Flutter, this only took a few days to build.
I can build and publish my Android, Tablet and iPhone app thru Android Studio and Google Play Store [3]. To publish my Flutter Web app, I just run “flutter build web” and manually deploy the web/build artifacts to my webserver (literally copy them to an existing site, in my case to http://foostack.ai/nlp — feel free to test it out).
Thanks for reading.
[1] Prior article on my Flutter NLP Chat Project— https://medium.com/flutter-community/nlp-chat-on-flutter-azure-676aa4768fbb
[2] Prior article on learning Flutter — https://codeburst.io/why-i-a-sr-manager-learned-flutter-8da9a05b2326?source=---------5------------------
[3] Nice article that inspired me — https://towardsdatascience.com/a-practitioners-guide-to-natural-language-processing-part-i-processing-understanding-text-9f4abfd13e72
[4] Some info on BERT and a few other NLP models— https://medium.com/swlh/bert-bidirectional-encoder-representations-from-transformers-c1ba3ef5e2f4
|
[
{
"code": null,
"e": 381,
"s": 172,
"text": "I started a project to build a Killer Chat App that leverages a NLP Sentiment Analyzer to perform realtime chat analysis in live chats as per my last article [2]. This article is the R&D phase of the project:"
},
{
"code": null,
"e": 425,
"s": 381,
"text": "Backend REST service for Sentiment Analysis"
},
{
"code": null,
"e": 477,
"s": 425,
"text": "Front end Visualizer to see what the model produces"
},
{
"code": null,
"e": 627,
"s": 477,
"text": "While I could have done this easier in a Python notebook, I will eventually be building the Chat GUI in Flutter anyways so consider it good practice!"
},
{
"code": null,
"e": 757,
"s": 627,
"text": "After pouring thru a lot of research on variants of NLP Sentiment Analyzers [4], I pulled out a few simple ones to cross-compare:"
},
{
"code": null,
"e": 763,
"s": 757,
"text": "Vader"
},
{
"code": null,
"e": 772,
"s": 763,
"text": "TextBlob"
},
{
"code": null,
"e": 814,
"s": 772,
"text": "Azure Text Analytics (Cognitive Services)"
},
{
"code": null,
"e": 848,
"s": 814,
"text": "Google Cloud Natural Language API"
},
{
"code": null,
"e": 1129,
"s": 848,
"text": "There are a dozen other libraries and I plan to build my own “Foo NLP”(for the experience) which I will detail in another blog. Eventually, I will add the holy grail BERT [5] but that requires some strategy on how to fine-tune and operate w/o costing me $$$ compute time on Azure."
},
{
"code": null,
"e": 1165,
"s": 1129,
"text": "My REST API has a simple interface:"
},
{
"code": null,
"e": 1184,
"s": 1165,
"text": "Input: Text String"
},
{
"code": null,
"e": 1250,
"s": 1184,
"text": "Output: Sentiment Score (-1 to +1, ie Negative to Positive scale)"
},
{
"code": null,
"e": 1384,
"s": 1250,
"text": "The URL GET format is “http://nlp.foostack.ai/nlp/sa/all?textinput=I love you” which you can test live and see the REST JSON results:"
},
{
"code": null,
"e": 1626,
"s": 1384,
"text": "The Python implementation uses the Flask web framework and exposes a single REST API which in turn calls some NLP Sentiment Analyzer libraries or webservices and aggregates the results into the JSON response. Easy and cheap hosting on Azure."
},
{
"code": null,
"e": 1807,
"s": 1626,
"text": "Most everyone knows Flutter is a great Android+iOS cross platform development system, but it also does Web as of mid-2019. The Web support works really well, though has its quirks:"
},
{
"code": null,
"e": 1917,
"s": 1807,
"text": "Some 3rd party controls may not work. (Url Launcher, for example, did not work on web until a recent upgrade)"
},
{
"code": null,
"e": 2043,
"s": 1917,
"text": "Copy-paste does not work in the Web. Text etc appear like unclickable images or something odd (I need to investigate further)"
},
{
"code": null,
"e": 2106,
"s": 2043,
"text": "Dev cycle is a little clunky building & testing web separately"
},
{
"code": null,
"e": 2162,
"s": 2106,
"text": "Adding custom web controls or HTML/JS appears difficult"
},
{
"code": null,
"e": 2236,
"s": 2162,
"text": "In the end, the Flutter Web is more than enough for FooStack’s customers."
},
{
"code": null,
"e": 2526,
"s": 2236,
"text": "Flutter nests everything in sub-Widgets. Ie, a Column widget to stack items vertically, Padding widgets to add space, Text widget for labels, etc. Makes for an easy lego-like interchangeable system. Just figure out the component to grab and stack it above, below, or inside another widget."
},
{
"code": null,
"e": 3307,
"s": 2526,
"text": "- <Widget build> - Scaffold # shortcut with top,body,footer areas - appBar: - body:Center # centers all subcomponents - Column # aligns subcomponents down the col - Padding - Text # title (Foo Sentiment Analyzer) - ContrainedBox # width controlling container - TextFormField # input box for text to analyze - FlatButton # submit button - Text # title (Results) - Wrap # wrap n-results across and down - Container - Column # single column result table - DataTable # formatted results table - DataColumns # headers - DataCells # rows - floatingButton: # bottom right help button"
},
{
"code": null,
"e": 3483,
"s": 3307,
"text": "The other interesting bit of code is how we call the REST service from the GUI. On the Go button, we have an event handler “onPressed” which is mapped to the _submit function."
},
{
"code": null,
"e": 3586,
"s": 3483,
"text": "FlatButton ( child: Text('Go'), color: Colors.blue, textColor: Colors.white, onPressed: _submit,),"
},
{
"code": null,
"e": 3851,
"s": 3586,
"text": "We define _submit() as a method that makes an HTTP request to our REST service which returns a JSON. The JSON is remapped to a List of Maps for the GUI to process. There is more to how GUI updates are done automatically that I won’t get into (StatefulWidgets etc)."
},
{
"code": null,
"e": 4678,
"s": 3851,
"text": "void _submit() async { // call REST service and extract JSON body var host = 'http://flaskmli.azurewebsites.net/nlp/sa/alldata='; var response = await http.get(host+inputController.text); var resp = response.body; // extract JSON \"results\" array to a Map (dictionary) // push it onto the new dataList array (list of Maps) Map<String, dynamic> nlps = jsonDecode(resp); List<dynamic> results = nlps['results']; List<Map<String, dynamic>> dataList = []; results.forEach((result) { dataList.add(result); }); // bit of hack here, add input text to _rawContentList _rawContentList.insert(0,[dataList, inputController.text]) inputController.text = ''; // reset focus (clears keyboard on mobile devices) FocusScope.of(context).requestFocus(FocusNode()); setState(() {}); // make GUI refresh from _rawContentList}"
},
{
"code": null,
"e": 4755,
"s": 4678,
"text": "All Done! I’m getting better at Flutter, this only took a few days to build."
},
{
"code": null,
"e": 5090,
"s": 4755,
"text": "I can build and publish my Android, Tablet and iPhone app thru Android Studio and Google Play Store [3]. To publish my Flutter Web app, I just run “flutter build web” and manually deploy the web/build artifacts to my webserver (literally copy them to an existing site, in my case to http://foostack.ai/nlp — feel free to test it out)."
},
{
"code": null,
"e": 5110,
"s": 5090,
"text": "Thanks for reading."
},
{
"code": null,
"e": 5236,
"s": 5110,
"text": "[1] Prior article on my Flutter NLP Chat Project— https://medium.com/flutter-community/nlp-chat-on-flutter-azure-676aa4768fbb"
},
{
"code": null,
"e": 5381,
"s": 5236,
"text": "[2] Prior article on learning Flutter — https://codeburst.io/why-i-a-sr-manager-learned-flutter-8da9a05b2326?source=---------5------------------"
},
{
"code": null,
"e": 5551,
"s": 5381,
"text": "[3] Nice article that inspired me — https://towardsdatascience.com/a-practitioners-guide-to-natural-language-processing-part-i-processing-understanding-text-9f4abfd13e72"
}
] |
CUDA - Keywords and Thread Organization
|
In this chapter, we will discuss the keywords and thread organisation in CUDA.
The following keywords are used while declaring a CUDA function. As an example, while declaring the kernel, we have to use the __global__ keyword. This provides a hint to the compiler that this function will be executed on the device and can be called from the host.
In this section, we will see a sample CUDA C Code.
void vecAdd(float* A, float* B, float* C,int N) {
int size=N*sizeOf(float);
float *d_A,*d_B,*d_C;
cudaMalloc((void**)&;d_A,size);
This helps in allocating memory on the device for storing vector A. When the function returns, we get a pointer to the starting location of the memory.
cudaMemcpy(d_A,A,size,cudaMemcpyHostToDevice);
Copy data from host to device. The host memory contains the contents of vector A. Now that we have allocated space on the device for storing vector A, we transfer the contents of vector A to the device. At this point, the GPU memory has vector A stored, ready to be operated upon.
cudaMalloc((void**)&;d_B,size);
cudaMemcpy(d_B,B,size,cudaMemcpyHostToDevice);
//Similar to A
cudaMalloc((void**)&;d_C,size);
This helps in allocating the memory on the GPU to store the result vector C. We will cover the Kernel launch statement later.
cudaMemcpy(C,d_C,size,cudaMemcpyDeviceToHost);
After all the threads have finished executing, the result is stored in d_C (d stands for device). The host copies the result back to vector C from d_C.
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_C);
This helps to free up the memory allocated on the device using cudaMalloc().
This is how the above program works −
The above program adds the corresponding elements of two vectors X and Y, and stores the final result in a vector Z.
The above program adds the corresponding elements of two vectors X and Y, and stores the final result in a vector Z.
The device memory is allocated for storing the input vectors (X and Y) and the result vector (Z).
The device memory is allocated for storing the input vectors (X and Y) and the result vector (Z).
cudaMalloc() − This method is used to allocate memory on the host. in two parameters, the address of a pointer to the allocated object, and the size of the allocated object in terms of bytes.
cudaMalloc() − This method is used to allocate memory on the host. in two parameters, the address of a pointer to the allocated object, and the size of the allocated object in terms of bytes.
cudaFree() − This method is used to release objects from device memory. It takes in the pointer to the freed object as parameter.
cudaFree() − This method is used to release objects from device memory. It takes in the pointer to the freed object as parameter.
cudaMemcpy() − This API function is used for memory data transfer. It requires four parameters as input: Pointer to the destination, pointer to the source, amount of data to be copied (in bytes), and the direction of transfer.
cudaMemcpy() − This API function is used for memory data transfer. It requires four parameters as input: Pointer to the destination, pointer to the source, amount of data to be copied (in bytes), and the direction of transfer.
Threads in a grid execute the same kernel function. They have specific coordinates to distinguish themselves from each other and identify the relevant portion of data to process. In CUDA, they are organized in a two-level hierarchy: a grid comprises blocks, and each block comprises threads.
For all threads in a block, the block index is the same. The block index parameter can be accessed using the blockIdx variable inside a kernel. Each thread also has an associated index, and it can be accessed by using threadIdx variable inside the kernel. Note that blockIdx and threadIdx are built-in CUDA variables that are only accessible from inside the kernel.
In a similar fashion, CUDA also has gridDim and blockDim variables that are also built-in. They return the dimensions of the grid and block along a particular axis respectively. As an example, blockDim. x can be used to find how many threads a particular block has along the x axis.
Let us consider an example to understand the concept explained above. Consider an image, which is 76 pixels along the x axis, and 62 pixels along the y axis. Our aim is to convert the image from sRGB to grayscale. We can calculate the total number of pixels by multiplying the number of pixels along the x axis with the total number along the y axis that comes out to be 4712 pixels. Since we are mapping each thread with each pixel, we need a minimum of 4712 pixels. Let us take number of threads in each direction to be a multiple of 4. So, along the x axis, we will need at least 80 threads, and along the y axis, we will need at least 64 threads to process the complete image. We will ensure that the extra threads are not assigned any work.
Thus, we are launching 5120 threads to process a 4712 pixels image. You may ask, why the extra threads? The answer to this question is that keeping the dimensions as multiple of 4 has many benefits that largely offsets any disadvantages that result from launching extra threads. This is explained in a later section).
Now, we have to divide these 5120 threads into grids and blocks. Let each block have 256 threads. If so, then one possibility that of the dimensions each block are: (16,16,1). This means, there are 16 threads in the x direction, 16 in the y direction, and 1 in the z direction. We will be needing 5 blocks in the x direction (since there are 80 threads in total along the x axis), and 4 blocks in y direction (64 threads along the y axis in total), and 1 block in z direction. So, in total, we need 20 blocks. In a nutshell, the grid dimensions are (5,4,1) and the block dimensions are (16,16,1). The programmer needs to specify these values in the program. This is shown in the figure above.
dim3 dimBlock(5,4,1) − To specify the grid dimensions
dim3 dimBlock(5,4,1) − To specify the grid dimensions
dim3 dimGrid(ceil(n/16.0),ceil(m/16.0),1) − To specify the block dimensions.
dim3 dimGrid(ceil(n/16.0),ceil(m/16.0),1) − To specify the block dimensions.
kernelName<<<dimGrid,dimBlock>>>(parameter1, parameter2, ...) − Launch the actual kernel.
kernelName<<<dimGrid,dimBlock>>>(parameter1, parameter2, ...) − Launch the actual kernel.
n is the number of pixels in the x direction, and m is the number of pixels in the y direction. ‘ceil’ is the regular ceiling function. We use it because we never want to end up with less number of blocks than required. dim3 is a data structure, just like an int or a float. dimBlock and dimGrid are variables names. The third statement is the kernel launch statement. ‘kernelName’ is the name of the kernel function, to which we pass the parameters: parameter1, parameter2, and so on. <<<>>> contain the dimensions of the grid and the block.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1971,
"s": 1892,
"text": "In this chapter, we will discuss the keywords and thread organisation in CUDA."
},
{
"code": null,
"e": 2238,
"s": 1971,
"text": "The following keywords are used while declaring a CUDA function. As an example, while declaring the kernel, we have to use the __global__ keyword. This provides a hint to the compiler that this function will be executed on the device and can be called from the host."
},
{
"code": null,
"e": 2289,
"s": 2238,
"text": "In this section, we will see a sample CUDA C Code."
},
{
"code": null,
"e": 2428,
"s": 2289,
"text": "void vecAdd(float* A, float* B, float* C,int N) {\n int size=N*sizeOf(float);\n float *d_A,*d_B,*d_C;\n cudaMalloc((void**)&;d_A,size);"
},
{
"code": null,
"e": 2580,
"s": 2428,
"text": "This helps in allocating memory on the device for storing vector A. When the function returns, we get a pointer to the starting location of the memory."
},
{
"code": null,
"e": 2628,
"s": 2580,
"text": "cudaMemcpy(d_A,A,size,cudaMemcpyHostToDevice);\n"
},
{
"code": null,
"e": 2909,
"s": 2628,
"text": "Copy data from host to device. The host memory contains the contents of vector A. Now that we have allocated space on the device for storing vector A, we transfer the contents of vector A to the device. At this point, the GPU memory has vector A stored, ready to be operated upon."
},
{
"code": null,
"e": 3036,
"s": 2909,
"text": "cudaMalloc((void**)&;d_B,size);\ncudaMemcpy(d_B,B,size,cudaMemcpyHostToDevice);\n\n//Similar to A\ncudaMalloc((void**)&;d_C,size);"
},
{
"code": null,
"e": 3162,
"s": 3036,
"text": "This helps in allocating the memory on the GPU to store the result vector C. We will cover the Kernel launch statement later."
},
{
"code": null,
"e": 3210,
"s": 3162,
"text": "cudaMemcpy(C,d_C,size,cudaMemcpyDeviceToHost);\n"
},
{
"code": null,
"e": 3362,
"s": 3210,
"text": "After all the threads have finished executing, the result is stored in d_C (d stands for device). The host copies the result back to vector C from d_C."
},
{
"code": null,
"e": 3408,
"s": 3362,
"text": "cudaFree(d_A);\ncudaFree(d_B);\ncudaFree(d_C);\n"
},
{
"code": null,
"e": 3485,
"s": 3408,
"text": "This helps to free up the memory allocated on the device using cudaMalloc()."
},
{
"code": null,
"e": 3523,
"s": 3485,
"text": "This is how the above program works −"
},
{
"code": null,
"e": 3640,
"s": 3523,
"text": "The above program adds the corresponding elements of two vectors X and Y, and stores the final result in a vector Z."
},
{
"code": null,
"e": 3757,
"s": 3640,
"text": "The above program adds the corresponding elements of two vectors X and Y, and stores the final result in a vector Z."
},
{
"code": null,
"e": 3855,
"s": 3757,
"text": "The device memory is allocated for storing the input vectors (X and Y) and the result vector (Z)."
},
{
"code": null,
"e": 3953,
"s": 3855,
"text": "The device memory is allocated for storing the input vectors (X and Y) and the result vector (Z)."
},
{
"code": null,
"e": 4145,
"s": 3953,
"text": "cudaMalloc() − This method is used to allocate memory on the host. in two parameters, the address of a pointer to the allocated object, and the size of the allocated object in terms of bytes."
},
{
"code": null,
"e": 4337,
"s": 4145,
"text": "cudaMalloc() − This method is used to allocate memory on the host. in two parameters, the address of a pointer to the allocated object, and the size of the allocated object in terms of bytes."
},
{
"code": null,
"e": 4467,
"s": 4337,
"text": "cudaFree() − This method is used to release objects from device memory. It takes in the pointer to the freed object as parameter."
},
{
"code": null,
"e": 4597,
"s": 4467,
"text": "cudaFree() − This method is used to release objects from device memory. It takes in the pointer to the freed object as parameter."
},
{
"code": null,
"e": 4824,
"s": 4597,
"text": "cudaMemcpy() − This API function is used for memory data transfer. It requires four parameters as input: Pointer to the destination, pointer to the source, amount of data to be copied (in bytes), and the direction of transfer."
},
{
"code": null,
"e": 5051,
"s": 4824,
"text": "cudaMemcpy() − This API function is used for memory data transfer. It requires four parameters as input: Pointer to the destination, pointer to the source, amount of data to be copied (in bytes), and the direction of transfer."
},
{
"code": null,
"e": 5343,
"s": 5051,
"text": "Threads in a grid execute the same kernel function. They have specific coordinates to distinguish themselves from each other and identify the relevant portion of data to process. In CUDA, they are organized in a two-level hierarchy: a grid comprises blocks, and each block comprises threads."
},
{
"code": null,
"e": 5710,
"s": 5343,
"text": "For all threads in a block, the block index is the same. The block index parameter can be accessed using the blockIdx variable inside a kernel. Each thread also has an associated index, and it can be accessed by using threadIdx variable inside the kernel. Note that blockIdx and threadIdx are built-in CUDA variables that are only accessible from inside the kernel."
},
{
"code": null,
"e": 5993,
"s": 5710,
"text": "In a similar fashion, CUDA also has gridDim and blockDim variables that are also built-in. They return the dimensions of the grid and block along a particular axis respectively. As an example, blockDim. x can be used to find how many threads a particular block has along the x axis."
},
{
"code": null,
"e": 6739,
"s": 5993,
"text": "Let us consider an example to understand the concept explained above. Consider an image, which is 76 pixels along the x axis, and 62 pixels along the y axis. Our aim is to convert the image from sRGB to grayscale. We can calculate the total number of pixels by multiplying the number of pixels along the x axis with the total number along the y axis that comes out to be 4712 pixels. Since we are mapping each thread with each pixel, we need a minimum of 4712 pixels. Let us take number of threads in each direction to be a multiple of 4. So, along the x axis, we will need at least 80 threads, and along the y axis, we will need at least 64 threads to process the complete image. We will ensure that the extra threads are not assigned any work."
},
{
"code": null,
"e": 7057,
"s": 6739,
"text": "Thus, we are launching 5120 threads to process a 4712 pixels image. You may ask, why the extra threads? The answer to this question is that keeping the dimensions as multiple of 4 has many benefits that largely offsets any disadvantages that result from launching extra threads. This is explained in a later section)."
},
{
"code": null,
"e": 7750,
"s": 7057,
"text": "Now, we have to divide these 5120 threads into grids and blocks. Let each block have 256 threads. If so, then one possibility that of the dimensions each block are: (16,16,1). This means, there are 16 threads in the x direction, 16 in the y direction, and 1 in the z direction. We will be needing 5 blocks in the x direction (since there are 80 threads in total along the x axis), and 4 blocks in y direction (64 threads along the y axis in total), and 1 block in z direction. So, in total, we need 20 blocks. In a nutshell, the grid dimensions are (5,4,1) and the block dimensions are (16,16,1). The programmer needs to specify these values in the program. This is shown in the figure above."
},
{
"code": null,
"e": 7804,
"s": 7750,
"text": "dim3 dimBlock(5,4,1) − To specify the grid dimensions"
},
{
"code": null,
"e": 7858,
"s": 7804,
"text": "dim3 dimBlock(5,4,1) − To specify the grid dimensions"
},
{
"code": null,
"e": 7935,
"s": 7858,
"text": "dim3 dimGrid(ceil(n/16.0),ceil(m/16.0),1) − To specify the block dimensions."
},
{
"code": null,
"e": 8012,
"s": 7935,
"text": "dim3 dimGrid(ceil(n/16.0),ceil(m/16.0),1) − To specify the block dimensions."
},
{
"code": null,
"e": 8102,
"s": 8012,
"text": "kernelName<<<dimGrid,dimBlock>>>(parameter1, parameter2, ...) − Launch the actual kernel."
},
{
"code": null,
"e": 8192,
"s": 8102,
"text": "kernelName<<<dimGrid,dimBlock>>>(parameter1, parameter2, ...) − Launch the actual kernel."
},
{
"code": null,
"e": 8735,
"s": 8192,
"text": "n is the number of pixels in the x direction, and m is the number of pixels in the y direction. ‘ceil’ is the regular ceiling function. We use it because we never want to end up with less number of blocks than required. dim3 is a data structure, just like an int or a float. dimBlock and dimGrid are variables names. The third statement is the kernel launch statement. ‘kernelName’ is the name of the kernel function, to which we pass the parameters: parameter1, parameter2, and so on. <<<>>> contain the dimensions of the grid and the block."
},
{
"code": null,
"e": 8742,
"s": 8735,
"text": " Print"
},
{
"code": null,
"e": 8753,
"s": 8742,
"text": " Add Notes"
}
] |
C++ Library - <thread>
|
Thread is a sequence of instructions that can be executed concurrently with other such sequences in multithreading environments, while sharing a same address spac.
It is a thread id.
It is a native handle type.
It is used to construct thread.
It is used to destructor thread.
It is a move-assign thread.
It is used to get thread id.
It is used to check if joinable.
It is used to join thread.
It is used to detach thread.
It is used to swap threads.
It is used to get native handle.
It is used to detect hardware concurrency.
It is used to swap threads.
In below example for std::thread.
#include <iostream>
#include <thread>
void foo() {
std::cout << " foo is executing concurrently...\n";
}
void bar(int x) {
std::cout << " bar is executing concurrently...\n";
}
int main() {
std::thread first (foo);
std::thread second (bar,0);
std::cout << "main, foo and bar now execute concurrently...\n";
first.join();
second.join();
std::cout << "foo and bar completed.\n";
return 0;
}
The output should be like this −
main, foo and bar now execute concurrently...
bar is executing concurrently...
foo is executing concurrently...
foo and bar completed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2767,
"s": 2603,
"text": "Thread is a sequence of instructions that can be executed concurrently with other such sequences in multithreading environments, while sharing a same address spac."
},
{
"code": null,
"e": 2786,
"s": 2767,
"text": "It is a thread id."
},
{
"code": null,
"e": 2814,
"s": 2786,
"text": "It is a native handle type."
},
{
"code": null,
"e": 2846,
"s": 2814,
"text": "It is used to construct thread."
},
{
"code": null,
"e": 2879,
"s": 2846,
"text": "It is used to destructor thread."
},
{
"code": null,
"e": 2907,
"s": 2879,
"text": "It is a move-assign thread."
},
{
"code": null,
"e": 2936,
"s": 2907,
"text": "It is used to get thread id."
},
{
"code": null,
"e": 2969,
"s": 2936,
"text": "It is used to check if joinable."
},
{
"code": null,
"e": 2996,
"s": 2969,
"text": "It is used to join thread."
},
{
"code": null,
"e": 3025,
"s": 2996,
"text": "It is used to detach thread."
},
{
"code": null,
"e": 3053,
"s": 3025,
"text": "It is used to swap threads."
},
{
"code": null,
"e": 3086,
"s": 3053,
"text": "It is used to get native handle."
},
{
"code": null,
"e": 3129,
"s": 3086,
"text": "It is used to detect hardware concurrency."
},
{
"code": null,
"e": 3157,
"s": 3129,
"text": "It is used to swap threads."
},
{
"code": null,
"e": 3191,
"s": 3157,
"text": "In below example for std::thread."
},
{
"code": null,
"e": 3614,
"s": 3191,
"text": "#include <iostream>\n#include <thread>\n\nvoid foo() {\n std::cout << \" foo is executing concurrently...\\n\";\n}\n\nvoid bar(int x) {\n std::cout << \" bar is executing concurrently...\\n\";\n}\n\nint main() {\n std::thread first (foo);\n std::thread second (bar,0);\n\n std::cout << \"main, foo and bar now execute concurrently...\\n\";\n\n first.join();\n second.join();\n\n std::cout << \"foo and bar completed.\\n\";\n\n return 0;\n}"
},
{
"code": null,
"e": 3647,
"s": 3614,
"text": "The output should be like this −"
},
{
"code": null,
"e": 3785,
"s": 3647,
"text": "main, foo and bar now execute concurrently...\n bar is executing concurrently...\n foo is executing concurrently...\nfoo and bar completed.\n"
},
{
"code": null,
"e": 3792,
"s": 3785,
"text": " Print"
},
{
"code": null,
"e": 3803,
"s": 3792,
"text": " Add Notes"
}
] |
How to print object array in JavaScript?
|
To print object array in JavaScript, use JSON.stringify() method.
You can try to run the following code to display object array −
Live Demo
<!DOCTYPE html>
<html>
<body>
<pre id="test"></pre>
<script>
var data = [{
date: new Date(2017, 11, 25),
value: 10
}, {
date: new Date(2017, 11, 30),
value: 20
}];
document.getElementById('test').innerHTML = JSON.stringify(data, null, 4);
</script>
</body>
</html>
[
{
"date": "2017-12-24T18:30:00.000Z",
"value": 10
},
{
"date": "2017-12-29T18:30:00.000Z",
"value": 20
}
]
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "To print object array in JavaScript, use JSON.stringify() method."
},
{
"code": null,
"e": 1192,
"s": 1128,
"text": "You can try to run the following code to display object array −"
},
{
"code": null,
"e": 1202,
"s": 1192,
"text": "Live Demo"
},
{
"code": null,
"e": 1575,
"s": 1202,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <pre id=\"test\"></pre>\n <script>\n var data = [{\n date: new Date(2017, 11, 25),\n value: 10\n }, {\n date: new Date(2017, 11, 30),\n value: 20\n }];\n document.getElementById('test').innerHTML = JSON.stringify(data, null, 4);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1750,
"s": 1575,
"text": "[ \n { \n \"date\": \"2017-12-24T18:30:00.000Z\",\n \"value\": 10\n }, \n { \n \"date\": \"2017-12-29T18:30:00.000Z\", \n \"value\": 20 \n }\n]"
}
] |
How to check if a variable is boolean in JavaScript?
|
To check if a variable is Boolean in JavaScript, use the typeof operator.
You can try to run the following code to check for a Boolean variable −
Live Demo
<html>
<head>
<title>JavaScript Boolean</title>
</head>
<body>
<script>
var answer = true;
if(typeof(answer) === "boolean") {
alert("Boolean");
} else {
alert("Not a Boolean");
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1136,
"s": 1062,
"text": "To check if a variable is Boolean in JavaScript, use the typeof operator."
},
{
"code": null,
"e": 1208,
"s": 1136,
"text": "You can try to run the following code to check for a Boolean variable −"
},
{
"code": null,
"e": 1218,
"s": 1208,
"text": "Live Demo"
},
{
"code": null,
"e": 1514,
"s": 1218,
"text": "<html>\n <head>\n <title>JavaScript Boolean</title>\n </head>\n\n <body>\n <script>\n var answer = true;\n if(typeof(answer) === \"boolean\") {\n alert(\"Boolean\");\n } else {\n alert(\"Not a Boolean\");\n }\n </script>\n </body>\n</html>"
}
] |
Longest alternating subsequence in terms of positive and negative integers - GeeksforGeeks
|
31 May, 2021
Given an array arr[] of positive and negative numbers only. The task is to find the length of the longest alternating (means negative-positive-negative or positive-negative-positive) subsequence present in the array.
Examples:
Input: arr[] = {-4, 3, -5, 9, 10, 12, 2, -1} Output: 5 Explanation: The longest sequence is {-4, 3, -5, 9, -1}, which is of length 5. There can be many more subsequences of this length.
Input: arr[] = {10, 12, 2, -1} Output: 2 Explanation: The longest sequence is {10, -1}, which is 2. There can be many more subsequences of this length.
Approach: This problem can be solved using Dynamic Programming. It is a variation Longest Increasing Subsequence(LIS). The following are the steps:
For including and excluding an element in the given array arr[] for LAS(Longest Alternative Subsequence), a variable pos is used, when pos = true means the current element needs to be positive and if pos = false then current element needs to be negative.If we include the current element, change the value of pos and recurr for the next element because we need the next element of the opposite to the previously included element.Now LAS[i][pos] can be recursively written as: Base case: If the index called recursively is greater than the last element, then return 0, as there is no such element left to form LAS and if LAS[i][pos] is calculated, then return the value.
For including and excluding an element in the given array arr[] for LAS(Longest Alternative Subsequence), a variable pos is used, when pos = true means the current element needs to be positive and if pos = false then current element needs to be negative.
If we include the current element, change the value of pos and recurr for the next element because we need the next element of the opposite to the previously included element.
Now LAS[i][pos] can be recursively written as: Base case: If the index called recursively is greater than the last element, then return 0, as there is no such element left to form LAS and if LAS[i][pos] is calculated, then return the value.
Base case: If the index called recursively is greater than the last element, then return 0, as there is no such element left to form LAS and if LAS[i][pos] is calculated, then return the value.
if(i == N) { return 0; } if(LAS[i][pos]) { return LAS[i][pos]; }
Recursive call: If the base case is not met, then recursively call when current element is included and excluded, then find the maximum of those to find LAS at that index.
LAS[i][pos] = Longest Alternating Subsequence at index i by including or excluding that element for the value of pos, LAS[i][pos] = max(1 + recursive_function(i+1, pos), recursive_function(i+1, pos));
Return statement: At each recursive call(except the base case), return the value of LAS[i][pos].
return LAS[i][pos];
The LAS for the given array arr[] is the maximum of LAS[0][0] and LAS[0][1].
The LAS for the given array arr[] is the maximum of LAS[0][0] and LAS[0][1].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the// length of longest alternate// subsequence#include <bits/stdc++.h>using namespace std; // LAS[i][pos] array to find// the length of LAS till// index i by including or// excluding element arr[i]// on the basis of value of posint LAS[1000][2] = { false }; int solve(int arr[], int n, int i, bool pos){ // Base Case if (i == n) return 0; if (LAS[i][pos]) return LAS[i][pos]; int inc = 0, exc = 0; // If current element is // positive and pos is true // Include the current element // and change pos to false if (arr[i] > 0 && pos == true) { pos = false; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // negative and pos is false // Include the current element // and change pos to true else if (arr[i] < 0 && pos == false) { pos = true; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // excluded, reccur for // next iteration exc = solve(arr, n, i + 1, pos); LAS[i][pos] = max(inc, exc); return LAS[i][pos];} // Driver's Codeint main(){ int arr[] = { -1, 2, 3, 4, 5, -6, 8, -99 }; int n = sizeof(arr) / sizeof(arr[0]); // Print LAS cout << max(solve(arr, n, 0, 0), solve(arr, n, 0, 1));}
// Java program to find the// length of longest alternate// subsequenceclass GFG { // LAS[i][pos] array to find// the length of LAS till// index i by including or// excluding element arr[i]// on the basis of value of posstatic int LAS[][] = new int[1000][2]; static int solve(int arr[], int n, int i,int pos){ // Base Case if (i == n) return 0; if (LAS[i][pos]== 1) return LAS[i][pos]; int inc = 0, exc = 0; // If current element is // positive and pos is 1 // Include the current element // and change pos to 0 if (arr[i] > 0 && pos == 1) { pos = 0; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // negative and pos is o // Include the current element // and change pos to 1 else if (arr[i] < 0 && pos == 0) { pos = 1; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // excluded, reccur for // next iteration exc = solve(arr, n, i + 1, pos); LAS[i][pos] = Math.max(inc, exc); return LAS[i][pos];} // Driver's Codepublic static void main (String[] args){ int arr[] = { -1, 2, 3, 4, 5, -6, 8, -99 }; int n = arr.length; // Print LAS System.out.println(Math.max(solve(arr, n, 0, 0),solve(arr, n, 0, 1)));}} // This code is contributed by AnkitRai01
# Python3 program to find the# length of longest alternate# subsequenceimport numpy as np # LAS[i][pos] array to find# the length of LAS till# index i by including or# excluding element arr[i]# on the basis of value of posLAS = np.zeros((1000, 2)) for i in range(1000) : for j in range(2) : LAS[i][j] = False def solve(arr, n, i, pos) : # Base Case if (i == n) : return 0; if (LAS[i][pos]) : return LAS[i][pos]; inc = 0; exc = 0; # If current element is # positive and pos is true # Include the current element # and change pos to false if (arr[i] > 0 and pos == True) : pos = False; # Recurr for the next # iteration inc = 1 + solve(arr, n, i + 1, pos); # If current element is # negative and pos is false # Include the current element # and change pos to true elif (arr[i] < 0 and pos == False) : pos = True; # Recurr for the next # iteration inc = 1 + solve(arr, n, i + 1, pos); # If current element is # excluded, reccur for # next iteration exc = solve(arr, n, i + 1, pos); LAS[i][pos] = max(inc, exc); return LAS[i][pos]; # Driver's Codeif __name__ == "__main__" : arr = [ -1, 2, 3, 4, 5, -6, 8, -99 ]; n = len(arr); # Print LAS print(max(solve(arr, n, 0, 0), solve(arr, n, 0, 1))); # This code is contributed by AnkitRai01
// C# program to find the// length of longest alternate// subsequence using System; public class GFG { // LAS[i][pos] array to find// the length of LAS till// index i by including or// excluding element arr[i]// on the basis of value of posstatic int [,]LAS = new int[1000,2]; static int solve(int []arr, int n, int i,int pos){ // Base Case if (i == n) return 0; if (LAS[i,pos]== 1) return LAS[i,pos]; int inc = 0, exc = 0; // If current element is // positive and pos is 1 // Include the current element // and change pos to 0 if (arr[i] > 0 && pos == 1) { pos = 0; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // negative and pos is o // Include the current element // and change pos to 1 else if (arr[i] < 0 && pos == 0) { pos = 1; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // excluded, reccur for // next iteration exc = solve(arr, n, i + 1, pos); LAS[i,pos] = Math.Max(inc, exc); return LAS[i,pos];} // Driver's Codepublic static void Main(){ int []arr = { -1, 2, 3, 4, 5, -6, 8, -99 }; int n = arr.Length; // Print LAS Console.WriteLine(Math.Max(solve(arr, n, 0, 0),solve(arr, n, 0, 1)));}} // This code is contributed by AnkitRai01
<script>// Javascript program to find the// length of longest alternate// subsequence // LAS[i][pos] array to find// the length of LAS till// index i by including or// excluding element arr[i]// on the basis of value of poslet LAS = new Array(); for(let i = 0; i < 1000; i++){ let temp = new Array() for(let j = 0; j < 2; j++){ temp.push([]) } LAS.push(temp);} for(let i = 0; i < 1000; i++){ for(let j = 0; j < 2; j++){ LAS[i][j] = false }} function solve(arr, n, i, pos){ // Base Case if (i == n) return 0; if (LAS[i][pos]) return LAS[i][pos]; let inc = 0, exc = 0; // If current element is // positive and pos is true // Include the current element // and change pos to false if (arr[i] > 0 && pos == true) { pos = false; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // negative and pos is false // Include the current element // and change pos to true else if (arr[i] < 0 && pos == false) { pos = true; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // excluded, reccur for // next iteration exc = solve(arr, n, i + 1, pos); LAS[i][pos] = Math.max(inc, exc); return LAS[i][pos];} // Driver's Code let arr = [ -1, 2, 3, 4, 5, -6, 8, -99 ];let n = arr.length; // Print LASdocument.write(Math.max(solve(arr, n, 0, 0), solve(arr, n, 0, 1))); // This code is contributed by _saurabh_jaiswal</script>
5
Time Complexity: O(N) where N is the length of the array.
ankthon
_saurabh_jaiswal
Arrays
Dynamic Programming
Recursion
Arrays
Dynamic Programming
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Longest Increasing Subsequence | DP-3
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 24549,
"s": 24521,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 24767,
"s": 24549,
"text": "Given an array arr[] of positive and negative numbers only. The task is to find the length of the longest alternating (means negative-positive-negative or positive-negative-positive) subsequence present in the array. "
},
{
"code": null,
"e": 24778,
"s": 24767,
"text": "Examples: "
},
{
"code": null,
"e": 24964,
"s": 24778,
"text": "Input: arr[] = {-4, 3, -5, 9, 10, 12, 2, -1} Output: 5 Explanation: The longest sequence is {-4, 3, -5, 9, -1}, which is of length 5. There can be many more subsequences of this length."
},
{
"code": null,
"e": 25117,
"s": 24964,
"text": "Input: arr[] = {10, 12, 2, -1} Output: 2 Explanation: The longest sequence is {10, -1}, which is 2. There can be many more subsequences of this length. "
},
{
"code": null,
"e": 25266,
"s": 25117,
"text": "Approach: This problem can be solved using Dynamic Programming. It is a variation Longest Increasing Subsequence(LIS). The following are the steps: "
},
{
"code": null,
"e": 25937,
"s": 25266,
"text": "For including and excluding an element in the given array arr[] for LAS(Longest Alternative Subsequence), a variable pos is used, when pos = true means the current element needs to be positive and if pos = false then current element needs to be negative.If we include the current element, change the value of pos and recurr for the next element because we need the next element of the opposite to the previously included element.Now LAS[i][pos] can be recursively written as: Base case: If the index called recursively is greater than the last element, then return 0, as there is no such element left to form LAS and if LAS[i][pos] is calculated, then return the value. "
},
{
"code": null,
"e": 26192,
"s": 25937,
"text": "For including and excluding an element in the given array arr[] for LAS(Longest Alternative Subsequence), a variable pos is used, when pos = true means the current element needs to be positive and if pos = false then current element needs to be negative."
},
{
"code": null,
"e": 26368,
"s": 26192,
"text": "If we include the current element, change the value of pos and recurr for the next element because we need the next element of the opposite to the previously included element."
},
{
"code": null,
"e": 26610,
"s": 26368,
"text": "Now LAS[i][pos] can be recursively written as: Base case: If the index called recursively is greater than the last element, then return 0, as there is no such element left to form LAS and if LAS[i][pos] is calculated, then return the value. "
},
{
"code": null,
"e": 26805,
"s": 26610,
"text": "Base case: If the index called recursively is greater than the last element, then return 0, as there is no such element left to form LAS and if LAS[i][pos] is calculated, then return the value. "
},
{
"code": null,
"e": 26871,
"s": 26805,
"text": "if(i == N) { return 0; } if(LAS[i][pos]) { return LAS[i][pos]; } "
},
{
"code": null,
"e": 27045,
"s": 26871,
"text": "Recursive call: If the base case is not met, then recursively call when current element is included and excluded, then find the maximum of those to find LAS at that index. "
},
{
"code": null,
"e": 27248,
"s": 27045,
"text": "LAS[i][pos] = Longest Alternating Subsequence at index i by including or excluding that element for the value of pos, LAS[i][pos] = max(1 + recursive_function(i+1, pos), recursive_function(i+1, pos)); "
},
{
"code": null,
"e": 27347,
"s": 27248,
"text": "Return statement: At each recursive call(except the base case), return the value of LAS[i][pos]. "
},
{
"code": null,
"e": 27369,
"s": 27347,
"text": "return LAS[i][pos]; "
},
{
"code": null,
"e": 27446,
"s": 27369,
"text": "The LAS for the given array arr[] is the maximum of LAS[0][0] and LAS[0][1]."
},
{
"code": null,
"e": 27523,
"s": 27446,
"text": "The LAS for the given array arr[] is the maximum of LAS[0][0] and LAS[0][1]."
},
{
"code": null,
"e": 27575,
"s": 27523,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27579,
"s": 27575,
"text": "C++"
},
{
"code": null,
"e": 27584,
"s": 27579,
"text": "Java"
},
{
"code": null,
"e": 27592,
"s": 27584,
"text": "Python3"
},
{
"code": null,
"e": 27595,
"s": 27592,
"text": "C#"
},
{
"code": null,
"e": 27606,
"s": 27595,
"text": "Javascript"
},
{
"code": "// C++ program to find the// length of longest alternate// subsequence#include <bits/stdc++.h>using namespace std; // LAS[i][pos] array to find// the length of LAS till// index i by including or// excluding element arr[i]// on the basis of value of posint LAS[1000][2] = { false }; int solve(int arr[], int n, int i, bool pos){ // Base Case if (i == n) return 0; if (LAS[i][pos]) return LAS[i][pos]; int inc = 0, exc = 0; // If current element is // positive and pos is true // Include the current element // and change pos to false if (arr[i] > 0 && pos == true) { pos = false; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // negative and pos is false // Include the current element // and change pos to true else if (arr[i] < 0 && pos == false) { pos = true; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // excluded, reccur for // next iteration exc = solve(arr, n, i + 1, pos); LAS[i][pos] = max(inc, exc); return LAS[i][pos];} // Driver's Codeint main(){ int arr[] = { -1, 2, 3, 4, 5, -6, 8, -99 }; int n = sizeof(arr) / sizeof(arr[0]); // Print LAS cout << max(solve(arr, n, 0, 0), solve(arr, n, 0, 1));}",
"e": 29016,
"s": 27606,
"text": null
},
{
"code": "// Java program to find the// length of longest alternate// subsequenceclass GFG { // LAS[i][pos] array to find// the length of LAS till// index i by including or// excluding element arr[i]// on the basis of value of posstatic int LAS[][] = new int[1000][2]; static int solve(int arr[], int n, int i,int pos){ // Base Case if (i == n) return 0; if (LAS[i][pos]== 1) return LAS[i][pos]; int inc = 0, exc = 0; // If current element is // positive and pos is 1 // Include the current element // and change pos to 0 if (arr[i] > 0 && pos == 1) { pos = 0; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // negative and pos is o // Include the current element // and change pos to 1 else if (arr[i] < 0 && pos == 0) { pos = 1; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // excluded, reccur for // next iteration exc = solve(arr, n, i + 1, pos); LAS[i][pos] = Math.max(inc, exc); return LAS[i][pos];} // Driver's Codepublic static void main (String[] args){ int arr[] = { -1, 2, 3, 4, 5, -6, 8, -99 }; int n = arr.length; // Print LAS System.out.println(Math.max(solve(arr, n, 0, 0),solve(arr, n, 0, 1)));}} // This code is contributed by AnkitRai01",
"e": 30432,
"s": 29016,
"text": null
},
{
"code": "# Python3 program to find the# length of longest alternate# subsequenceimport numpy as np # LAS[i][pos] array to find# the length of LAS till# index i by including or# excluding element arr[i]# on the basis of value of posLAS = np.zeros((1000, 2)) for i in range(1000) : for j in range(2) : LAS[i][j] = False def solve(arr, n, i, pos) : # Base Case if (i == n) : return 0; if (LAS[i][pos]) : return LAS[i][pos]; inc = 0; exc = 0; # If current element is # positive and pos is true # Include the current element # and change pos to false if (arr[i] > 0 and pos == True) : pos = False; # Recurr for the next # iteration inc = 1 + solve(arr, n, i + 1, pos); # If current element is # negative and pos is false # Include the current element # and change pos to true elif (arr[i] < 0 and pos == False) : pos = True; # Recurr for the next # iteration inc = 1 + solve(arr, n, i + 1, pos); # If current element is # excluded, reccur for # next iteration exc = solve(arr, n, i + 1, pos); LAS[i][pos] = max(inc, exc); return LAS[i][pos]; # Driver's Codeif __name__ == \"__main__\" : arr = [ -1, 2, 3, 4, 5, -6, 8, -99 ]; n = len(arr); # Print LAS print(max(solve(arr, n, 0, 0), solve(arr, n, 0, 1))); # This code is contributed by AnkitRai01",
"e": 31834,
"s": 30432,
"text": null
},
{
"code": "// C# program to find the// length of longest alternate// subsequence using System; public class GFG { // LAS[i][pos] array to find// the length of LAS till// index i by including or// excluding element arr[i]// on the basis of value of posstatic int [,]LAS = new int[1000,2]; static int solve(int []arr, int n, int i,int pos){ // Base Case if (i == n) return 0; if (LAS[i,pos]== 1) return LAS[i,pos]; int inc = 0, exc = 0; // If current element is // positive and pos is 1 // Include the current element // and change pos to 0 if (arr[i] > 0 && pos == 1) { pos = 0; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // negative and pos is o // Include the current element // and change pos to 1 else if (arr[i] < 0 && pos == 0) { pos = 1; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // excluded, reccur for // next iteration exc = solve(arr, n, i + 1, pos); LAS[i,pos] = Math.Max(inc, exc); return LAS[i,pos];} // Driver's Codepublic static void Main(){ int []arr = { -1, 2, 3, 4, 5, -6, 8, -99 }; int n = arr.Length; // Print LAS Console.WriteLine(Math.Max(solve(arr, n, 0, 0),solve(arr, n, 0, 1)));}} // This code is contributed by AnkitRai01",
"e": 33249,
"s": 31834,
"text": null
},
{
"code": "<script>// Javascript program to find the// length of longest alternate// subsequence // LAS[i][pos] array to find// the length of LAS till// index i by including or// excluding element arr[i]// on the basis of value of poslet LAS = new Array(); for(let i = 0; i < 1000; i++){ let temp = new Array() for(let j = 0; j < 2; j++){ temp.push([]) } LAS.push(temp);} for(let i = 0; i < 1000; i++){ for(let j = 0; j < 2; j++){ LAS[i][j] = false }} function solve(arr, n, i, pos){ // Base Case if (i == n) return 0; if (LAS[i][pos]) return LAS[i][pos]; let inc = 0, exc = 0; // If current element is // positive and pos is true // Include the current element // and change pos to false if (arr[i] > 0 && pos == true) { pos = false; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // negative and pos is false // Include the current element // and change pos to true else if (arr[i] < 0 && pos == false) { pos = true; // Recurr for the next // iteration inc = 1 + solve(arr, n, i + 1, pos); } // If current element is // excluded, reccur for // next iteration exc = solve(arr, n, i + 1, pos); LAS[i][pos] = Math.max(inc, exc); return LAS[i][pos];} // Driver's Code let arr = [ -1, 2, 3, 4, 5, -6, 8, -99 ];let n = arr.length; // Print LASdocument.write(Math.max(solve(arr, n, 0, 0), solve(arr, n, 0, 1))); // This code is contributed by _saurabh_jaiswal</script>",
"e": 34844,
"s": 33249,
"text": null
},
{
"code": null,
"e": 34846,
"s": 34844,
"text": "5"
},
{
"code": null,
"e": 34907,
"s": 34848,
"text": "Time Complexity: O(N) where N is the length of the array. "
},
{
"code": null,
"e": 34915,
"s": 34907,
"text": "ankthon"
},
{
"code": null,
"e": 34932,
"s": 34915,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 34939,
"s": 34932,
"text": "Arrays"
},
{
"code": null,
"e": 34959,
"s": 34939,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34969,
"s": 34959,
"text": "Recursion"
},
{
"code": null,
"e": 34976,
"s": 34969,
"text": "Arrays"
},
{
"code": null,
"e": 34996,
"s": 34976,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 35006,
"s": 34996,
"text": "Recursion"
},
{
"code": null,
"e": 35104,
"s": 35006,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35113,
"s": 35104,
"text": "Comments"
},
{
"code": null,
"e": 35126,
"s": 35113,
"text": "Old Comments"
},
{
"code": null,
"e": 35174,
"s": 35126,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 35218,
"s": 35174,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 35241,
"s": 35218,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 35273,
"s": 35241,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 35287,
"s": 35273,
"text": "Linear Search"
},
{
"code": null,
"e": 35316,
"s": 35287,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 35350,
"s": 35316,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 35388,
"s": 35350,
"text": "Longest Increasing Subsequence | DP-3"
},
{
"code": null,
"e": 35419,
"s": 35388,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
Tag Sort (To get both sorted and original)
|
14 Jun, 2022
This is not a new sorting algorithm, but an idea when we need to avoid swapping of large objects or need to access elements of a large array in both original and sorted orders.A common sorting task is to sort elements of an array using a sorting algorithm like Quick Sort, Bubble Sort.. etc, but there may be times when we need to keep the actual array in tact and use a “tagged” array to store the correct positioning of the array when it is sorted. When we want to access elements in sorted way, we can use this “tagged” array.
Why to use Tag Sort?
When we are operating on large array of objects, it might be too costly to swap these large object. After all its about the disk swaps and we want to minimize it!
Tag Sort allows sorting an integer array after tagging it with original object.
In turn, we only swap the tag array integers instead of large array of objects.
The actual elements are not being changed during the sort process. The positions in the tag array are being changed so they will hold the correct ordering of the elements when they are sorted.
In this example, the original elements in arr[] are not changed, but the original elements in tag[] are manipulated. The tag[] array will now hold the correct subscript ordering of the elements in arr[] so the array can be sorted into descending order when the tag[] array is called upon.
Another Example, Suppose we have following Person object which inherently takes large chunk of memory( in GB or hundreds of MB).
class Person
{
private int id;
private float salary;
private Object someBigObject = new Object();
public Person(int id, float salary)
{ }
public float getSalary()
{ }
public String toString()
{ }
}
Hence, it might not be practical to move around these objects as disk seeks for swaps can eat up a lot of time. To avoid this, we start by creating a tag array.
Every Person object is tagged to one element in the tag array and Instead of swapping the person object for sorting based on salary , we swap the tag[] integers.
While printing the sorted array we take a cue from the tag array to print the sorted Persons array.
Eventually, we’ll escape swapping large Persons object.
Below is the implementation of above idea.
// Java Program to illustrate Tag Sort. This code// uses Bubble Sort to modify tag array according// to salaries. We can use other optimized sorting// techniques also.class Person{ private int id; private float salary; private Object someBigObject = new Object(); public Person(int id, float salary) { this.id = id; this.salary = salary; } public float getSalary() { return salary; } @Override public String toString() { return "Person{" + "id=" + id + ", salary=" + salary + ", someBigObject=" + someBigObject + '}'; }} public class Main{ public static void main(String[] args) { // Creating objects and their original // order (in tag array) int n = 5; Person persons[] = new Person[n]; persons[0] = new Person(0, 233.5f); persons[1] = new Person(1, 23f); persons[2] = new Person(2, 13.98f); persons[3] = new Person(3, 143.2f); persons[4] = new Person(4, 3f); int tag[] = new int[n]; for (int i = 0; i < n; i++) tag[i] = i; // Every Person object is tagged to // an element in the tag array. System.out.println("Given Person and Tag "); for (int i = 0; i < n; i++) System.out.println(persons[i] + " : Tag: " + tag[i]); // Modifying tag array so that we can access // persons in sorted order. tagSort(persons, tag); System.out.println("New Tag Array after "+ "getting sorted as per Person[] "); for (int i=0; i<n; i++) System.out.println(tag[i]); // Accessing persons in sorted (by salary) // way using modified tag array. for (int i = 0; i < n; i++) System.out.println(persons[tag[i]]); } // Modifying tag array so that we can access // persons in sorted order of salary. public static void tagSort(Person persons[], int tag[]) { int n = persons.length; for (int i=0; i<n; i++) { for (int j=i+1; j<n; j++) { if (persons[tag[i]].getSalary() > persons[tag[j]].getSalary()) { // Note we are not sorting the // actual Persons array, but only // the tag array int temp = tag[i]; tag[i] = tag[j]; tag[j] = temp; } } } }}
Output:
Given Person and Tag
Person{id=0, salary=233.5, someBigObject=java.lang.Object@15db9742} : Tag: 0
Person{id=1, salary=23.0, someBigObject=java.lang.Object@6d06d69c} : Tag: 1
Person{id=2, salary=13.98, someBigObject=java.lang.Object@7852e922} : Tag: 2
Person{id=3, salary=143.2, someBigObject=java.lang.Object@4e25154f} : Tag: 3
Person{id=4, salary=3.0, someBigObject=java.lang.Object@70dea4e} : Tag: 4
New Tag Array after getting sorted as per Person[]
4
2
1
3
0
Person{id=4, salary=3.0, someBigObject=java.lang.Object@70dea4e}
Person{id=2, salary=13.98, someBigObject=java.lang.Object@7852e922}
Person{id=1, salary=23.0, someBigObject=java.lang.Object@6d06d69c}
Person{id=3, salary=143.2, someBigObject=java.lang.Object@4e25154f}
Person{id=0, salary=233.5, someBigObject=java.lang.Object@15db9742}
This article is contributed by Rishi Verma . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 582,
"s": 52,
"text": "This is not a new sorting algorithm, but an idea when we need to avoid swapping of large objects or need to access elements of a large array in both original and sorted orders.A common sorting task is to sort elements of an array using a sorting algorithm like Quick Sort, Bubble Sort.. etc, but there may be times when we need to keep the actual array in tact and use a “tagged” array to store the correct positioning of the array when it is sorted. When we want to access elements in sorted way, we can use this “tagged” array."
},
{
"code": null,
"e": 603,
"s": 582,
"text": "Why to use Tag Sort?"
},
{
"code": null,
"e": 766,
"s": 603,
"text": "When we are operating on large array of objects, it might be too costly to swap these large object. After all its about the disk swaps and we want to minimize it!"
},
{
"code": null,
"e": 846,
"s": 766,
"text": "Tag Sort allows sorting an integer array after tagging it with original object."
},
{
"code": null,
"e": 926,
"s": 846,
"text": "In turn, we only swap the tag array integers instead of large array of objects."
},
{
"code": null,
"e": 1119,
"s": 926,
"text": "The actual elements are not being changed during the sort process. The positions in the tag array are being changed so they will hold the correct ordering of the elements when they are sorted."
},
{
"code": null,
"e": 1408,
"s": 1119,
"text": "In this example, the original elements in arr[] are not changed, but the original elements in tag[] are manipulated. The tag[] array will now hold the correct subscript ordering of the elements in arr[] so the array can be sorted into descending order when the tag[] array is called upon."
},
{
"code": null,
"e": 1537,
"s": 1408,
"text": "Another Example, Suppose we have following Person object which inherently takes large chunk of memory( in GB or hundreds of MB)."
},
{
"code": null,
"e": 1777,
"s": 1537,
"text": "class Person \n{\n private int id;\n private float salary;\n private Object someBigObject = new Object(); \n public Person(int id, float salary) \n { }\n public float getSalary() \n { }\n public String toString() \n { }\n}\n"
},
{
"code": null,
"e": 1938,
"s": 1777,
"text": "Hence, it might not be practical to move around these objects as disk seeks for swaps can eat up a lot of time. To avoid this, we start by creating a tag array."
},
{
"code": null,
"e": 2100,
"s": 1938,
"text": "Every Person object is tagged to one element in the tag array and Instead of swapping the person object for sorting based on salary , we swap the tag[] integers."
},
{
"code": null,
"e": 2200,
"s": 2100,
"text": "While printing the sorted array we take a cue from the tag array to print the sorted Persons array."
},
{
"code": null,
"e": 2256,
"s": 2200,
"text": "Eventually, we’ll escape swapping large Persons object."
},
{
"code": null,
"e": 2299,
"s": 2256,
"text": "Below is the implementation of above idea."
},
{
"code": "// Java Program to illustrate Tag Sort. This code// uses Bubble Sort to modify tag array according// to salaries. We can use other optimized sorting// techniques also.class Person{ private int id; private float salary; private Object someBigObject = new Object(); public Person(int id, float salary) { this.id = id; this.salary = salary; } public float getSalary() { return salary; } @Override public String toString() { return \"Person{\" + \"id=\" + id + \", salary=\" + salary + \", someBigObject=\" + someBigObject + '}'; }} public class Main{ public static void main(String[] args) { // Creating objects and their original // order (in tag array) int n = 5; Person persons[] = new Person[n]; persons[0] = new Person(0, 233.5f); persons[1] = new Person(1, 23f); persons[2] = new Person(2, 13.98f); persons[3] = new Person(3, 143.2f); persons[4] = new Person(4, 3f); int tag[] = new int[n]; for (int i = 0; i < n; i++) tag[i] = i; // Every Person object is tagged to // an element in the tag array. System.out.println(\"Given Person and Tag \"); for (int i = 0; i < n; i++) System.out.println(persons[i] + \" : Tag: \" + tag[i]); // Modifying tag array so that we can access // persons in sorted order. tagSort(persons, tag); System.out.println(\"New Tag Array after \"+ \"getting sorted as per Person[] \"); for (int i=0; i<n; i++) System.out.println(tag[i]); // Accessing persons in sorted (by salary) // way using modified tag array. for (int i = 0; i < n; i++) System.out.println(persons[tag[i]]); } // Modifying tag array so that we can access // persons in sorted order of salary. public static void tagSort(Person persons[], int tag[]) { int n = persons.length; for (int i=0; i<n; i++) { for (int j=i+1; j<n; j++) { if (persons[tag[i]].getSalary() > persons[tag[j]].getSalary()) { // Note we are not sorting the // actual Persons array, but only // the tag array int temp = tag[i]; tag[i] = tag[j]; tag[j] = temp; } } } }}",
"e": 4914,
"s": 2299,
"text": null
},
{
"code": null,
"e": 4922,
"s": 4914,
"text": "Output:"
},
{
"code": null,
"e": 5724,
"s": 4922,
"text": "Given Person and Tag \nPerson{id=0, salary=233.5, someBigObject=java.lang.Object@15db9742} : Tag: 0\nPerson{id=1, salary=23.0, someBigObject=java.lang.Object@6d06d69c} : Tag: 1\nPerson{id=2, salary=13.98, someBigObject=java.lang.Object@7852e922} : Tag: 2\nPerson{id=3, salary=143.2, someBigObject=java.lang.Object@4e25154f} : Tag: 3\nPerson{id=4, salary=3.0, someBigObject=java.lang.Object@70dea4e} : Tag: 4\nNew Tag Array after getting sorted as per Person[] \n4\n2\n1\n3\n0\nPerson{id=4, salary=3.0, someBigObject=java.lang.Object@70dea4e}\nPerson{id=2, salary=13.98, someBigObject=java.lang.Object@7852e922}\nPerson{id=1, salary=23.0, someBigObject=java.lang.Object@6d06d69c}\nPerson{id=3, salary=143.2, someBigObject=java.lang.Object@4e25154f}\nPerson{id=0, salary=233.5, someBigObject=java.lang.Object@15db9742}\n"
},
{
"code": null,
"e": 6020,
"s": 5724,
"text": "This article is contributed by Rishi Verma . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6145,
"s": 6020,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6153,
"s": 6145,
"text": "Sorting"
},
{
"code": null,
"e": 6161,
"s": 6153,
"text": "Sorting"
}
] |
Program to print tetrahedral numbers upto Nth term
|
25 May, 2022
Prerequisites:
Triangular numbers
Tetrahedral numbers
Given a value n, and the task is to print tetrahedral number series up to nth term.Examples:
Input: 5
Output: 1 4 10 20 35
Input: 10
Output: 1 4 10 20 35 56 84 120 165 220
Method 1: Using Triangular Number series: This problem can be easily solved with the fact that Nth Tetrahedral Number is equal to the sum of first N Triangular Numbers.Let’s have a look on Series of triangular and tetrahedral Numbers.
To print series upto 5th term:
Triangular Numbers = 1 3 6 10 15
Tetrahedral numbers = 1 4 10 20 35
i.e (1) (1 + 3) (1 + 3 + 6) (1 + 3 + 6 + 10) (1 + 3 + 6 + 10 + 35)
Calculate Nth Triangular number using formula So, print the tetrahedral numbers series by generating triangular numbers and adding it with the sum of all previously generated triangular numbers. Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to generate tetrahedral// number series#include <bits/stdc++.h>using namespace std; // function to generate nth triangular// numberlong findTriangularNumber(int n){ return (n * (n + 1)) / 2;} // function to print tetrahedral number// series up to nvoid printSeries(int n){ // Initialize prev as 0. It stores // the sum of all previously generated // triangular number int prev = 0; int curr; // Loop to print series for (int i = 1; i <= n; i++) { // Find ith triangular number curr = findTriangularNumber(i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number curr = curr + prev; cout << curr << " "; // Update sum of all previously // generated triangular number prev = curr; }} // Driver codeint main(){ int n = 10; // function call to print series printSeries(n); return 0;}
// Java program to generate tetrahedral// number seriesimport java.io.*; class GFG { // function to generate nth triangular // number static long findTriangularNumber(int n) { return (n * (n + 1)) / 2; } // function to print tetrahedral number // series up to n static void printSeries(int n) { // Initialize prev as 0. It store // the sum of all previously generated // triangular number long prev = 0; long curr; // Loop to print series for (int i = 1; i <= n; i++) { // Find ithh triangular number curr = findTriangularNumber(i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number curr = curr + prev; System.out.print(curr + " "); // Update sum of all previously // generated triangular number prev = curr; } } // Driver code public static void main (String[] args) { int n = 10; // function call to print series printSeries(n); }}
# Python3 program to generate# tetrahedral number series # function to generate nth# triangular numberdef findTriangularNumber(n): return (n * (n + 1)) / 2 # function to print tetrahedral# number series up to ndef printSeries(n): # Initialize prev as 0. # It stores the sum of all # previously generated # triangular number prev = 0 # Loop to print series for i in range(1, n+1): # Find ith triangular number curr = findTriangularNumber(i) # Add ith triangular number # to sum of all previously # generated triangular number # to get ith tetrahedral number curr = int(curr + prev) print(curr, end = ' ') # Update sum of all previously # generated triangular number prev = curr # Driver coden = 10 # function call to# print seriesprintSeries(n) # This code is contributed by Mahadev.
// C# program to generate tetrahedral// number seriesusing System; public class GFG{ // function to generate nth triangular // number static long findTriangularNumber(int n) { return (n * (n + 1)) / 2; } // function to print tetrahedral number // series up to n static void printSeries(int n) { // Initialize prev as 0. It store // the sum of all previously generated // triangular number long prev = 0; long curr; // Loop to print series for (int i = 1; i <= n; i++) { // Find ithh triangular number curr = findTriangularNumber(i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number curr = curr + prev; Console.Write(curr + " "); // Update sum of all previously // generated triangular number prev = curr; } } // Driver code static public void Main () { int n = 10; // function call to print series printSeries(n); }}
<?php// PHP program to generate tetrahedral// number series // function to generate nth triangular// numberfunction findTriangularNumber($n){ return ($n * ($n + 1)) / 2;} // function to print tetrahedral number// series up to nfunction printSeries($n){ // Initialize prev as 0. It store // the sum of all previously generated // triangular number $prev = 0; $curr; // Loop to print series for ($i = 1; $i <= $n; $i++) { // Find ithh triangular number $curr = findTriangularNumber($i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number $curr = $curr + $prev; echo($curr . " "); // Update sum of all previously // generated triangular number $prev = $curr; }} // Driver code$n = 10; // function call to print seriesprintSeries($n);?>
<script>// Javascript program to generate tetrahedral// number series // function to generate nth triangular// numberfunction findTriangularNumber(n){ return (n * (n + 1)) / 2;} // function to print tetrahedral number// series up to nfunction printSeries(n){ // Initialize prev as 0. It stores // the sum of all previously generated // triangular number var prev = 0; var curr; // Loop to print series for (var i = 1; i <= n; i++) { // Find ith triangular number curr = findTriangularNumber(i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number curr = curr + prev; document.write( curr + " "); // Update sum of all previously // generated triangular number prev = curr; }} // Driver codevar n = 10; // function call to print seriesprintSeries(n); // This code is contributed by itsok.</script>
1 4 10 20 35 56 84 120 165 220
Time Complexity: O(n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant.
Method 2: Using Tetrahedral Number Formula: Formula to find nth tetrahedral number:Below is the required implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to generate series of// tetrahedral numbers#include <bits/stdc++.h>using namespace std; // function to print tetrahedral// number series up to nvoid printSeries(int n){ // loop to print series for (int i = 1; i <= n; i++) { // Calculate and print ith // tetrahedral number int num = i * (i + 1) * (i + 2) / 6; cout << num << " "; }} // Driver codeint main(){ int n = 10; // function call to print series printSeries(n); return 0;}
// Java program to generate series of// tetrahedral numbersimport java.io.*; class GFG { // function to print tetrahedral // number series up to n static void printSeries(int n) { // loop to print series for (int i = 1; i <= n; i++) { // Calculate and print ith // tetrahedral number int num = i * (i + 1) * (i + 2) / 6; System.out.print(num + " "); } } // Driver code public static void main (String[] args) { int n = 10; // function call to print series printSeries(n); }}
# Python3 code to print tetrahedral# numbers series up to n # function to print tetrahedral series up to ndef printSeries(n): # loop to print series for i in range(1, n + 1): # Calculate and print ith # Tetrahedral number num = i * (i + 1) * (i + 2) // 6 print(num, end =' ') # Driver coden = 10 # function call to print seriesprintSeries(n)
// C# program to generate series of// tetrahedral numbersusing System; public class GFG{ // function to print tetrahedral // number series up to n static void printSeries(int n) { // loop to print series for (int i = 1; i <= n; i++) { // Calculate and print ith // tetrahedral number int num = i * (i + 1) * (i + 2) / 6; Console.Write(num + " "); } } // Driver code static public void Main () { int n = 10; // function call to print series printSeries(n); }}
<?php// PHP program to generate series of// tetrahedral numbers // function to print tetrahedral// number series up to nfunction printSeries($n){ // loop to print series for ($i = 1; $i <= $n; $i++) { // Calculate and print ith // tetrahedral number $num = $i * ($i + 1) * ($i + 2) / 6; echo ($num . " "); }} // Driver code$n = 10; // function call to print seriesprintSeries($n); ?>
<script> // Javascript program to generate series of// tetrahedral numbers // function to print tetrahedral // number series up to n function printSeries(n) { let i; // loop to print series for (i = 1; i <= n; i++) { // Calculate and print ith // tetrahedral number let num = i * (i + 1) * ((i + 2) / 6); document.write(num + " "); } } // driver program let n = 10; // function call to print series printSeries(n); // This code is contributed by susmitakundugoaldanga.</script>
1 4 10 20 35 56 84 120 165 220
Time Complexity: O(n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant.
Mahadev99
susmitakundugoaldanga
itsok
tamanna17122007
math
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
Operators in C / C++
Program to find GCD or HCF of two numbers
Prime Numbers
Find minimum number of coins that make a given value
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 45,
"s": 28,
"text": "Prerequisites: "
},
{
"code": null,
"e": 64,
"s": 45,
"text": "Triangular numbers"
},
{
"code": null,
"e": 84,
"s": 64,
"text": "Tetrahedral numbers"
},
{
"code": null,
"e": 179,
"s": 84,
"text": "Given a value n, and the task is to print tetrahedral number series up to nth term.Examples: "
},
{
"code": null,
"e": 273,
"s": 179,
"text": "Input: 5\nOutput: 1 4 10 20 35\n\nInput: 10\nOutput: 1 4 10 20 35 56 84 120 165 220 "
},
{
"code": null,
"e": 512,
"s": 275,
"text": "Method 1: Using Triangular Number series: This problem can be easily solved with the fact that Nth Tetrahedral Number is equal to the sum of first N Triangular Numbers.Let’s have a look on Series of triangular and tetrahedral Numbers. "
},
{
"code": null,
"e": 798,
"s": 512,
"text": "To print series upto 5th term:\nTriangular Numbers = 1 3 6 10 15\nTetrahedral numbers = 1 4 10 20 35 \n i.e (1) (1 + 3) (1 + 3 + 6) (1 + 3 + 6 + 10) (1 + 3 + 6 + 10 + 35) "
},
{
"code": null,
"e": 1045,
"s": 798,
"text": "Calculate Nth Triangular number using formula So, print the tetrahedral numbers series by generating triangular numbers and adding it with the sum of all previously generated triangular numbers. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1049,
"s": 1045,
"text": "C++"
},
{
"code": null,
"e": 1054,
"s": 1049,
"text": "Java"
},
{
"code": null,
"e": 1062,
"s": 1054,
"text": "Python3"
},
{
"code": null,
"e": 1065,
"s": 1062,
"text": "C#"
},
{
"code": null,
"e": 1069,
"s": 1065,
"text": "PHP"
},
{
"code": null,
"e": 1080,
"s": 1069,
"text": "Javascript"
},
{
"code": "// C++ program to generate tetrahedral// number series#include <bits/stdc++.h>using namespace std; // function to generate nth triangular// numberlong findTriangularNumber(int n){ return (n * (n + 1)) / 2;} // function to print tetrahedral number// series up to nvoid printSeries(int n){ // Initialize prev as 0. It stores // the sum of all previously generated // triangular number int prev = 0; int curr; // Loop to print series for (int i = 1; i <= n; i++) { // Find ith triangular number curr = findTriangularNumber(i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number curr = curr + prev; cout << curr << \" \"; // Update sum of all previously // generated triangular number prev = curr; }} // Driver codeint main(){ int n = 10; // function call to print series printSeries(n); return 0;}",
"e": 2075,
"s": 1080,
"text": null
},
{
"code": "// Java program to generate tetrahedral// number seriesimport java.io.*; class GFG { // function to generate nth triangular // number static long findTriangularNumber(int n) { return (n * (n + 1)) / 2; } // function to print tetrahedral number // series up to n static void printSeries(int n) { // Initialize prev as 0. It store // the sum of all previously generated // triangular number long prev = 0; long curr; // Loop to print series for (int i = 1; i <= n; i++) { // Find ithh triangular number curr = findTriangularNumber(i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number curr = curr + prev; System.out.print(curr + \" \"); // Update sum of all previously // generated triangular number prev = curr; } } // Driver code public static void main (String[] args) { int n = 10; // function call to print series printSeries(n); }}",
"e": 3265,
"s": 2075,
"text": null
},
{
"code": "# Python3 program to generate# tetrahedral number series # function to generate nth# triangular numberdef findTriangularNumber(n): return (n * (n + 1)) / 2 # function to print tetrahedral# number series up to ndef printSeries(n): # Initialize prev as 0. # It stores the sum of all # previously generated # triangular number prev = 0 # Loop to print series for i in range(1, n+1): # Find ith triangular number curr = findTriangularNumber(i) # Add ith triangular number # to sum of all previously # generated triangular number # to get ith tetrahedral number curr = int(curr + prev) print(curr, end = ' ') # Update sum of all previously # generated triangular number prev = curr # Driver coden = 10 # function call to# print seriesprintSeries(n) # This code is contributed by Mahadev.",
"e": 4162,
"s": 3265,
"text": null
},
{
"code": "// C# program to generate tetrahedral// number seriesusing System; public class GFG{ // function to generate nth triangular // number static long findTriangularNumber(int n) { return (n * (n + 1)) / 2; } // function to print tetrahedral number // series up to n static void printSeries(int n) { // Initialize prev as 0. It store // the sum of all previously generated // triangular number long prev = 0; long curr; // Loop to print series for (int i = 1; i <= n; i++) { // Find ithh triangular number curr = findTriangularNumber(i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number curr = curr + prev; Console.Write(curr + \" \"); // Update sum of all previously // generated triangular number prev = curr; } } // Driver code static public void Main () { int n = 10; // function call to print series printSeries(n); }}",
"e": 5336,
"s": 4162,
"text": null
},
{
"code": "<?php// PHP program to generate tetrahedral// number series // function to generate nth triangular// numberfunction findTriangularNumber($n){ return ($n * ($n + 1)) / 2;} // function to print tetrahedral number// series up to nfunction printSeries($n){ // Initialize prev as 0. It store // the sum of all previously generated // triangular number $prev = 0; $curr; // Loop to print series for ($i = 1; $i <= $n; $i++) { // Find ithh triangular number $curr = findTriangularNumber($i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number $curr = $curr + $prev; echo($curr . \" \"); // Update sum of all previously // generated triangular number $prev = $curr; }} // Driver code$n = 10; // function call to print seriesprintSeries($n);?>",
"e": 6253,
"s": 5336,
"text": null
},
{
"code": "<script>// Javascript program to generate tetrahedral// number series // function to generate nth triangular// numberfunction findTriangularNumber(n){ return (n * (n + 1)) / 2;} // function to print tetrahedral number// series up to nfunction printSeries(n){ // Initialize prev as 0. It stores // the sum of all previously generated // triangular number var prev = 0; var curr; // Loop to print series for (var i = 1; i <= n; i++) { // Find ith triangular number curr = findTriangularNumber(i); // Add ith triangular number to // sum of all previously generated // triangular number to get ith // tetrahedral number curr = curr + prev; document.write( curr + \" \"); // Update sum of all previously // generated triangular number prev = curr; }} // Driver codevar n = 10; // function call to print seriesprintSeries(n); // This code is contributed by itsok.</script>",
"e": 7229,
"s": 6253,
"text": null
},
{
"code": null,
"e": 7260,
"s": 7229,
"text": "1 4 10 20 35 56 84 120 165 220"
},
{
"code": null,
"e": 7394,
"s": 7262,
"text": "Time Complexity: O(n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 7516,
"s": 7394,
"text": "Method 2: Using Tetrahedral Number Formula: Formula to find nth tetrahedral number:Below is the required implementation: "
},
{
"code": null,
"e": 7520,
"s": 7516,
"text": "C++"
},
{
"code": null,
"e": 7525,
"s": 7520,
"text": "Java"
},
{
"code": null,
"e": 7533,
"s": 7525,
"text": "Python3"
},
{
"code": null,
"e": 7536,
"s": 7533,
"text": "C#"
},
{
"code": null,
"e": 7540,
"s": 7536,
"text": "PHP"
},
{
"code": null,
"e": 7551,
"s": 7540,
"text": "Javascript"
},
{
"code": "// C++ program to generate series of// tetrahedral numbers#include <bits/stdc++.h>using namespace std; // function to print tetrahedral// number series up to nvoid printSeries(int n){ // loop to print series for (int i = 1; i <= n; i++) { // Calculate and print ith // tetrahedral number int num = i * (i + 1) * (i + 2) / 6; cout << num << \" \"; }} // Driver codeint main(){ int n = 10; // function call to print series printSeries(n); return 0;}",
"e": 8068,
"s": 7551,
"text": null
},
{
"code": "// Java program to generate series of// tetrahedral numbersimport java.io.*; class GFG { // function to print tetrahedral // number series up to n static void printSeries(int n) { // loop to print series for (int i = 1; i <= n; i++) { // Calculate and print ith // tetrahedral number int num = i * (i + 1) * (i + 2) / 6; System.out.print(num + \" \"); } } // Driver code public static void main (String[] args) { int n = 10; // function call to print series printSeries(n); }}",
"e": 8696,
"s": 8068,
"text": null
},
{
"code": "# Python3 code to print tetrahedral# numbers series up to n # function to print tetrahedral series up to ndef printSeries(n): # loop to print series for i in range(1, n + 1): # Calculate and print ith # Tetrahedral number num = i * (i + 1) * (i + 2) // 6 print(num, end =' ') # Driver coden = 10 # function call to print seriesprintSeries(n)",
"e": 9111,
"s": 8696,
"text": null
},
{
"code": "// C# program to generate series of// tetrahedral numbersusing System; public class GFG{ // function to print tetrahedral // number series up to n static void printSeries(int n) { // loop to print series for (int i = 1; i <= n; i++) { // Calculate and print ith // tetrahedral number int num = i * (i + 1) * (i + 2) / 6; Console.Write(num + \" \"); } } // Driver code static public void Main () { int n = 10; // function call to print series printSeries(n); }}",
"e": 9723,
"s": 9111,
"text": null
},
{
"code": "<?php// PHP program to generate series of// tetrahedral numbers // function to print tetrahedral// number series up to nfunction printSeries($n){ // loop to print series for ($i = 1; $i <= $n; $i++) { // Calculate and print ith // tetrahedral number $num = $i * ($i + 1) * ($i + 2) / 6; echo ($num . \" \"); }} // Driver code$n = 10; // function call to print seriesprintSeries($n); ?>",
"e": 10152,
"s": 9723,
"text": null
},
{
"code": "<script> // Javascript program to generate series of// tetrahedral numbers // function to print tetrahedral // number series up to n function printSeries(n) { let i; // loop to print series for (i = 1; i <= n; i++) { // Calculate and print ith // tetrahedral number let num = i * (i + 1) * ((i + 2) / 6); document.write(num + \" \"); } } // driver program let n = 10; // function call to print series printSeries(n); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 10780,
"s": 10152,
"text": null
},
{
"code": null,
"e": 10811,
"s": 10780,
"text": "1 4 10 20 35 56 84 120 165 220"
},
{
"code": null,
"e": 10945,
"s": 10813,
"text": "Time Complexity: O(n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 10955,
"s": 10945,
"text": "Mahadev99"
},
{
"code": null,
"e": 10977,
"s": 10955,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 10983,
"s": 10977,
"text": "itsok"
},
{
"code": null,
"e": 10999,
"s": 10983,
"text": "tamanna17122007"
},
{
"code": null,
"e": 11004,
"s": 10999,
"text": "math"
},
{
"code": null,
"e": 11011,
"s": 11004,
"text": "series"
},
{
"code": null,
"e": 11024,
"s": 11011,
"text": "Mathematical"
},
{
"code": null,
"e": 11037,
"s": 11024,
"text": "Mathematical"
},
{
"code": null,
"e": 11044,
"s": 11037,
"text": "series"
},
{
"code": null,
"e": 11142,
"s": 11044,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11172,
"s": 11142,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 11215,
"s": 11172,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 11275,
"s": 11215,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 11290,
"s": 11275,
"text": "C++ Data Types"
},
{
"code": null,
"e": 11314,
"s": 11290,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 11333,
"s": 11314,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 11354,
"s": 11333,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 11396,
"s": 11354,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 11410,
"s": 11396,
"text": "Prime Numbers"
}
] |
MySQL | Common MySQL Queries
|
14 Aug, 2021
MySQL server is a open-source relational database management system which is a major support for web based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. Even all social networking websites mainly Facebook, Twitter, and Google depends on MySQL data which are designed and optimized for such purpose. For all these reasons, MySQL server becomes the default choice for web applications.
MySQL server is used for data operations like querying, sorting, filtering, grouping, modifying and joining the tables. Before learning the commonly used queries, let us look into some of the advantages of MySQL.
Advantages of MySQL :
Fast and high Performance database.
Easy to use, maintain and administer.
Easily available and maintain integrity of database.
Provides scalability, usability and reliability.
Low cost hardware.
MySQL can read simple and complex queries and write operations.
InnoDB is default and widely used storage engine.
Provides strong indexing support.
Provides SSL support for secured connections.
Provides powerful data encryption and accuracy.
Provides Cross-platform compatibility.
Provides minimized code repetition.
Queries can be understood as the commands which interacts with database tables to work around with data. Some of the commonly used MySQL queries, operators, and functions are as follows :
1. SHOW DATABASES
This displays information of all the existing databases in the server.
Output:
Note : The databases ‘information_schema’, ‘mysql’ and ‘performance_schema’ are system databases which are used internally by MySQL server. A ‘test’ database is meant for testing purpose which is provided during installation.
2. USE database_name database_name : name of the database This sets the database as the current database in the MySQL server. To display the current database name which is set, use syntax
SELECT DATABASE();
3. DESCRIBE table_name table_name : name of the table This describes the columns of the table_name with respect to Field, Type, Null, Key, Default, Extra.
4. SHOW TABLES This shows all the tables in the selected database as a information.
5. SHOW CREATE TABLE table_name table_name : name of the table This shows the complete CREATE TABLE statement used by MySQL for creating the table.
6. SELECT NOW() MySQL queries mostly starts with SELECT statement. This query shows the current date and time. Output :
2019-09-24 07:08:30
7. SELECT 2 + 4;
Output :
6
This executes SELECT statement without any table. SELECT can be used for executing an expression or evaluating an in-built function. SELECT can also be used for more than one or many columns.
Example :
SELECT 2+4, CURDATE();
Output :
8. Comments Comments are of two types. Multi-line comments or single-line or end-of-line comment.
/* These are multi-line comments. */
# This is single-line comment.
-- This is also single-line comment.
9. CREATE DATABASE database_name database_name : name of the database This statement creates a new database.
10. DROP DATABASE database_name database_name : name of the database This statement deletes the database. Note : User has to be very careful before deleting a database as it will lose all the crucial information stored in the database.
11. CREATE TABLE table_name(column1, column2, column3..) table_name : name of the table column1 : name of first column column2 : name of second column column3 : name of third column When the developer start building an application, he needs to create database tables. This statement creates a new table with the given columns.
Example :
CREATE TABLE employee(
'id' INTEGER NOT NULL AUTO_INCREMENT,
'name' VARCHAR(30) NOT NULL,
'profile' VARCHAR(40) DEFAULT 'engineer',
PRIMARY KEY ('id')
)ENGINE = InnoDB;
Note : You have ‘id’ column as AUTO_INCREMENT with a primary key constraint which ensures that each id is incremented value, avoiding duplication. Storage engine selected is ‘InnoDB’ allowing foreign key constraint and related transactions.
12. AUTO_INCREMENT It is used to generate a unique identification field for new row.
13. DROP TABLE table_name table_name : name of the table This statement deletes the mentioned table.
14. RENAME TABLE old_table_name TO new_table_name old_table_name : name of the previous table. new_table_name : name of the new table. This statement renames the table to a new name.
15. ALTER TABLE table_name ADD(column1, column2, column3..) table_name : name of the existing table. column1 : name of first column. column2 : name of second column. column3 : name of third column. This statement adds columns to the existing table.
16. ALTER TABLE table_name DROP(column1) table_name : name of the existing table. column1 : name of first column. This statement deletes specified columns from the existing table.
17. INSERT INTO table_name (column1, column2, column3 . . ) VALUES(value1, value2, value3 . . ) table_name : name of the existing table. column1 : name of first column. column2 : name of second column. column3 : name of third column. value1 : value for first column. value2 : value for second column. value3 : value for third column. This statement inserts a new record into a table with specified values.
18. UPDATE table_name SET column1 = value1, column2 = value2, column3 = value3.. WHERE condition table_name : name of the table. column1 : name of first column. column2 : name of second column. column3 : name of third column. value1 : value for first column. value2 : value for second column. value3 : value for third column. condition : the condition statement. This statement update records in the table with the new given values for the columns.
Note : WHERE clause in MySQL queries is used to filter rows for a specific condition.
19. DELETE FROM table_name WHERE condition table_name : name of the table. condition : the condition statement. This statement deletes records from the table.
20. SELECT column1, column2, column3.. FROM table_name WHERE condition table_name : name of the table. column1 : name of first column. column2 : name of second column. column3 : name of third column. condition : the condition statement. This statement executes and gives records from specific columns from the table which matches the condition after WHERE clause.
21. SELECT * FROM table_name table_name: name of the table. Instead of specifying one column or many columns, you can use an asterisk (*) which represents all columns of table. This query retrieves all records from the table.
22. COUNT The COUNT function is used to return total number of records matching a condition from any table. It is one of the known AGGREGATE function.
Example :
SELECT COUNT(*) from student;
Note: AGGREGATE functions allow you to run calculations on data and provide information by using a SELECT query.
23. MAX It is used to get the maximum numeric value of a particular column of table.
Example :
SELECT MAX(marks) FROM student_report;
Note: The MIN and MAX functions work correctly on numeric as well as alphabetic values.
24. MIN It is used to get the minimum numeric value of a particular column of table.
Example :
SELECT MIN(marks) FROM student_report;
Note : The above given example queries can also be nested with each other depending on the requirement.
Example :
SELECT MIN(marks)
FROM student_report
WHERE marks > ( SELECT MIN(marks) from student_report);
25. LIMIT It is used to set the limit of number of records in result set.
Example :
SELECT *
FROM student limit 4, 10;
This gives 10 records starting from the 5th record.
26. BETWEEN It is used to get records from the specified lower limit to upper limit. This verifies if a value lies within that given range.
Example :
SELECT * FROM employee
WHERE age BETWEEN 25 to 45.
27. DISTINCT This is used to fetch all distinct records avoiding all duplicate ones.
Example :
SELECT DISTINCT profile
FROM employee;
28. IN clause This verifies if a row is contained in a set of given values. It is used instead of using so many OR clause in a query.
Example :
SELECT *
FROM employee
WHERE age IN(40, 50, 55);
29. AND This condition in MySQL queries are used to filter the result data based on AND conditions.
Example :
SELECT NAME, AGE
FROM student
WHERE marks > 95 AND grade = 7;
30. OR This condition in MySQL queries are used to filter the result data based on OR conditions.
Example :
SELECT *
FROM student
WHERE address = 'Hyderabad' OR address = 'Bangalore';
31. IS NULL This keyword is used for boolean comparison or to check if the data value of a column is null.
Example :
SELECT *
FROM employee
WHERE contact_number IS NULL;
32. FOREIGN KEY It is used for pointing a PRIMARY KEY of another table.
Example :
CREATE TABLE Customers
(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
)
CREATE TABLE Orders
(
order_id INT AUTO_INCREMENT PRIMARY KEY,
FOREIGN KEY (id) REFERENCES Customers(id)
);
Note: This is not used in the MYISAM storage engine of MySQL server. InnoDB storage engines supports foreign key constraints.
33. LIKE This is used to fetch records matching for specified string pattern.
Example :
SELECT *
FROM employee
WHERE name LIKE 'Sh%';
SELECT *
FROM employee
WHERE name LIKE '%Sh%';
Note: Percentage signs (%) in the query represent zero or more characters.
34. JOINS Joins are the joining of two or more database tables to fetch data based on a common field. There are various types of joins with different names in different databases. Commonly known joins are self join, outer join, inner join and many more.
Regular Join : It is the join which gets all the records from both the tables which exactly match the given condition.
Example :
SELECT student.name, department.name
FROM student JOIN department ON student.department = department.name
Left Join : It is the join which gets all the records that match the given condition, and also fetch all the records from the left table.
Example :
SELECT student.name, department.name
FROM student LEFT JOIN department ON student.deptartment = department.name
Right Join : It is the join which gets all the records that match the given condition, and also fetch all the records from the right table.
Example :
SELECT student.name, department.name
FROM student RIGHT JOIN department on student.department = department.name
35. ADD or DROP a column A new column can be added on a database table, if required later on.
Example :
ALTER TABLE employee ADD COLUMN salary VARCHAR(25);
Similarly, any column can be deleted from a database table.
Example :
ALTER TABLE employee DROP COLUMN salary;
Conclusion :
Running MySQL queries are the most commonly-performed tasks used to get data within the process of database management. There are many database management tools like phpMyAdmin, that helps to perform queries and handle transactions comfortably with visual data results. You have scrolled the most common MySQL queries, which are used in daily coding practices. Developer can customize or enhance the queries with respect to a particular requirement.
abhishek0719kadiyan
rajeev0719singh
kalrap615
mysql
SQLmysql
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Aug, 2021"
},
{
"code": null,
"e": 541,
"s": 52,
"text": "MySQL server is a open-source relational database management system which is a major support for web based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. Even all social networking websites mainly Facebook, Twitter, and Google depends on MySQL data which are designed and optimized for such purpose. For all these reasons, MySQL server becomes the default choice for web applications. "
},
{
"code": null,
"e": 755,
"s": 541,
"text": "MySQL server is used for data operations like querying, sorting, filtering, grouping, modifying and joining the tables. Before learning the commonly used queries, let us look into some of the advantages of MySQL. "
},
{
"code": null,
"e": 778,
"s": 755,
"text": "Advantages of MySQL : "
},
{
"code": null,
"e": 814,
"s": 778,
"text": "Fast and high Performance database."
},
{
"code": null,
"e": 852,
"s": 814,
"text": "Easy to use, maintain and administer."
},
{
"code": null,
"e": 905,
"s": 852,
"text": "Easily available and maintain integrity of database."
},
{
"code": null,
"e": 954,
"s": 905,
"text": "Provides scalability, usability and reliability."
},
{
"code": null,
"e": 973,
"s": 954,
"text": "Low cost hardware."
},
{
"code": null,
"e": 1037,
"s": 973,
"text": "MySQL can read simple and complex queries and write operations."
},
{
"code": null,
"e": 1087,
"s": 1037,
"text": "InnoDB is default and widely used storage engine."
},
{
"code": null,
"e": 1121,
"s": 1087,
"text": "Provides strong indexing support."
},
{
"code": null,
"e": 1167,
"s": 1121,
"text": "Provides SSL support for secured connections."
},
{
"code": null,
"e": 1215,
"s": 1167,
"text": "Provides powerful data encryption and accuracy."
},
{
"code": null,
"e": 1254,
"s": 1215,
"text": "Provides Cross-platform compatibility."
},
{
"code": null,
"e": 1290,
"s": 1254,
"text": "Provides minimized code repetition."
},
{
"code": null,
"e": 1480,
"s": 1290,
"text": "Queries can be understood as the commands which interacts with database tables to work around with data. Some of the commonly used MySQL queries, operators, and functions are as follows : "
},
{
"code": null,
"e": 1499,
"s": 1480,
"text": "1. SHOW DATABASES "
},
{
"code": null,
"e": 1571,
"s": 1499,
"text": "This displays information of all the existing databases in the server. "
},
{
"code": null,
"e": 1579,
"s": 1571,
"text": "Output:"
},
{
"code": null,
"e": 1806,
"s": 1579,
"text": "Note : The databases ‘information_schema’, ‘mysql’ and ‘performance_schema’ are system databases which are used internally by MySQL server. A ‘test’ database is meant for testing purpose which is provided during installation. "
},
{
"code": null,
"e": 1995,
"s": 1806,
"text": "2. USE database_name database_name : name of the database This sets the database as the current database in the MySQL server. To display the current database name which is set, use syntax "
},
{
"code": null,
"e": 2015,
"s": 1995,
"text": "SELECT DATABASE(); "
},
{
"code": null,
"e": 2171,
"s": 2015,
"text": "3. DESCRIBE table_name table_name : name of the table This describes the columns of the table_name with respect to Field, Type, Null, Key, Default, Extra. "
},
{
"code": null,
"e": 2256,
"s": 2171,
"text": "4. SHOW TABLES This shows all the tables in the selected database as a information. "
},
{
"code": null,
"e": 2405,
"s": 2256,
"text": "5. SHOW CREATE TABLE table_name table_name : name of the table This shows the complete CREATE TABLE statement used by MySQL for creating the table. "
},
{
"code": null,
"e": 2526,
"s": 2405,
"text": "6. SELECT NOW() MySQL queries mostly starts with SELECT statement. This query shows the current date and time. Output : "
},
{
"code": null,
"e": 2547,
"s": 2526,
"text": "2019-09-24 07:08:30 "
},
{
"code": null,
"e": 2565,
"s": 2547,
"text": "7. SELECT 2 + 4; "
},
{
"code": null,
"e": 2575,
"s": 2565,
"text": "Output : "
},
{
"code": null,
"e": 2578,
"s": 2575,
"text": "6 "
},
{
"code": null,
"e": 2771,
"s": 2578,
"text": "This executes SELECT statement without any table. SELECT can be used for executing an expression or evaluating an in-built function. SELECT can also be used for more than one or many columns. "
},
{
"code": null,
"e": 2782,
"s": 2771,
"text": "Example : "
},
{
"code": null,
"e": 2806,
"s": 2782,
"text": "SELECT 2+4, CURDATE(); "
},
{
"code": null,
"e": 2816,
"s": 2806,
"text": "Output : "
},
{
"code": null,
"e": 2915,
"s": 2816,
"text": "8. Comments Comments are of two types. Multi-line comments or single-line or end-of-line comment. "
},
{
"code": null,
"e": 2955,
"s": 2915,
"text": "/* These are multi-line comments. */ "
},
{
"code": null,
"e": 2988,
"s": 2955,
"text": " # This is single-line comment."
},
{
"code": null,
"e": 3026,
"s": 2988,
"text": " -- This is also single-line comment."
},
{
"code": null,
"e": 3136,
"s": 3026,
"text": "9. CREATE DATABASE database_name database_name : name of the database This statement creates a new database. "
},
{
"code": null,
"e": 3373,
"s": 3136,
"text": "10. DROP DATABASE database_name database_name : name of the database This statement deletes the database. Note : User has to be very careful before deleting a database as it will lose all the crucial information stored in the database. "
},
{
"code": null,
"e": 3701,
"s": 3373,
"text": "11. CREATE TABLE table_name(column1, column2, column3..) table_name : name of the table column1 : name of first column column2 : name of second column column3 : name of third column When the developer start building an application, he needs to create database tables. This statement creates a new table with the given columns. "
},
{
"code": null,
"e": 3712,
"s": 3701,
"text": "Example : "
},
{
"code": null,
"e": 3896,
"s": 3712,
"text": "CREATE TABLE employee(\n 'id' INTEGER NOT NULL AUTO_INCREMENT,\n 'name' VARCHAR(30) NOT NULL,\n 'profile' VARCHAR(40) DEFAULT 'engineer',\n PRIMARY KEY ('id')\n)ENGINE = InnoDB; "
},
{
"code": null,
"e": 4138,
"s": 3896,
"text": "Note : You have ‘id’ column as AUTO_INCREMENT with a primary key constraint which ensures that each id is incremented value, avoiding duplication. Storage engine selected is ‘InnoDB’ allowing foreign key constraint and related transactions. "
},
{
"code": null,
"e": 4224,
"s": 4138,
"text": "12. AUTO_INCREMENT It is used to generate a unique identification field for new row. "
},
{
"code": null,
"e": 4326,
"s": 4224,
"text": "13. DROP TABLE table_name table_name : name of the table This statement deletes the mentioned table. "
},
{
"code": null,
"e": 4510,
"s": 4326,
"text": "14. RENAME TABLE old_table_name TO new_table_name old_table_name : name of the previous table. new_table_name : name of the new table. This statement renames the table to a new name. "
},
{
"code": null,
"e": 4760,
"s": 4510,
"text": "15. ALTER TABLE table_name ADD(column1, column2, column3..) table_name : name of the existing table. column1 : name of first column. column2 : name of second column. column3 : name of third column. This statement adds columns to the existing table. "
},
{
"code": null,
"e": 4941,
"s": 4760,
"text": "16. ALTER TABLE table_name DROP(column1) table_name : name of the existing table. column1 : name of first column. This statement deletes specified columns from the existing table. "
},
{
"code": null,
"e": 5348,
"s": 4941,
"text": "17. INSERT INTO table_name (column1, column2, column3 . . ) VALUES(value1, value2, value3 . . ) table_name : name of the existing table. column1 : name of first column. column2 : name of second column. column3 : name of third column. value1 : value for first column. value2 : value for second column. value3 : value for third column. This statement inserts a new record into a table with specified values. "
},
{
"code": null,
"e": 5798,
"s": 5348,
"text": "18. UPDATE table_name SET column1 = value1, column2 = value2, column3 = value3.. WHERE condition table_name : name of the table. column1 : name of first column. column2 : name of second column. column3 : name of third column. value1 : value for first column. value2 : value for second column. value3 : value for third column. condition : the condition statement. This statement update records in the table with the new given values for the columns. "
},
{
"code": null,
"e": 5885,
"s": 5798,
"text": "Note : WHERE clause in MySQL queries is used to filter rows for a specific condition. "
},
{
"code": null,
"e": 6045,
"s": 5885,
"text": "19. DELETE FROM table_name WHERE condition table_name : name of the table. condition : the condition statement. This statement deletes records from the table. "
},
{
"code": null,
"e": 6410,
"s": 6045,
"text": "20. SELECT column1, column2, column3.. FROM table_name WHERE condition table_name : name of the table. column1 : name of first column. column2 : name of second column. column3 : name of third column. condition : the condition statement. This statement executes and gives records from specific columns from the table which matches the condition after WHERE clause. "
},
{
"code": null,
"e": 6637,
"s": 6410,
"text": "21. SELECT * FROM table_name table_name: name of the table. Instead of specifying one column or many columns, you can use an asterisk (*) which represents all columns of table. This query retrieves all records from the table. "
},
{
"code": null,
"e": 6789,
"s": 6637,
"text": "22. COUNT The COUNT function is used to return total number of records matching a condition from any table. It is one of the known AGGREGATE function. "
},
{
"code": null,
"e": 6800,
"s": 6789,
"text": "Example : "
},
{
"code": null,
"e": 6831,
"s": 6800,
"text": "SELECT COUNT(*) from student; "
},
{
"code": null,
"e": 6945,
"s": 6831,
"text": "Note: AGGREGATE functions allow you to run calculations on data and provide information by using a SELECT query. "
},
{
"code": null,
"e": 7031,
"s": 6945,
"text": "23. MAX It is used to get the maximum numeric value of a particular column of table. "
},
{
"code": null,
"e": 7042,
"s": 7031,
"text": "Example : "
},
{
"code": null,
"e": 7083,
"s": 7042,
"text": "SELECT MAX(marks) FROM student_report; "
},
{
"code": null,
"e": 7172,
"s": 7083,
"text": "Note: The MIN and MAX functions work correctly on numeric as well as alphabetic values. "
},
{
"code": null,
"e": 7258,
"s": 7172,
"text": "24. MIN It is used to get the minimum numeric value of a particular column of table. "
},
{
"code": null,
"e": 7269,
"s": 7258,
"text": "Example : "
},
{
"code": null,
"e": 7310,
"s": 7269,
"text": "SELECT MIN(marks) FROM student_report; "
},
{
"code": null,
"e": 7415,
"s": 7310,
"text": "Note : The above given example queries can also be nested with each other depending on the requirement. "
},
{
"code": null,
"e": 7426,
"s": 7415,
"text": "Example : "
},
{
"code": null,
"e": 7523,
"s": 7426,
"text": "SELECT MIN(marks) \nFROM student_report \nWHERE marks > ( SELECT MIN(marks) from student_report); "
},
{
"code": null,
"e": 7598,
"s": 7523,
"text": "25. LIMIT It is used to set the limit of number of records in result set. "
},
{
"code": null,
"e": 7609,
"s": 7598,
"text": "Example : "
},
{
"code": null,
"e": 7646,
"s": 7609,
"text": "SELECT * \nFROM student limit 4, 10; "
},
{
"code": null,
"e": 7699,
"s": 7646,
"text": "This gives 10 records starting from the 5th record. "
},
{
"code": null,
"e": 7840,
"s": 7699,
"text": "26. BETWEEN It is used to get records from the specified lower limit to upper limit. This verifies if a value lies within that given range. "
},
{
"code": null,
"e": 7851,
"s": 7840,
"text": "Example : "
},
{
"code": null,
"e": 7904,
"s": 7851,
"text": "SELECT * FROM employee \nWHERE age BETWEEN 25 to 45. "
},
{
"code": null,
"e": 7990,
"s": 7904,
"text": "27. DISTINCT This is used to fetch all distinct records avoiding all duplicate ones. "
},
{
"code": null,
"e": 8001,
"s": 7990,
"text": "Example : "
},
{
"code": null,
"e": 8042,
"s": 8001,
"text": "SELECT DISTINCT profile \nFROM employee; "
},
{
"code": null,
"e": 8177,
"s": 8042,
"text": "28. IN clause This verifies if a row is contained in a set of given values. It is used instead of using so many OR clause in a query. "
},
{
"code": null,
"e": 8188,
"s": 8177,
"text": "Example : "
},
{
"code": null,
"e": 8240,
"s": 8188,
"text": "SELECT * \nFROM employee \nWHERE age IN(40, 50, 55); "
},
{
"code": null,
"e": 8341,
"s": 8240,
"text": "29. AND This condition in MySQL queries are used to filter the result data based on AND conditions. "
},
{
"code": null,
"e": 8352,
"s": 8341,
"text": "Example : "
},
{
"code": null,
"e": 8417,
"s": 8352,
"text": "SELECT NAME, AGE \nFROM student \nWHERE marks > 95 AND grade = 7; "
},
{
"code": null,
"e": 8516,
"s": 8417,
"text": "30. OR This condition in MySQL queries are used to filter the result data based on OR conditions. "
},
{
"code": null,
"e": 8527,
"s": 8516,
"text": "Example : "
},
{
"code": null,
"e": 8606,
"s": 8527,
"text": "SELECT * \nFROM student \nWHERE address = 'Hyderabad' OR address = 'Bangalore'; "
},
{
"code": null,
"e": 8714,
"s": 8606,
"text": "31. IS NULL This keyword is used for boolean comparison or to check if the data value of a column is null. "
},
{
"code": null,
"e": 8725,
"s": 8714,
"text": "Example : "
},
{
"code": null,
"e": 8781,
"s": 8725,
"text": "SELECT * \nFROM employee \nWHERE contact_number IS NULL; "
},
{
"code": null,
"e": 8854,
"s": 8781,
"text": "32. FOREIGN KEY It is used for pointing a PRIMARY KEY of another table. "
},
{
"code": null,
"e": 8865,
"s": 8854,
"text": "Example : "
},
{
"code": null,
"e": 9072,
"s": 8865,
"text": "CREATE TABLE Customers\n (\n id INT AUTO_INCREMENT PRIMARY KEY, \n name VARCHAR(30) NOT NULL, \n)\n\nCREATE TABLE Orders\n(\n order_id INT AUTO_INCREMENT PRIMARY KEY,\n FOREIGN KEY (id) REFERENCES Customers(id)\n ); "
},
{
"code": null,
"e": 9199,
"s": 9072,
"text": "Note: This is not used in the MYISAM storage engine of MySQL server. InnoDB storage engines supports foreign key constraints. "
},
{
"code": null,
"e": 9278,
"s": 9199,
"text": "33. LIKE This is used to fetch records matching for specified string pattern. "
},
{
"code": null,
"e": 9289,
"s": 9278,
"text": "Example : "
},
{
"code": null,
"e": 9391,
"s": 9289,
"text": "SELECT * \nFROM employee \nWHERE name LIKE 'Sh%';\n\nSELECT * \nFROM employee \nWHERE name LIKE '%Sh%'; "
},
{
"code": null,
"e": 9467,
"s": 9391,
"text": "Note: Percentage signs (%) in the query represent zero or more characters. "
},
{
"code": null,
"e": 9722,
"s": 9467,
"text": "34. JOINS Joins are the joining of two or more database tables to fetch data based on a common field. There are various types of joins with different names in different databases. Commonly known joins are self join, outer join, inner join and many more. "
},
{
"code": null,
"e": 9842,
"s": 9722,
"text": "Regular Join : It is the join which gets all the records from both the tables which exactly match the given condition. "
},
{
"code": null,
"e": 9853,
"s": 9842,
"text": "Example : "
},
{
"code": null,
"e": 9961,
"s": 9853,
"text": "SELECT student.name, department.name \nFROM student JOIN department ON student.department = department.name "
},
{
"code": null,
"e": 10100,
"s": 9961,
"text": "Left Join : It is the join which gets all the records that match the given condition, and also fetch all the records from the left table. "
},
{
"code": null,
"e": 10111,
"s": 10100,
"text": "Example : "
},
{
"code": null,
"e": 10225,
"s": 10111,
"text": "SELECT student.name, department.name \nFROM student LEFT JOIN department ON student.deptartment = department.name "
},
{
"code": null,
"e": 10366,
"s": 10225,
"text": "Right Join : It is the join which gets all the records that match the given condition, and also fetch all the records from the right table. "
},
{
"code": null,
"e": 10377,
"s": 10366,
"text": "Example : "
},
{
"code": null,
"e": 10491,
"s": 10377,
"text": "SELECT student.name, department.name \nFROM student RIGHT JOIN department on student.department = department.name "
},
{
"code": null,
"e": 10586,
"s": 10491,
"text": "35. ADD or DROP a column A new column can be added on a database table, if required later on. "
},
{
"code": null,
"e": 10597,
"s": 10586,
"text": "Example : "
},
{
"code": null,
"e": 10650,
"s": 10597,
"text": "ALTER TABLE employee ADD COLUMN salary VARCHAR(25); "
},
{
"code": null,
"e": 10711,
"s": 10650,
"text": "Similarly, any column can be deleted from a database table. "
},
{
"code": null,
"e": 10722,
"s": 10711,
"text": "Example : "
},
{
"code": null,
"e": 10764,
"s": 10722,
"text": "ALTER TABLE employee DROP COLUMN salary; "
},
{
"code": null,
"e": 10777,
"s": 10764,
"text": "Conclusion :"
},
{
"code": null,
"e": 11228,
"s": 10777,
"text": "Running MySQL queries are the most commonly-performed tasks used to get data within the process of database management. There are many database management tools like phpMyAdmin, that helps to perform queries and handle transactions comfortably with visual data results. You have scrolled the most common MySQL queries, which are used in daily coding practices. Developer can customize or enhance the queries with respect to a particular requirement. "
},
{
"code": null,
"e": 11248,
"s": 11228,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 11264,
"s": 11248,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 11274,
"s": 11264,
"text": "kalrap615"
},
{
"code": null,
"e": 11280,
"s": 11274,
"text": "mysql"
},
{
"code": null,
"e": 11289,
"s": 11280,
"text": "SQLmysql"
},
{
"code": null,
"e": 11294,
"s": 11289,
"text": "DBMS"
},
{
"code": null,
"e": 11299,
"s": 11294,
"text": "DBMS"
}
] |
How To Use Jupyter Notebook - An Ultimate Guide - GeeksforGeeks
|
28 Mar, 2022
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. Jupyter has support for over 40 different programming languages and Python is one of them. Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook itself.
Table Of Content
Installation
Starting Jupyter Notebook
Creating a Notebook
Hello World in Jupyter Notebook
Cells in Jupyter Notebook
Kernel
Naming the notebook
Notebook Extensions
Install Python and Jupyter using the Anaconda Distribution, which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science. You can download Anaconda’s latest Python3 version from here. Now, install the downloaded version of Anaconda. Installing Jupyter Notebook using pip:
python3 -m pip install --upgrade pip
python3 -m pip install jupyter
To start the jupyter notebook, type the below command in the terminal.
jupyter notebook
This will print some information about the notebook server in your terminal, including the URL of the web application (by default, http://localhost:8888) and then open your default web browser to this URL. After the notebook is opened, you’ll see the Notebook Dashboard, which will show a list of the notebooks, files, and subdirectories in the directory where the notebook server was started. Most of the time, you will wish to start a notebook server in the highest level directory containing notebooks. Often this will be your home directory.
To create a new notebook, click on the new button at the top right corner. Click it to open a drop-down list and then if you’ll click on Python3, it will open a new notebook. The web page should look like this:
After successfully installing and creating a notebook in Jupyter Notebook, let’s see how to write code in it. Jupyter notebook provides a cell for writing code in it. The type of code depends on the type of notebook you created. For example, if you created a Python3 notebook then you can write Python3 code in the cell. Now, let’s add the following code –
Python3
print("Hello World")
To run a cell either click the run button or press shift ⇧ + enter ⏎ after selecting the cell you want to execute. After writing the above code in the jupyter notebook, the output was: Note: When a cell has executed the label on the left i.e. ln[] changes to ln[1]. If the cell is still under execution the label remains ln[*].
Cells can be considered as the body of the Jupyter. In the above screenshot, the box with the green outline is a cell. There are 3 types of cell:
Code
Markup
Raw NBConverter
This is where the code is typed and when executed the code will display the output below the cell. The type of code depends on the type of the notebook you have created. For example, if the notebook of Python3 is created then the code of Python3 can be added. Consider the below example, where a simple code of the Fibonacci series is created and this code also takes input from the user. Example: The tex bar in the above code is prompted for taking input from the user. The output of the above code is as follows: Output:
Markdown is a popular markup language that is the superset of the HTML. Jupyter Notebook also supports markdown. The cell type can be changed to markdown using the cell menu. Adding Headers: Heading can be added by prefixing any line by single or multiple ‘#’ followed by space. Example: Output: Adding List: Adding List is really simple in Jupyter Notebook. The list can be added by using ‘*’ sign. And the Nested list can be created by using indentation. Example: Output: Adding Latex Equations: Latex expressions can be added by surrounding the latex code by ‘$’ and for writing the expressions in the middle, surrounds the latex code by ‘$$’. Example: Output: Adding Table: A table can be added by writing the content in the following format. Output: Note: The text can be made bold or italic by enclosing the text in ‘**’ and ‘*’ respectively.
Raw cells are provided to write the output directly. This cell is not evaluated by Jupyter notebook. After passing through nbconvert the raw cells arrives in the destination folder without any modification. For example, one can write full Python into a raw cell that can only be rendered by Python only after conversion by nbconvert.
A kernel runs behind every notebook. Whenever a cell is executed, the code inside the cell is executed within the kernel and the output is returned back to the cell to be displayed. The kernel continues to exist to the document as a whole and not for individual cells. For example, if a module is imported in one cell then, that module will be available for the whole document. See the below example for better understanding. Example: Note: The order of execution of each cell is stated to the left of the cell. In the above example, the cell with In[1] is executed first then the cell with In[2] is executed. Options for kernels: Jupyter Notebook provides various options for kernels. This can be useful if you want to reset things. The options are:
Restart: This will restart the kernels i.e. clearing all the variables that were defined, clearing the modules that were imported, etc.
Restart and Clear Output: This will do the same as above but will also clear all the output that was displayed below the cell.
Restart and Run All: This is also the same as above but will also run all the cells in the top-down order.
Interrupt: This option will interrupt the kernel execution. It can be useful in the case where the programs continue for execution or the kernel is stuck over some computation.
When the notebook is created, Jupyter Notebook names the notebook as Untitled as default. However, the notebook can be renamed. To rename the notebook just click on the word Untitled. This will prompt a dialogue box titled Rename Notebook. Enter the valid name for your notebook in the text bar, then click ok.
New functionality can be added to Jupyter through extensions. Extensions are javascript module. You can even write your own extension that can access the page’s DOM and the Jupyter Javascript API. Jupyter supports four types of extensions.
Kernel
IPyhton Kernel
Notebook
Notebook server
Most of the extensions can be installed using Python’s pip tool. If an extension can not be installed using pip, then install the extension using the below command.
jupyter nbextension install extension_name
The above only installs the extension but does not enables it. To enable it type the below command in the terminal.
jupyter nbextension enable extension_name
varshagumber28
Machine Learning
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
ML | Linear Regression
ML | Underfitting and Overfitting
Python | Decision tree implementation
Decision Tree Introduction with example
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Read JSON file using Python
|
[
{
"code": null,
"e": 24433,
"s": 24402,
"text": " \n28 Mar, 2022\n"
},
{
"code": null,
"e": 24947,
"s": 24433,
"text": "The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. Jupyter has support for over 40 different programming languages and Python is one of them. Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook itself."
},
{
"code": null,
"e": 24964,
"s": 24947,
"text": "Table Of Content"
},
{
"code": null,
"e": 24977,
"s": 24964,
"text": "Installation"
},
{
"code": null,
"e": 25003,
"s": 24977,
"text": "Starting Jupyter Notebook"
},
{
"code": null,
"e": 25023,
"s": 25003,
"text": "Creating a Notebook"
},
{
"code": null,
"e": 25055,
"s": 25023,
"text": "Hello World in Jupyter Notebook"
},
{
"code": null,
"e": 25081,
"s": 25055,
"text": "Cells in Jupyter Notebook"
},
{
"code": null,
"e": 25088,
"s": 25081,
"text": "Kernel"
},
{
"code": null,
"e": 25108,
"s": 25088,
"text": "Naming the notebook"
},
{
"code": null,
"e": 25128,
"s": 25108,
"text": "Notebook Extensions"
},
{
"code": null,
"e": 25459,
"s": 25128,
"text": "Install Python and Jupyter using the Anaconda Distribution, which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science. You can download Anaconda’s latest Python3 version from here. Now, install the downloaded version of Anaconda. Installing Jupyter Notebook using pip:"
},
{
"code": null,
"e": 25527,
"s": 25459,
"text": "python3 -m pip install --upgrade pip\npython3 -m pip install jupyter"
},
{
"code": null,
"e": 25598,
"s": 25527,
"text": "To start the jupyter notebook, type the below command in the terminal."
},
{
"code": null,
"e": 25615,
"s": 25598,
"text": "jupyter notebook"
},
{
"code": null,
"e": 26163,
"s": 25615,
"text": "This will print some information about the notebook server in your terminal, including the URL of the web application (by default, http://localhost:8888) and then open your default web browser to this URL. After the notebook is opened, you’ll see the Notebook Dashboard, which will show a list of the notebooks, files, and subdirectories in the directory where the notebook server was started. Most of the time, you will wish to start a notebook server in the highest level directory containing notebooks. Often this will be your home directory. "
},
{
"code": null,
"e": 26376,
"s": 26163,
"text": "To create a new notebook, click on the new button at the top right corner. Click it to open a drop-down list and then if you’ll click on Python3, it will open a new notebook. The web page should look like this: "
},
{
"code": null,
"e": 26734,
"s": 26376,
"text": "After successfully installing and creating a notebook in Jupyter Notebook, let’s see how to write code in it. Jupyter notebook provides a cell for writing code in it. The type of code depends on the type of notebook you created. For example, if you created a Python3 notebook then you can write Python3 code in the cell. Now, let’s add the following code – "
},
{
"code": null,
"e": 26742,
"s": 26734,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\nprint(\"Hello World\")\n\n\n\n\n\n",
"e": 26786,
"s": 26752,
"text": null
},
{
"code": null,
"e": 27115,
"s": 26786,
"text": "To run a cell either click the run button or press shift ⇧ + enter ⏎ after selecting the cell you want to execute. After writing the above code in the jupyter notebook, the output was: Note: When a cell has executed the label on the left i.e. ln[] changes to ln[1]. If the cell is still under execution the label remains ln[*]."
},
{
"code": null,
"e": 27261,
"s": 27115,
"text": "Cells can be considered as the body of the Jupyter. In the above screenshot, the box with the green outline is a cell. There are 3 types of cell:"
},
{
"code": null,
"e": 27266,
"s": 27261,
"text": "Code"
},
{
"code": null,
"e": 27273,
"s": 27266,
"text": "Markup"
},
{
"code": null,
"e": 27289,
"s": 27273,
"text": "Raw NBConverter"
},
{
"code": null,
"e": 27815,
"s": 27289,
"text": "This is where the code is typed and when executed the code will display the output below the cell. The type of code depends on the type of the notebook you have created. For example, if the notebook of Python3 is created then the code of Python3 can be added. Consider the below example, where a simple code of the Fibonacci series is created and this code also takes input from the user. Example: The tex bar in the above code is prompted for taking input from the user. The output of the above code is as follows: Output: "
},
{
"code": null,
"e": 28673,
"s": 27815,
"text": "Markdown is a popular markup language that is the superset of the HTML. Jupyter Notebook also supports markdown. The cell type can be changed to markdown using the cell menu. Adding Headers: Heading can be added by prefixing any line by single or multiple ‘#’ followed by space. Example: Output: Adding List: Adding List is really simple in Jupyter Notebook. The list can be added by using ‘*’ sign. And the Nested list can be created by using indentation. Example: Output: Adding Latex Equations: Latex expressions can be added by surrounding the latex code by ‘$’ and for writing the expressions in the middle, surrounds the latex code by ‘$$’. Example: Output: Adding Table: A table can be added by writing the content in the following format. Output: Note: The text can be made bold or italic by enclosing the text in ‘**’ and ‘*’ respectively."
},
{
"code": null,
"e": 29007,
"s": 28673,
"text": "Raw cells are provided to write the output directly. This cell is not evaluated by Jupyter notebook. After passing through nbconvert the raw cells arrives in the destination folder without any modification. For example, one can write full Python into a raw cell that can only be rendered by Python only after conversion by nbconvert."
},
{
"code": null,
"e": 29759,
"s": 29007,
"text": "A kernel runs behind every notebook. Whenever a cell is executed, the code inside the cell is executed within the kernel and the output is returned back to the cell to be displayed. The kernel continues to exist to the document as a whole and not for individual cells. For example, if a module is imported in one cell then, that module will be available for the whole document. See the below example for better understanding. Example: Note: The order of execution of each cell is stated to the left of the cell. In the above example, the cell with In[1] is executed first then the cell with In[2] is executed. Options for kernels: Jupyter Notebook provides various options for kernels. This can be useful if you want to reset things. The options are:"
},
{
"code": null,
"e": 29895,
"s": 29759,
"text": "Restart: This will restart the kernels i.e. clearing all the variables that were defined, clearing the modules that were imported, etc."
},
{
"code": null,
"e": 30022,
"s": 29895,
"text": "Restart and Clear Output: This will do the same as above but will also clear all the output that was displayed below the cell."
},
{
"code": null,
"e": 30129,
"s": 30022,
"text": "Restart and Run All: This is also the same as above but will also run all the cells in the top-down order."
},
{
"code": null,
"e": 30306,
"s": 30129,
"text": "Interrupt: This option will interrupt the kernel execution. It can be useful in the case where the programs continue for execution or the kernel is stuck over some computation."
},
{
"code": null,
"e": 30618,
"s": 30306,
"text": "When the notebook is created, Jupyter Notebook names the notebook as Untitled as default. However, the notebook can be renamed. To rename the notebook just click on the word Untitled. This will prompt a dialogue box titled Rename Notebook. Enter the valid name for your notebook in the text bar, then click ok. "
},
{
"code": null,
"e": 30858,
"s": 30618,
"text": "New functionality can be added to Jupyter through extensions. Extensions are javascript module. You can even write your own extension that can access the page’s DOM and the Jupyter Javascript API. Jupyter supports four types of extensions."
},
{
"code": null,
"e": 30865,
"s": 30858,
"text": "Kernel"
},
{
"code": null,
"e": 30880,
"s": 30865,
"text": "IPyhton Kernel"
},
{
"code": null,
"e": 30889,
"s": 30880,
"text": "Notebook"
},
{
"code": null,
"e": 30905,
"s": 30889,
"text": "Notebook server"
},
{
"code": null,
"e": 31070,
"s": 30905,
"text": "Most of the extensions can be installed using Python’s pip tool. If an extension can not be installed using pip, then install the extension using the below command."
},
{
"code": null,
"e": 31113,
"s": 31070,
"text": "jupyter nbextension install extension_name"
},
{
"code": null,
"e": 31229,
"s": 31113,
"text": "The above only installs the extension but does not enables it. To enable it type the below command in the terminal."
},
{
"code": null,
"e": 31271,
"s": 31229,
"text": "jupyter nbextension enable extension_name"
},
{
"code": null,
"e": 31286,
"s": 31271,
"text": "varshagumber28"
},
{
"code": null,
"e": 31305,
"s": 31286,
"text": "\nMachine Learning\n"
},
{
"code": null,
"e": 31314,
"s": 31305,
"text": "\nPython\n"
},
{
"code": null,
"e": 31519,
"s": 31314,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 31533,
"s": 31519,
"text": "Decision Tree"
},
{
"code": null,
"e": 31556,
"s": 31533,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 31590,
"s": 31556,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 31628,
"s": 31590,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 31668,
"s": 31628,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 31718,
"s": 31668,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 31740,
"s": 31718,
"text": "Python map() function"
},
{
"code": null,
"e": 31784,
"s": 31740,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 31802,
"s": 31784,
"text": "Python Dictionary"
}
] |
How to remove leading and trailing whitespace in a MySQL field?
|
To remove leading and trailing space, we can use the trim() in MySQL. Firstly, we will create a
table with the help of CREATE command.
Creating a table −
mysql> CREATE table TrailingANdLeadingDemo
-> (
-> SpaceTrailLead varchar(100)
-> );
Query OK, 0 rows affected (0.57 sec)
After creating a table, we will insert a record with the help of INSERT command. Let us insert a
record with leading and trailing space −
mysql> INSERT into TrailingANdLeadingDemo values(' john ');
Query OK, 1 row affected (0.12 sec)
We can display all the records with the help of SELECT command
mysql> SELECT * from TrailingANdLeadingDemo;
The following is the output
+----------------+
| SpaceTrailLead |
+----------------+
| john |
+----------------+
1 row in set (0.00 sec)
Now, record has been inserted with some space. The syntax to remove leading and trailing space with the help of trim() function is as follows −
UPDATE yourTableName set column_name=trim(column_name);
Now, I am applying the above query to remove trailing and leading space −
mysql> UPDATE TrailingANdLeadingDemo set SpaceTrailLead=trim(SpaceTrailLead);
Query OK, 1 row affected (0.17 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Now, we can check whether the space is removed or not. Use SELECT statement to display the
records −
mysql> SELECT * from TrailingANdLeadingDemo;
The following is the output
+----------------+
| SpaceTrailLead |
+----------------+
| john |
+----------------+
1 row in set (0.00 sec)
Look at the above output, the spaces have been removed clearly from the column.
|
[
{
"code": null,
"e": 1197,
"s": 1062,
"text": "To remove leading and trailing space, we can use the trim() in MySQL. Firstly, we will create a\ntable with the help of CREATE command."
},
{
"code": null,
"e": 1216,
"s": 1197,
"text": "Creating a table −"
},
{
"code": null,
"e": 1338,
"s": 1216,
"text": "mysql> CREATE table TrailingANdLeadingDemo\n-> (\n-> SpaceTrailLead varchar(100)\n-> );\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 1476,
"s": 1338,
"text": "After creating a table, we will insert a record with the help of INSERT command. Let us insert a\nrecord with leading and trailing space −"
},
{
"code": null,
"e": 1572,
"s": 1476,
"text": "mysql> INSERT into TrailingANdLeadingDemo values(' john ');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1635,
"s": 1572,
"text": "We can display all the records with the help of SELECT command"
},
{
"code": null,
"e": 1681,
"s": 1635,
"text": "mysql> SELECT * from TrailingANdLeadingDemo;\n"
},
{
"code": null,
"e": 1709,
"s": 1681,
"text": "The following is the output"
},
{
"code": null,
"e": 1828,
"s": 1709,
"text": "+----------------+\n| SpaceTrailLead |\n+----------------+\n| john |\n+----------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1972,
"s": 1828,
"text": "Now, record has been inserted with some space. The syntax to remove leading and trailing space with the help of trim() function is as follows −"
},
{
"code": null,
"e": 2029,
"s": 1972,
"text": "UPDATE yourTableName set column_name=trim(column_name);\n"
},
{
"code": null,
"e": 2103,
"s": 2029,
"text": "Now, I am applying the above query to remove trailing and leading space −"
},
{
"code": null,
"e": 2256,
"s": 2103,
"text": "mysql> UPDATE TrailingANdLeadingDemo set SpaceTrailLead=trim(SpaceTrailLead);\nQuery OK, 1 row affected (0.17 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 2357,
"s": 2256,
"text": "Now, we can check whether the space is removed or not. Use SELECT statement to display the\nrecords −"
},
{
"code": null,
"e": 2403,
"s": 2357,
"text": "mysql> SELECT * from TrailingANdLeadingDemo;\n"
},
{
"code": null,
"e": 2431,
"s": 2403,
"text": "The following is the output"
},
{
"code": null,
"e": 2550,
"s": 2431,
"text": "+----------------+\n| SpaceTrailLead |\n+----------------+\n| john |\n+----------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2630,
"s": 2550,
"text": "Look at the above output, the spaces have been removed clearly from the column."
}
] |
Create two unequal columns with Bootstrap Grid Layout
|
To create two unequal columns with Bootstrap Grid Layout, you can try to run the following code
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container-fluid">
<h2>Bootstrap Grid Unequal Columns</h2>
<div class = "row">
<div class = "col-sm-9" style = "background-color:blue; color: white;">Column One</div>
<div class = "col-sm-3" style = "background-color:red; color: white;">Column Two</div>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1158,
"s": 1062,
"text": "To create two unequal columns with Bootstrap Grid Layout, you can try to run the following code"
},
{
"code": null,
"e": 1168,
"s": 1158,
"text": "Live Demo"
},
{
"code": null,
"e": 1816,
"s": 1168,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container-fluid\">\n <h2>Bootstrap Grid Unequal Columns</h2>\n <div class = \"row\">\n <div class = \"col-sm-9\" style = \"background-color:blue; color: white;\">Column One</div>\n <div class = \"col-sm-3\" style = \"background-color:red; color: white;\">Column Two</div>\n </div>\n </div>\n </body>\n</html>"
}
] |
A Beginners guide to Building your own Face Recognition System to creep out your Friends | by Rachel Smith | Towards Data Science
|
Facial recognition systems are steadily making their way into our everyday lives. Built on AI, they can (with varying degrees of accuracy) pick you out of a crowd and identify you as an individual leading to all manner of consequences. Depending on where you live in the world, they are able to unlock your phone screen, pay for your chicken, get you arrested, keep you away from Taylor Swift and find your dream guy.
But how do these systems actually work, how accurate are they and who has permission to deploy them? To find out, let’s make one ourselves using free, open source software and pictures of friends.
Download the text editor Sublime Text and when it has finished, open it up and follow the installation instructions. This is where we will write the code which will become the programme.Check to see if you already have Python 3 on your computer. This is the programming language that we will write in. To do this for Macs open Terminal (in the Utilities folder in Applications) or for Windows open Command Prompt (press Windows + X and select Command Prompt). Then type the following and press enter:
Download the text editor Sublime Text and when it has finished, open it up and follow the installation instructions. This is where we will write the code which will become the programme.
Check to see if you already have Python 3 on your computer. This is the programming language that we will write in. To do this for Macs open Terminal (in the Utilities folder in Applications) or for Windows open Command Prompt (press Windows + X and select Command Prompt). Then type the following and press enter:
python3 -- version
if it says Python 3.7.3, ignore step 3. Otherwise continue.
3. Download Python 3. For Windows, when the download has finished, open up the python.exe file and under the ‘Modify’ menu, make sure ‘pip’ and ‘Add Python to environment variables’ is ticked and then press ‘install’.
4. Go to Terminal or Command Prompt again and type the following, pressing enter after each line to install the packages we need. The fourth line ‘dlib’ may take a while.
pip3 install cmakepip3 install face_recognitionpip3 install numpypip3 install dlibpip3 install opencv-python
If the final command asked you to install Xcode (for Macs), go to the App Store and install. This may take a while as it is quite large. Then re-type the last line (pip3 install opencv-python) and press enter.
1. Copy and paste this open source piece of code into Sublime Text. It may be easier to click ‘view raw’ at the bottom of the image to do this.
2. Save this file in the Desktop folder on your computer as recognise_face.py and create a folder called known_people (make sure this is also in the Desktop folder).
3. Now we can add pictures of people we wish to identify by saving an image of their face in the known_people folder. Make sure the person is facing forwards and is the only person in the photograph (crop if necessary). We name each file as the person’s name, as we wish it to appear on screen. In this case, only the .jpg files will be used.
4. Now we can run the programme by going back to the Terminal (Mac) or Command Prompt (Windows), writing the following and pressing enter
cd Desktoppython3 recognise_face.py
if an error message appears try:
python recognise_face.py
Pressing Ctrl + c with the Terminal window selected will exit the programme.
This blog post by Adam Geitgey explains in detail how this system works (and is very good).
To summarise, the face recognition process can be broken down into four steps.
Detect any faces which appear in the frame.
Detect any faces which appear in the frame.
2. Locate specific points on the face, for example the tip of the nose and the corners of each eye to create a mask. Then move that mask so that it is facing straight ahead using only transformations that preserve the original shape e.g rotation and zooming.
3. Encoding. This stage is about identifying key parts of a face (through the eyes of a computer) that will be similar for any photo of the same person and different for an image of anybody else. For humans this may be eye colour, hair style, nose shape etc but for computer vision, there is a highly effective set of 128 measurements for each face known as an embedding. These measurements have been found using machine learning by comparing thousands of images of labeled faces. We can then access a pre-trained network generated by this process to find the measurements we need.
4. Compare the 128 measurements from the faces detected in step 1 to all of those from the images in the known_people folder. If a similar enough set of measurements is found in this folder, it’s a match!
With a set of around 30 faces to recognise, this method holds up well. But what about if you were to scrape a picture of every one of your Facebook friends? Since the average user has 338 of them, this is a much larger set for comparison and would surely lead to ambiguity? In the next blog post, we will test this out, consider the legalities of making and utilising such an application and look further in to current applications of face recognition technology.
|
[
{
"code": null,
"e": 590,
"s": 172,
"text": "Facial recognition systems are steadily making their way into our everyday lives. Built on AI, they can (with varying degrees of accuracy) pick you out of a crowd and identify you as an individual leading to all manner of consequences. Depending on where you live in the world, they are able to unlock your phone screen, pay for your chicken, get you arrested, keep you away from Taylor Swift and find your dream guy."
},
{
"code": null,
"e": 787,
"s": 590,
"text": "But how do these systems actually work, how accurate are they and who has permission to deploy them? To find out, let’s make one ourselves using free, open source software and pictures of friends."
},
{
"code": null,
"e": 1288,
"s": 787,
"text": "Download the text editor Sublime Text and when it has finished, open it up and follow the installation instructions. This is where we will write the code which will become the programme.Check to see if you already have Python 3 on your computer. This is the programming language that we will write in. To do this for Macs open Terminal (in the Utilities folder in Applications) or for Windows open Command Prompt (press Windows + X and select Command Prompt). Then type the following and press enter:"
},
{
"code": null,
"e": 1475,
"s": 1288,
"text": "Download the text editor Sublime Text and when it has finished, open it up and follow the installation instructions. This is where we will write the code which will become the programme."
},
{
"code": null,
"e": 1790,
"s": 1475,
"text": "Check to see if you already have Python 3 on your computer. This is the programming language that we will write in. To do this for Macs open Terminal (in the Utilities folder in Applications) or for Windows open Command Prompt (press Windows + X and select Command Prompt). Then type the following and press enter:"
},
{
"code": null,
"e": 1809,
"s": 1790,
"text": "python3 -- version"
},
{
"code": null,
"e": 1869,
"s": 1809,
"text": "if it says Python 3.7.3, ignore step 3. Otherwise continue."
},
{
"code": null,
"e": 2087,
"s": 1869,
"text": "3. Download Python 3. For Windows, when the download has finished, open up the python.exe file and under the ‘Modify’ menu, make sure ‘pip’ and ‘Add Python to environment variables’ is ticked and then press ‘install’."
},
{
"code": null,
"e": 2258,
"s": 2087,
"text": "4. Go to Terminal or Command Prompt again and type the following, pressing enter after each line to install the packages we need. The fourth line ‘dlib’ may take a while."
},
{
"code": null,
"e": 2367,
"s": 2258,
"text": "pip3 install cmakepip3 install face_recognitionpip3 install numpypip3 install dlibpip3 install opencv-python"
},
{
"code": null,
"e": 2577,
"s": 2367,
"text": "If the final command asked you to install Xcode (for Macs), go to the App Store and install. This may take a while as it is quite large. Then re-type the last line (pip3 install opencv-python) and press enter."
},
{
"code": null,
"e": 2721,
"s": 2577,
"text": "1. Copy and paste this open source piece of code into Sublime Text. It may be easier to click ‘view raw’ at the bottom of the image to do this."
},
{
"code": null,
"e": 2887,
"s": 2721,
"text": "2. Save this file in the Desktop folder on your computer as recognise_face.py and create a folder called known_people (make sure this is also in the Desktop folder)."
},
{
"code": null,
"e": 3230,
"s": 2887,
"text": "3. Now we can add pictures of people we wish to identify by saving an image of their face in the known_people folder. Make sure the person is facing forwards and is the only person in the photograph (crop if necessary). We name each file as the person’s name, as we wish it to appear on screen. In this case, only the .jpg files will be used."
},
{
"code": null,
"e": 3368,
"s": 3230,
"text": "4. Now we can run the programme by going back to the Terminal (Mac) or Command Prompt (Windows), writing the following and pressing enter"
},
{
"code": null,
"e": 3404,
"s": 3368,
"text": "cd Desktoppython3 recognise_face.py"
},
{
"code": null,
"e": 3437,
"s": 3404,
"text": "if an error message appears try:"
},
{
"code": null,
"e": 3462,
"s": 3437,
"text": "python recognise_face.py"
},
{
"code": null,
"e": 3539,
"s": 3462,
"text": "Pressing Ctrl + c with the Terminal window selected will exit the programme."
},
{
"code": null,
"e": 3631,
"s": 3539,
"text": "This blog post by Adam Geitgey explains in detail how this system works (and is very good)."
},
{
"code": null,
"e": 3710,
"s": 3631,
"text": "To summarise, the face recognition process can be broken down into four steps."
},
{
"code": null,
"e": 3754,
"s": 3710,
"text": "Detect any faces which appear in the frame."
},
{
"code": null,
"e": 3798,
"s": 3754,
"text": "Detect any faces which appear in the frame."
},
{
"code": null,
"e": 4057,
"s": 3798,
"text": "2. Locate specific points on the face, for example the tip of the nose and the corners of each eye to create a mask. Then move that mask so that it is facing straight ahead using only transformations that preserve the original shape e.g rotation and zooming."
},
{
"code": null,
"e": 4639,
"s": 4057,
"text": "3. Encoding. This stage is about identifying key parts of a face (through the eyes of a computer) that will be similar for any photo of the same person and different for an image of anybody else. For humans this may be eye colour, hair style, nose shape etc but for computer vision, there is a highly effective set of 128 measurements for each face known as an embedding. These measurements have been found using machine learning by comparing thousands of images of labeled faces. We can then access a pre-trained network generated by this process to find the measurements we need."
},
{
"code": null,
"e": 4844,
"s": 4639,
"text": "4. Compare the 128 measurements from the faces detected in step 1 to all of those from the images in the known_people folder. If a similar enough set of measurements is found in this folder, it’s a match!"
}
] |
Java - Bitwise Operators Example
|
The following program is a simple example that demonstrates the bitwise operators. Copy and paste the following Java program in Test.java file and compile and run this program −
public class Test {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 15 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}
}
This will produce the following result −
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2555,
"s": 2377,
"text": "The following program is a simple example that demonstrates the bitwise operators. Copy and paste the following Java program in Test.java file and compile and run this program −"
},
{
"code": null,
"e": 3343,
"s": 2555,
"text": "public class Test {\n\n public static void main(String args[]) {\n int a = 60;\t/* 60 = 0011 1100 */\n int b = 13;\t/* 13 = 0000 1101 */\n int c = 0;\n\n c = a & b; /* 12 = 0000 1100 */\n System.out.println(\"a & b = \" + c );\n\n c = a | b; /* 61 = 0011 1101 */\n System.out.println(\"a | b = \" + c );\n\n c = a ^ b; /* 49 = 0011 0001 */\n System.out.println(\"a ^ b = \" + c );\n\n c = ~a; /*-61 = 1100 0011 */\n System.out.println(\"~a = \" + c );\n\n c = a << 2; /* 240 = 1111 0000 */\n System.out.println(\"a << 2 = \" + c );\n\n c = a >> 2; /* 15 = 1111 */\n System.out.println(\"a >> 2 = \" + c );\n\n c = a >>> 2; /* 15 = 0000 1111 */\n System.out.println(\"a >>> 2 = \" + c );\n }\n}"
},
{
"code": null,
"e": 3384,
"s": 3343,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3466,
"s": 3384,
"text": "a & b = 12\na | b = 61\na ^ b = 49\n~a = -61\na << 2 = 240\na >> 2 = 15\na >>> 2 = 15\n"
},
{
"code": null,
"e": 3499,
"s": 3466,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3515,
"s": 3499,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3548,
"s": 3515,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3564,
"s": 3548,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3599,
"s": 3564,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3613,
"s": 3599,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3647,
"s": 3613,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3661,
"s": 3647,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3698,
"s": 3661,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3713,
"s": 3698,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3746,
"s": 3713,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3765,
"s": 3746,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3772,
"s": 3765,
"text": " Print"
},
{
"code": null,
"e": 3783,
"s": 3772,
"text": " Add Notes"
}
] |
Job Sequencing Problem with Deadlines
|
In this problem, there is a list of jobs given. In the list, the deadline and the profits are also given for each job. Every job will take a single unit of time, so the minimum deadline for a job is 1. If only one job can be scheduled at a time, then maximize the profit.
To solve this problem, all subset of the set of jobs are generated to check whether the individual subset is feasible or not. Also, keep track on maximum profit for all feasible subset that has generated.
The time complexity of this algorithm is O(n^2)
Input:
A list of jobs with job id, deadline and profit. And the number of jobs n.
{('a', 2, 100), ('b', 1, 19), ('c', 2, 27), ('d', 1, 25), ('e', 3, 15)}
n = 5
Output:
Following is maximum profit sequence of job sequence: c a e
jobSequence(jobList, n)
Input − The list of jobs and the number of jobs present in the list.
Output − The sequence, how jobs are taken.
Begin
sort the jobs in jobList according to their profit create a list of job sequence and slot to track free time slots
initially make all slots are free
for all given jobs i do
for all jobs in the list from ending of the list do
if slot[j] is free then
jobSequence[j] := i
make slot[j] := fill
break the loop
done
done
for all slots when it is not free do
print id of job using jobList[jobSequence[i]]
done
End
#include<iostream>
#include<algorithm>
using namespace std;
struct Job {
char id;
int deadLine;
int profit;
};
bool comp(Job j1, Job j2) {
return (j1.profit > j2.profit); //compare jobs based on profit
}
int min(int a, int b) {
return (a<b)?a:b;
}
void jobSequence(Job jobList[], int n) {
sort(jobList, jobList+n, comp); //sort jobList on profit
int jobSeq[n]; // To store result (Sequence of jobs)
bool slot[n]; // To keep track of free time slots
for (int i=0; i<n; i++)
slot[i] = false; //initially all slots are free
for (int i=0; i<n; i++) { //for all given jobs
for (int j=min(n, jobList[i].deadLine)-1; j>=0; j--) { //search from last free slot
if (slot[j]==false) {
jobSeq[j] = i; // Add this job to job sequence
slot[j] = true; // mark this slot as occupied
break;
}
}
}
for (int i=0; i<n; i++)
if (slot[i])
cout << jobList[jobSeq[i]].id << " "; //display the sequence
}
int main() {
Job jobList[] = {{'a',2,100}, {'b',1,19}, {'c',2,27},{'d',1,25},{'e',3,15}};
int n = 5;
cout << "Following is maximum profit sequence of job sequence: ";
jobSequence(jobList, n);
}
Following is maximum profit sequence of job sequence: c a e
|
[
{
"code": null,
"e": 1334,
"s": 1062,
"text": "In this problem, there is a list of jobs given. In the list, the deadline and the profits are also given for each job. Every job will take a single unit of time, so the minimum deadline for a job is 1. If only one job can be scheduled at a time, then maximize the profit."
},
{
"code": null,
"e": 1539,
"s": 1334,
"text": "To solve this problem, all subset of the set of jobs are generated to check whether the individual subset is feasible or not. Also, keep track on maximum profit for all feasible subset that has generated."
},
{
"code": null,
"e": 1587,
"s": 1539,
"text": "The time complexity of this algorithm is O(n^2)"
},
{
"code": null,
"e": 1815,
"s": 1587,
"text": "Input:\nA list of jobs with job id, deadline and profit. And the number of jobs n.\n{('a', 2, 100), ('b', 1, 19), ('c', 2, 27), ('d', 1, 25), ('e', 3, 15)}\nn = 5\nOutput:\nFollowing is maximum profit sequence of job sequence: c a e"
},
{
"code": null,
"e": 1839,
"s": 1815,
"text": "jobSequence(jobList, n)"
},
{
"code": null,
"e": 1908,
"s": 1839,
"text": "Input − The list of jobs and the number of jobs present in the list."
},
{
"code": null,
"e": 1951,
"s": 1908,
"text": "Output − The sequence, how jobs are taken."
},
{
"code": null,
"e": 2446,
"s": 1951,
"text": "Begin\n sort the jobs in jobList according to their profit create a list of job sequence and slot to track free time slots\n initially make all slots are free\n for all given jobs i do\n for all jobs in the list from ending of the list do\n if slot[j] is free then\n jobSequence[j] := i\n make slot[j] := fill\n break the loop\n done\n done\n\n for all slots when it is not free do\n print id of job using jobList[jobSequence[i]]\n done\nEnd"
},
{
"code": null,
"e": 3690,
"s": 2446,
"text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\n\nstruct Job {\n char id;\n int deadLine;\n int profit;\n};\n\nbool comp(Job j1, Job j2) {\n return (j1.profit > j2.profit); //compare jobs based on profit\n}\n\nint min(int a, int b) {\n return (a<b)?a:b;\n}\n\nvoid jobSequence(Job jobList[], int n) {\n sort(jobList, jobList+n, comp); //sort jobList on profit\n\n int jobSeq[n]; // To store result (Sequence of jobs)\n bool slot[n]; // To keep track of free time slots\n\n for (int i=0; i<n; i++)\n slot[i] = false; //initially all slots are free\n\n for (int i=0; i<n; i++) { //for all given jobs\n for (int j=min(n, jobList[i].deadLine)-1; j>=0; j--) { //search from last free slot\n if (slot[j]==false) {\n jobSeq[j] = i; // Add this job to job sequence\n slot[j] = true; // mark this slot as occupied\n break;\n }\n }\n }\n\n for (int i=0; i<n; i++)\n if (slot[i])\n cout << jobList[jobSeq[i]].id << \" \"; //display the sequence\n}\n\nint main() {\n Job jobList[] = {{'a',2,100}, {'b',1,19}, {'c',2,27},{'d',1,25},{'e',3,15}};\n int n = 5;\n cout << \"Following is maximum profit sequence of job sequence: \";\n jobSequence(jobList, n);\n}"
},
{
"code": null,
"e": 3750,
"s": 3690,
"text": "Following is maximum profit sequence of job sequence: c a e"
}
] |
Bootstrap 4 - Text
|
Bootstrap provides text utilities to control text alignment, transform, weight and more.
The text can justified by using the .text-justify class and for left, right, and center alignment of text, use the text-left, text-right and text-center classes respectively.
The following example demonstrates usage of text alignment utilities −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
<style type = "text/css"></style>
</head>
<body>
<div class = "container">
<h2>Text alignment: Text Justify </h2>
<p class = "text-success">
The below text is justified by using the class "text-justify"
</p>
<p class = "text-justify">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to
make a type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
<h2>Text alignment: Left, Right, Center </h2>
<p class = "text-left">Text is aligned on Left side by using class "text-left"</p>
<p class = "text-center">Text is aligned at Center by using class "text-center"</p>
<p class = "text-right">Text is aligned on Right side by using class "text-right"</p>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
The below text is justified by using the class "text-justify"
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to
make a type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.
Text is aligned on Left side by using class "text-left"
Text is aligned at Center by using class "text-center"
Text is aligned on Right side by using class "text-right"
You can transform the text by using text capitalization classes as shown in the following example −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
<style type = "text/css"></style>
</head>
<body>
<div class = "container">
<h2>Text Transform</h2>
<p>Welcome to
<span class = "text-lowercase">tutorialspoint (text-lowercase)</span>.
</p>
<p>Welcome to
<span class = "text-uppercase">tutorialspoint (text-uppercase)</span>
</p>
<p>Welcome to
<span class = "text-capitalize">tutorials-point (text-capitalize)</span>
</p>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity =" sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
Welcome to
tutorialspoint (text-lowercase).
Welcome to
tutorialspoint (text-uppercase)
Welcome to
tutorials-point (text-capitalize)
You can change font weight of the text by using font-weight-* class and italicize the text by using font-italic class. The monospace font creates fixed width text, which takes the same amount of horizontal space.
The following example demonstrates usage of above utilities −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
<style type = "text/css"></style>
</head>
<body>
<div class = "container">
<h2>Font weight and italics</h2>
<p>
This text is <span class = "font-weight-bold">font-weight-bold </span>
</p>
<p>
This text is <span class = "font-weight-normal">font-weight-normal</span>
</p>
<p>
This text is <span class = "font-weight-light">font-weight-light</span>
</p>
<p>
This text is <span class = "font-italic">font-italic</span>
</p>
<h2>Monospace</h2>
<p class = "text-monospace">
This text is written by using 'text-monospace' class
</p>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
This text is font-weight-bold
This text is font-weight-normal
This text is font-weight-light
This text is font-italic
This text is written by using 'text-monospace' class
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1905,
"s": 1816,
"text": "Bootstrap provides text utilities to control text alignment, transform, weight and more."
},
{
"code": null,
"e": 2080,
"s": 1905,
"text": "The text can justified by using the .text-justify class and for left, right, and center alignment of text, use the text-left, text-right and text-center classes respectively."
},
{
"code": null,
"e": 2151,
"s": 2080,
"text": "The following example demonstrates usage of text alignment utilities −"
},
{
"code": null,
"e": 4796,
"s": 2151,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n <style type = \"text/css\"></style>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Text alignment: Text Justify </h2>\n <p class = \"text-success\">\n The below text is justified by using the class \"text-justify\"\n </p>\n <p class = \"text-justify\">\n Lorem Ipsum is simply dummy text of the printing and typesetting industry. \n Lorem Ipsum has been the industry's standard dummy text ever since the \n 1500s, when an unknown printer took a galley of type and scrambled it to \n make a type specimen book. It has survived not only five centuries, but \n also the leap into electronic typesetting, remaining essentially unchanged. \n It was popularised in the 1960s with the release of Letraset sheets \n containing Lorem Ipsum passages, and more recently with desktop publishing \n software like Aldus PageMaker including versions of Lorem Ipsum.\n </p>\n \n <h2>Text alignment: Left, Right, Center </h2>\n <p class = \"text-left\">Text is aligned on Left side by using class \"text-left\"</p>\n <p class = \"text-center\">Text is aligned at Center by using class \"text-center\"</p>\n <p class = \"text-right\">Text is aligned on Right side by using class \"text-right\"</p>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4835,
"s": 4796,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4920,
"s": 4835,
"text": "\n The below text is justified by using the class \"text-justify\"\n "
},
{
"code": null,
"e": 5609,
"s": 4920,
"text": "\n Lorem Ipsum is simply dummy text of the printing and typesetting industry. \n Lorem Ipsum has been the industry's standard dummy text ever since the \n 1500s, when an unknown printer took a galley of type and scrambled it to \n make a type specimen book. It has survived not only five centuries, but \n also the leap into electronic typesetting, remaining essentially unchanged. \n It was popularised in the 1960s with the release of Letraset sheets \n containing Lorem Ipsum passages, and more recently with desktop publishing \n software like Aldus PageMaker including versions of Lorem Ipsum.\n "
},
{
"code": null,
"e": 5665,
"s": 5609,
"text": "Text is aligned on Left side by using class \"text-left\""
},
{
"code": null,
"e": 5720,
"s": 5665,
"text": "Text is aligned at Center by using class \"text-center\""
},
{
"code": null,
"e": 5778,
"s": 5720,
"text": "Text is aligned on Right side by using class \"text-right\""
},
{
"code": null,
"e": 5878,
"s": 5778,
"text": "You can transform the text by using text capitalization classes as shown in the following example −"
},
{
"code": null,
"e": 7673,
"s": 5878,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n <style type = \"text/css\"></style>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Text Transform</h2>\n <p>Welcome to \n <span class = \"text-lowercase\">tutorialspoint (text-lowercase)</span>. \n </p>\n <p>Welcome to \n <span class = \"text-uppercase\">tutorialspoint (text-uppercase)</span>\n </p>\n <p>Welcome to \n <span class = \"text-capitalize\">tutorials-point (text-capitalize)</span>\n </p>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity =\" sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7712,
"s": 7673,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 7780,
"s": 7712,
"text": "Welcome to \n tutorialspoint (text-lowercase). \n "
},
{
"code": null,
"e": 7837,
"s": 7780,
"text": "Welcome to \n tutorialspoint (text-uppercase)\n"
},
{
"code": null,
"e": 7896,
"s": 7837,
"text": "Welcome to \n tutorials-point (text-capitalize)\n"
},
{
"code": null,
"e": 8110,
"s": 7896,
"text": "You can change font weight of the text by using font-weight-* class and italicize the text by using font-italic class. The monospace font creates fixed width text, which takes the same amount of horizontal space."
},
{
"code": null,
"e": 8172,
"s": 8110,
"text": "The following example demonstrates usage of above utilities −"
},
{
"code": null,
"e": 10199,
"s": 8172,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n <style type = \"text/css\"></style>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Font weight and italics</h2>\n <p>\n This text is <span class = \"font-weight-bold\">font-weight-bold </span>\n </p>\n <p>\n This text is <span class = \"font-weight-normal\">font-weight-normal</span>\n </p>\n <p>\n This text is <span class = \"font-weight-light\">font-weight-light</span>\n </p>\n <p>\n This text is <span class = \"font-italic\">font-italic</span>\n </p>\n \n <h2>Monospace</h2>\n <p class = \"text-monospace\">\n This text is written by using 'text-monospace' class\n </p>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 10238,
"s": 10199,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 10283,
"s": 10238,
"text": "\n This text is font-weight-bold \n"
},
{
"code": null,
"e": 10329,
"s": 10283,
"text": "\n This text is font-weight-normal\n"
},
{
"code": null,
"e": 10374,
"s": 10329,
"text": "\n This text is font-weight-light\n"
},
{
"code": null,
"e": 10413,
"s": 10374,
"text": "\n This text is font-italic\n"
},
{
"code": null,
"e": 10489,
"s": 10413,
"text": "\n This text is written by using 'text-monospace' class\n "
},
{
"code": null,
"e": 10522,
"s": 10489,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10536,
"s": 10522,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 10571,
"s": 10536,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10588,
"s": 10571,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10625,
"s": 10588,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 10653,
"s": 10625,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10686,
"s": 10653,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10698,
"s": 10686,
"text": " Azaz Patel"
},
{
"code": null,
"e": 10733,
"s": 10698,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10750,
"s": 10733,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 10783,
"s": 10750,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10803,
"s": 10783,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 10810,
"s": 10803,
"text": " Print"
},
{
"code": null,
"e": 10821,
"s": 10810,
"text": " Add Notes"
}
] |
Cryptography with Python - ROT13 Algorithm
|
Till now, you have learnt about reverse cipher and Caesar cipher algorithms. Now, let us discuss the ROT13 algorithm and its implementation.
ROT13 cipher refers to the abbreviated form Rotate by 13 places. It is a special case of Caesar Cipher in which shift is always 13. Every letter is shifted by 13 places to encrypt or decrypt the message.
The following diagram explains the ROT13 algorithm process pictorially −
The program implementation of ROT13 algorithm is as follows −
from string import maketrans
rot13trans = maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')
# Function to translate plain text
def rot13(text):
return text.translate(rot13trans)
def main():
txt = "ROT13 Algorithm"
print rot13(txt)
if __name__ == "__main__":
main()
You can see the ROT13 output as shown in the following image −
The ROT13 algorithm uses 13 shifts. Therefore, it is very easy to shift the characters in the reverse manner to decrypt the cipher text.
ROT13 cipher algorithm is considered as special case of Caesar Cipher. It is not a very secure algorithm and can be broken easily with frequency analysis or by just trying possible 25 keys whereas ROT13 can be broken by shifting 13 places. Therefore, it does not include any practical use.
10 Lectures
2 hours
Total Seminars
10 Lectures
2 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2433,
"s": 2292,
"text": "Till now, you have learnt about reverse cipher and Caesar cipher algorithms. Now, let us discuss the ROT13 algorithm and its implementation."
},
{
"code": null,
"e": 2637,
"s": 2433,
"text": "ROT13 cipher refers to the abbreviated form Rotate by 13 places. It is a special case of Caesar Cipher in which shift is always 13. Every letter is shifted by 13 places to encrypt or decrypt the message."
},
{
"code": null,
"e": 2710,
"s": 2637,
"text": "The following diagram explains the ROT13 algorithm process pictorially −"
},
{
"code": null,
"e": 2772,
"s": 2710,
"text": "The program implementation of ROT13 algorithm is as follows −"
},
{
"code": null,
"e": 3129,
"s": 2772,
"text": "from string import maketrans\n\nrot13trans = maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', \n 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')\n\n# Function to translate plain text\ndef rot13(text):\n return text.translate(rot13trans)\ndef main():\n txt = \"ROT13 Algorithm\"\n print rot13(txt)\n\t\nif __name__ == \"__main__\":\n main()"
},
{
"code": null,
"e": 3192,
"s": 3129,
"text": "You can see the ROT13 output as shown in the following image −"
},
{
"code": null,
"e": 3329,
"s": 3192,
"text": "The ROT13 algorithm uses 13 shifts. Therefore, it is very easy to shift the characters in the reverse manner to decrypt the cipher text."
},
{
"code": null,
"e": 3619,
"s": 3329,
"text": "ROT13 cipher algorithm is considered as special case of Caesar Cipher. It is not a very secure algorithm and can be broken easily with frequency analysis or by just trying possible 25 keys whereas ROT13 can be broken by shifting 13 places. Therefore, it does not include any practical use."
},
{
"code": null,
"e": 3652,
"s": 3619,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3668,
"s": 3652,
"text": " Total Seminars"
},
{
"code": null,
"e": 3701,
"s": 3668,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3724,
"s": 3701,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3731,
"s": 3724,
"text": " Print"
},
{
"code": null,
"e": 3742,
"s": 3731,
"text": " Add Notes"
}
] |
How to find the sum of variables by row in an R data frame?
|
To find the sum of variables by row we mean the sum of row values in the data frame. This can be easily done with the help of rowSums function. For example, if we have a data frame called df then the sum of variables by row can be found by using the command −
rowSums(df)
Consider the below data frame −
Live Demo
> x1<-rpois(20,2)
> x2<-rpois(20,2)
> x3<-rpois(20,2)
> df1<-data.frame(x1,x2,x3)
> df1
x1 x2 x3
1 0 2 3
2 1 0 1
3 1 0 2
4 3 3 2
5 4 2 2
6 3 1 5
7 2 2 1
8 4 2 2
9 2 4 0
10 3 1 5
11 3 1 2
12 0 3 1
13 2 3 0
14 1 1 0
15 1 1 1
16 3 1 0
17 1 2 1
18 1 0 2
19 4 2 1
20 0 2 3
Finding row sums for data in df1 −
> df1$x_total<-rowSums(df1)
> df1
x1 x2 x3 x_total
1 0 2 3 5
2 1 0 1 2
3 1 0 2 3
4 3 3 2 8
5 4 2 2 8
6 3 1 5 9
7 2 2 1 5
8 4 2 2 8
9 2 4 0 6
10 3 1 5 9
11 3 1 2 6
12 0 3 1 4
13 2 3 0 5
14 1 1 0 2
15 1 1 1 3
16 3 1 0 4
17 1 2 1 4
18 1 0 2 3
19 4 2 1 7
20 0 2 3 5
x1 x2 x3 x_total
1 0 2 3 5
2 1 0 1 2
3 1 0 2 3
4 3 3 2 8
5 4 2 2 8
6 3 1 5 9
7 2 2 1 5
8 4 2 2 8
9 2 4 0 6
10 3 1 5 9
11 3 1 2 6
12 0 3 1 4
13 2 3 0 5
14 1 1 0 2
15 1 1 1 3
16 3 1 0 4
17 1 2 1 4
18 1 0 2 3
19 4 2 1 7
20 0 2 3 5
Live Demo
> y1<-rnorm(20)
> y2<-rnorm(20)
> y3<-rnorm(20)
> df2<-data.frame(y1,y2,y3)
> df2
y1 y2 y3
1 0.59017486 -0.1196278 0.822573265
2 -1.12831016 0.7454030 0.173110462
3 0.65838766 -0.4798106 0.700891619
4 -3.09790550 -0.4401321 0.343264756
5 -0.27170928 -0.8106993 -0.658724220
6 1.51823786 0.1162130 -0.145487501
7 1.66852069 -0.4254530 -0.372181307
8 0.39011721 1.7260926 -0.253079767
9 0.12034466 0.4142485 -0.547526473
10 0.73264687 0.3537576 -0.248502362
11 -1.19683499 1.0923578 0.139092087
12 -0.02475713 -0.7436116 1.154820901
13 -1.68760189 -1.1306767 -0.002655384
14 -0.56164347 0.6580410 1.831938297
15 0.26013745 -0.6617675 -1.398981829
16 0.68685167 -1.2256218 0.435335557
17 -0.01735620 1.2882963 -0.378027363
18 -0.86458207 1.6013430 0.567320925
19 0.15593632 0.7086373 -0.231115639
20 0.54771681 1.8800467 0.235589089
Finding row sums for data in df2 −
> df2$y_total<-rowSums(df2)
> df2
y1 y2 y3 y_total
1 0.59017486 -0.1196278 0.822573265 1.29312029
2 -1.12831016 0.7454030 0.173110462 -0.20979674
3 0.65838766 -0.4798106 0.700891619 0.87946873
4 -3.09790550 -0.4401321 0.343264756 -3.19477280
5 -0.27170928 -0.8106993 -0.658724220 -1.74113281
6 1.51823786 0.1162130 -0.145487501 1.48896334
7 1.66852069 -0.4254530 -0.372181307 0.87088643
8 0.39011721 1.7260926 -0.253079767 1.86313004
9 0.12034466 0.4142485 -0.547526473 -0.01293328
10 0.73264687 0.3537576 -0.248502362 0.83790209
11 -1.19683499 1.0923578 0.139092087 0.03461487
12 -0.02475713 -0.7436116 1.154820901 0.38645212
13 -1.68760189 -1.1306767 -0.002655384 -2.82093399
14 -0.56164347 0.6580410 1.831938297 1.92833585
15 0.26013745 -0.6617675 -1.398981829 -1.80061190
16 0.68685167 -1.2256218 0.435335557 -0.10343459
17 -0.01735620 1.2882963 -0.378027363 0.89291278
18 -0.86458207 1.6013430 0.567320925 1.30408187
19 0.15593632 0.7086373 -0.231115639 0.63345799
20 0.54771681 1.8800467 0.235589089 2.66335255
|
[
{
"code": null,
"e": 1322,
"s": 1062,
"text": "To find the sum of variables by row we mean the sum of row values in the data frame. This can be easily done with the help of rowSums function. For example, if we have a data frame called df then the sum of variables by row can be found by using the command −"
},
{
"code": null,
"e": 1334,
"s": 1322,
"text": "rowSums(df)"
},
{
"code": null,
"e": 1366,
"s": 1334,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1376,
"s": 1366,
"text": "Live Demo"
},
{
"code": null,
"e": 1464,
"s": 1376,
"text": "> x1<-rpois(20,2)\n> x2<-rpois(20,2)\n> x3<-rpois(20,2)\n> df1<-data.frame(x1,x2,x3)\n> df1"
},
{
"code": null,
"e": 1716,
"s": 1464,
"text": " x1 x2 x3\n1 0 2 3\n2 1 0 1\n3 1 0 2\n4 3 3 2\n5 4 2 2\n6 3 1 5\n7 2 2 1\n8 4 2 2\n9 2 4 0\n10 3 1 5\n11 3 1 2\n12 0 3 1\n13 2 3 0\n14 1 1 0\n15 1 1 1\n16 3 1 0\n17 1 2 1\n18 1 0 2\n19 4 2 1\n20 0 2 3"
},
{
"code": null,
"e": 1751,
"s": 1716,
"text": "Finding row sums for data in df1 −"
},
{
"code": null,
"e": 1785,
"s": 1751,
"text": "> df1$x_total<-rowSums(df1)\n> df1"
},
{
"code": null,
"e": 2205,
"s": 1785,
"text": " x1 x2 x3 x_total\n1 0 2 3 5\n2 1 0 1 2\n3 1 0 2 3\n4 3 3 2 8\n5 4 2 2 8\n6 3 1 5 9\n7 2 2 1 5\n8 4 2 2 8\n9 2 4 0 6\n10 3 1 5 9\n11 3 1 2 6\n12 0 3 1 4\n13 2 3 0 5\n14 1 1 0 2\n15 1 1 1 3\n16 3 1 0 4\n17 1 2 1 4\n18 1 0 2 3\n19 4 2 1 7\n20 0 2 3 5"
},
{
"code": null,
"e": 2625,
"s": 2205,
"text": " x1 x2 x3 x_total\n1 0 2 3 5\n2 1 0 1 2\n3 1 0 2 3\n4 3 3 2 8\n5 4 2 2 8\n6 3 1 5 9\n7 2 2 1 5\n8 4 2 2 8\n9 2 4 0 6\n10 3 1 5 9\n11 3 1 2 6\n12 0 3 1 4\n13 2 3 0 5\n14 1 1 0 2\n15 1 1 1 3\n16 3 1 0 4\n17 1 2 1 4\n18 1 0 2 3\n19 4 2 1 7\n20 0 2 3 5"
},
{
"code": null,
"e": 2635,
"s": 2625,
"text": "Live Demo"
},
{
"code": null,
"e": 2717,
"s": 2635,
"text": "> y1<-rnorm(20)\n> y2<-rnorm(20)\n> y3<-rnorm(20)\n> df2<-data.frame(y1,y2,y3)\n> df2"
},
{
"code": null,
"e": 3536,
"s": 2717,
"text": " y1 y2 y3\n1 0.59017486 -0.1196278 0.822573265\n2 -1.12831016 0.7454030 0.173110462\n3 0.65838766 -0.4798106 0.700891619\n4 -3.09790550 -0.4401321 0.343264756\n5 -0.27170928 -0.8106993 -0.658724220\n6 1.51823786 0.1162130 -0.145487501\n7 1.66852069 -0.4254530 -0.372181307\n8 0.39011721 1.7260926 -0.253079767\n9 0.12034466 0.4142485 -0.547526473\n10 0.73264687 0.3537576 -0.248502362\n11 -1.19683499 1.0923578 0.139092087\n12 -0.02475713 -0.7436116 1.154820901\n13 -1.68760189 -1.1306767 -0.002655384\n14 -0.56164347 0.6580410 1.831938297\n15 0.26013745 -0.6617675 -1.398981829\n16 0.68685167 -1.2256218 0.435335557\n17 -0.01735620 1.2882963 -0.378027363\n18 -0.86458207 1.6013430 0.567320925\n19 0.15593632 0.7086373 -0.231115639\n20 0.54771681 1.8800467 0.235589089"
},
{
"code": null,
"e": 3571,
"s": 3536,
"text": "Finding row sums for data in df2 −"
},
{
"code": null,
"e": 3605,
"s": 3571,
"text": "> df2$y_total<-rowSums(df2)\n> df2"
},
{
"code": null,
"e": 4676,
"s": 3605,
"text": " y1 y2 y3 y_total\n1 0.59017486 -0.1196278 0.822573265 1.29312029\n2 -1.12831016 0.7454030 0.173110462 -0.20979674\n3 0.65838766 -0.4798106 0.700891619 0.87946873\n4 -3.09790550 -0.4401321 0.343264756 -3.19477280\n5 -0.27170928 -0.8106993 -0.658724220 -1.74113281\n6 1.51823786 0.1162130 -0.145487501 1.48896334\n7 1.66852069 -0.4254530 -0.372181307 0.87088643\n8 0.39011721 1.7260926 -0.253079767 1.86313004\n9 0.12034466 0.4142485 -0.547526473 -0.01293328\n10 0.73264687 0.3537576 -0.248502362 0.83790209\n11 -1.19683499 1.0923578 0.139092087 0.03461487\n12 -0.02475713 -0.7436116 1.154820901 0.38645212\n13 -1.68760189 -1.1306767 -0.002655384 -2.82093399\n14 -0.56164347 0.6580410 1.831938297 1.92833585\n15 0.26013745 -0.6617675 -1.398981829 -1.80061190\n16 0.68685167 -1.2256218 0.435335557 -0.10343459\n17 -0.01735620 1.2882963 -0.378027363 0.89291278\n18 -0.86458207 1.6013430 0.567320925 1.30408187\n19 0.15593632 0.7086373 -0.231115639 0.63345799\n20 0.54771681 1.8800467 0.235589089 2.66335255"
}
] |
Using Bitcoin Data in Python. Getting Started with the Bitcoin... | by Stephen Lewis | Towards Data Science
|
Bitcoin and cryptocurrencies, in general, have been on the up in recent months. From the sudden crash in March, Bitcoin has responded very well and has since almost doubled in price. Add to this the much-hyped halving event earlier this month, and there are now a lot of people curious and looking to start investing and trading.
Well, here I present the Python code you need to start analysing Bitcoin and get it into a usable form. I will hopefully demonstrate just how easy this is in Python using the pandas library. The full code can be found at the bottom of the article.
If you are not interested in cryptocurrencies then this might also be a good tutorial demonstrating the power of Python and pandas in data manipulation and analysis and might have some useful snippets of code to apply to other projects.
To get started, first, you will need to install the pandas library if you don’t have it already. Simply run the following in the command line.
pip install pandas
Or if you are using Anaconda like I am, you can open the Anaconda terminal in the environment you are using and then enter the following command.
conda install pandas
If no errors occur you should have the library installed correctly. We will do a final test in a minute.
For data analysis, I find Jupyter Notebook to be the best IDE as it allows you to run snippets of code in blocks and therefore can be a great time saver when importing and manipulating large datasets. However, any IDE will do.
Open a new script and save it. The first task is to test if the pandas library is installed correctly. Run the following code to import the library into your script. If no errors occur then you can proceed with the rest of the tutorial. If not, you will have to get the pandas library installed correctly — google will be your friend here.
import pandas as pd
The data I will be using is from Kaggle which is the worlds largest data science community and one of the best places to find a huge variety of datasets. This particular dataset is historical minute data of Bitcoin from 2012/01/01–2020/04/22.
Once you have downloaded and saved the csv file into the same directory as your script, you will now want to load that data. To do this we use the pd.read_csv() method in pandas, passing the data filename as a string. This creates a data frame with all the data from the csv file.
We will also run the .head() method on the data frame which shows us the first 5 rows of my data. As you can see, there is one row of data followed by four successive rows of NaN values. This is because some data is missing and therefore we have some cleaning up to do. This is due to a number of reasons but it seems that early in this dataset the data was not archived every minute so large chunks are missing.
raw_data = pd.read_csv("bitstampUSD_1-min_data_2012-01-01_to_2020-04-22.csv")raw_data.head()
Running the .tail() method on the data frame will shows the last 5 rows and you can see that these rows are in fact full. Also, note the number of rows in this dataset from the data frame index column (far left). Over four million! Way too many for Excel but Python and pandas handle it with ease.
raw_data.tail()
So now we want to create a data frame with all the rows with NaN values in them removed. In pandas, this is incredibly easy and we just use the .dropna() method on our data frame and assign that to a new data frame we call df. This is the data frame containing all the useful data that we will use in our analysis going forward.
We also call the .reset_index() method on the data frame so that the index column is reset. This assigns an index value starting at 0 for the first row of data, 1 for the second row and so on. We will also pass the argument inplace=True. This is commonly used in pandas and what it does is it tell Python that we want our original data frame to become the new edited version of that data frame. If inplace is not set to True then the data frame we are working on will be unchanged after the line is run. Explore this behaviour using the .head() method and looking at the index values.
We also pass a second argument drop=True. By default, the .reset_index() method will reset the index of our data but the original index column will be copied to a new column called “index”. We have no use for this additional column and so we will drop this. This could also be achieved using the .drop() method on the data frame and specifying the column name to drop.
df = raw_data.dropna()df.reset_index(inplace=True, drop=True)df.head()
You can see that the ‘Timestamp’ column is in a weird format, this is in fact the UNIX time format and so we would like to convert this to UTC time. We do this using the pd.to_datetime() method. We will pass the arguments for the data we want to perform this function on, which is the ‘Timestamp’ Column of our data and also we will pass the argument unit=’s’ which tells the function that the units of our inputted UNIX times are seconds. We save the output of this function to the ‘Timestamp’ column in our data frame using the line of code below. Note that in pandas to reference the data inside a column, we use the following notion df[‘Timestamp’]. Where the string passed inside the square brackets is the name of the column.
df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='s')df.head()
We can see here that part of the dataset is actually from 2011. For completeness, I will remove these four rows. The easiest way to do this when there is only a few rows to remove is to simply specify the indices of the rows in a list and pass this into the .drop() method. We also have to pass in the argument inplace=True again. And then finally fix the index like we did before.
df.drop([0,1,2,3], inplace=True)df.reset_index(inplace=True, drop=True)df.head()
So now we have our data in a nice structure and hopefully all the data in our data frame. A very quick check to verify that everything looks good at this point is to simply plot the price of bitcoin over time. We will do this by
running the .plot() method on the data frame and then specifying the columns we want to be on out x and y axes. The .plot() method in pandas actually uses the matplotlib library in the background to display the graph and will try to choose sensible default settings for the axes. The graph can of course be customised if you wish.
df.plot(x="Timestamp",y="Weighted_Price")
Great! So our data looks to be correct and therefore we can proceed to the more interesting part which is to analyse or manipulate the data. One thing that you might want to do is to create a new column that processes the data in some way. An example would be to find the difference between each successive point in time.
We can do this using a method built into pandas called .diff(). We simply have to specify the column we wish to create using the following notation df[“Title of new column”] and set this equal to the column we wish to find the difference of with the .diff() method.
df["closeDiff"] = df["Close"].diff()df.head()
Notice the new column we created called “closeDiff”.
Now lets imagine that we want to create data frames for each of the years in our data. For example, a data frame df19 for all the data from 2019. One way to do this would be to first create a column called ‘year’ that contains values of the year at each data point. And then we will create a new dataframe containing only the rows of data where the ‘year’ column equals 2019.
To do this we will first create a ‘year’ column. We feed our ‘Timestamp’ column in to the pd.DatetimeIndex class and ask for the .year attribute. This returns the value of the year for each of our time stamps and we assigned this data to a new column that we define as ‘year’.
df["year"] = pd.DatetimeIndex(df["Timestamp"]).yeardf.head()
So now we want a new data frame df19, which contains all the rows in our dataframe df, that have the value 2019 in the ‘year’ column. To do that we write the following line of code. This notation can be slightly confusing but here we simply are saying, get all the rows with the data frame df where the ‘year’ column equals 2019 and assign it to a new data frame called df19.
df19 = df[df["year"] == 2019]df19.reset_index(inplace=True, drop=True)df19.head()
Now we can plot just like before the data but this time just for the year 2019.
df19.plot(x="Timestamp",y="Weighted_Price")
So now you have clean data and perhaps you have added to the data or made a subset. It is common that you want to save this data so then you don’t have to run this code again. This is very easy using the .to_csv() method on the data frame. Below is the code I use to save the df19 data frame so I can use it easily in the future. The first argument you pass to the method is the filename you wish to save it as and the index=False tells Python not to save the index of the data frame to a column in the csv file which is usually unwanted.
df19.to_csv('btc19.csv', index=False)
There you have it, a basic framework to get you started using this Bitcoin historical dataset along with some basic things that you can do in Python and pandas. The full streamlined code without the .head() and .tail() calls can be found below.
|
[
{
"code": null,
"e": 502,
"s": 172,
"text": "Bitcoin and cryptocurrencies, in general, have been on the up in recent months. From the sudden crash in March, Bitcoin has responded very well and has since almost doubled in price. Add to this the much-hyped halving event earlier this month, and there are now a lot of people curious and looking to start investing and trading."
},
{
"code": null,
"e": 750,
"s": 502,
"text": "Well, here I present the Python code you need to start analysing Bitcoin and get it into a usable form. I will hopefully demonstrate just how easy this is in Python using the pandas library. The full code can be found at the bottom of the article."
},
{
"code": null,
"e": 987,
"s": 750,
"text": "If you are not interested in cryptocurrencies then this might also be a good tutorial demonstrating the power of Python and pandas in data manipulation and analysis and might have some useful snippets of code to apply to other projects."
},
{
"code": null,
"e": 1130,
"s": 987,
"text": "To get started, first, you will need to install the pandas library if you don’t have it already. Simply run the following in the command line."
},
{
"code": null,
"e": 1149,
"s": 1130,
"text": "pip install pandas"
},
{
"code": null,
"e": 1295,
"s": 1149,
"text": "Or if you are using Anaconda like I am, you can open the Anaconda terminal in the environment you are using and then enter the following command."
},
{
"code": null,
"e": 1316,
"s": 1295,
"text": "conda install pandas"
},
{
"code": null,
"e": 1421,
"s": 1316,
"text": "If no errors occur you should have the library installed correctly. We will do a final test in a minute."
},
{
"code": null,
"e": 1648,
"s": 1421,
"text": "For data analysis, I find Jupyter Notebook to be the best IDE as it allows you to run snippets of code in blocks and therefore can be a great time saver when importing and manipulating large datasets. However, any IDE will do."
},
{
"code": null,
"e": 1988,
"s": 1648,
"text": "Open a new script and save it. The first task is to test if the pandas library is installed correctly. Run the following code to import the library into your script. If no errors occur then you can proceed with the rest of the tutorial. If not, you will have to get the pandas library installed correctly — google will be your friend here."
},
{
"code": null,
"e": 2008,
"s": 1988,
"text": "import pandas as pd"
},
{
"code": null,
"e": 2251,
"s": 2008,
"text": "The data I will be using is from Kaggle which is the worlds largest data science community and one of the best places to find a huge variety of datasets. This particular dataset is historical minute data of Bitcoin from 2012/01/01–2020/04/22."
},
{
"code": null,
"e": 2532,
"s": 2251,
"text": "Once you have downloaded and saved the csv file into the same directory as your script, you will now want to load that data. To do this we use the pd.read_csv() method in pandas, passing the data filename as a string. This creates a data frame with all the data from the csv file."
},
{
"code": null,
"e": 2945,
"s": 2532,
"text": "We will also run the .head() method on the data frame which shows us the first 5 rows of my data. As you can see, there is one row of data followed by four successive rows of NaN values. This is because some data is missing and therefore we have some cleaning up to do. This is due to a number of reasons but it seems that early in this dataset the data was not archived every minute so large chunks are missing."
},
{
"code": null,
"e": 3038,
"s": 2945,
"text": "raw_data = pd.read_csv(\"bitstampUSD_1-min_data_2012-01-01_to_2020-04-22.csv\")raw_data.head()"
},
{
"code": null,
"e": 3336,
"s": 3038,
"text": "Running the .tail() method on the data frame will shows the last 5 rows and you can see that these rows are in fact full. Also, note the number of rows in this dataset from the data frame index column (far left). Over four million! Way too many for Excel but Python and pandas handle it with ease."
},
{
"code": null,
"e": 3352,
"s": 3336,
"text": "raw_data.tail()"
},
{
"code": null,
"e": 3681,
"s": 3352,
"text": "So now we want to create a data frame with all the rows with NaN values in them removed. In pandas, this is incredibly easy and we just use the .dropna() method on our data frame and assign that to a new data frame we call df. This is the data frame containing all the useful data that we will use in our analysis going forward."
},
{
"code": null,
"e": 4266,
"s": 3681,
"text": "We also call the .reset_index() method on the data frame so that the index column is reset. This assigns an index value starting at 0 for the first row of data, 1 for the second row and so on. We will also pass the argument inplace=True. This is commonly used in pandas and what it does is it tell Python that we want our original data frame to become the new edited version of that data frame. If inplace is not set to True then the data frame we are working on will be unchanged after the line is run. Explore this behaviour using the .head() method and looking at the index values."
},
{
"code": null,
"e": 4635,
"s": 4266,
"text": "We also pass a second argument drop=True. By default, the .reset_index() method will reset the index of our data but the original index column will be copied to a new column called “index”. We have no use for this additional column and so we will drop this. This could also be achieved using the .drop() method on the data frame and specifying the column name to drop."
},
{
"code": null,
"e": 4706,
"s": 4635,
"text": "df = raw_data.dropna()df.reset_index(inplace=True, drop=True)df.head()"
},
{
"code": null,
"e": 5438,
"s": 4706,
"text": "You can see that the ‘Timestamp’ column is in a weird format, this is in fact the UNIX time format and so we would like to convert this to UTC time. We do this using the pd.to_datetime() method. We will pass the arguments for the data we want to perform this function on, which is the ‘Timestamp’ Column of our data and also we will pass the argument unit=’s’ which tells the function that the units of our inputted UNIX times are seconds. We save the output of this function to the ‘Timestamp’ column in our data frame using the line of code below. Note that in pandas to reference the data inside a column, we use the following notion df[‘Timestamp’]. Where the string passed inside the square brackets is the name of the column."
},
{
"code": null,
"e": 5507,
"s": 5438,
"text": "df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='s')df.head()"
},
{
"code": null,
"e": 5889,
"s": 5507,
"text": "We can see here that part of the dataset is actually from 2011. For completeness, I will remove these four rows. The easiest way to do this when there is only a few rows to remove is to simply specify the indices of the rows in a list and pass this into the .drop() method. We also have to pass in the argument inplace=True again. And then finally fix the index like we did before."
},
{
"code": null,
"e": 5970,
"s": 5889,
"text": "df.drop([0,1,2,3], inplace=True)df.reset_index(inplace=True, drop=True)df.head()"
},
{
"code": null,
"e": 6199,
"s": 5970,
"text": "So now we have our data in a nice structure and hopefully all the data in our data frame. A very quick check to verify that everything looks good at this point is to simply plot the price of bitcoin over time. We will do this by"
},
{
"code": null,
"e": 6530,
"s": 6199,
"text": "running the .plot() method on the data frame and then specifying the columns we want to be on out x and y axes. The .plot() method in pandas actually uses the matplotlib library in the background to display the graph and will try to choose sensible default settings for the axes. The graph can of course be customised if you wish."
},
{
"code": null,
"e": 6572,
"s": 6530,
"text": "df.plot(x=\"Timestamp\",y=\"Weighted_Price\")"
},
{
"code": null,
"e": 6894,
"s": 6572,
"text": "Great! So our data looks to be correct and therefore we can proceed to the more interesting part which is to analyse or manipulate the data. One thing that you might want to do is to create a new column that processes the data in some way. An example would be to find the difference between each successive point in time."
},
{
"code": null,
"e": 7160,
"s": 6894,
"text": "We can do this using a method built into pandas called .diff(). We simply have to specify the column we wish to create using the following notation df[“Title of new column”] and set this equal to the column we wish to find the difference of with the .diff() method."
},
{
"code": null,
"e": 7206,
"s": 7160,
"text": "df[\"closeDiff\"] = df[\"Close\"].diff()df.head()"
},
{
"code": null,
"e": 7259,
"s": 7206,
"text": "Notice the new column we created called “closeDiff”."
},
{
"code": null,
"e": 7635,
"s": 7259,
"text": "Now lets imagine that we want to create data frames for each of the years in our data. For example, a data frame df19 for all the data from 2019. One way to do this would be to first create a column called ‘year’ that contains values of the year at each data point. And then we will create a new dataframe containing only the rows of data where the ‘year’ column equals 2019."
},
{
"code": null,
"e": 7912,
"s": 7635,
"text": "To do this we will first create a ‘year’ column. We feed our ‘Timestamp’ column in to the pd.DatetimeIndex class and ask for the .year attribute. This returns the value of the year for each of our time stamps and we assigned this data to a new column that we define as ‘year’."
},
{
"code": null,
"e": 7973,
"s": 7912,
"text": "df[\"year\"] = pd.DatetimeIndex(df[\"Timestamp\"]).yeardf.head()"
},
{
"code": null,
"e": 8349,
"s": 7973,
"text": "So now we want a new data frame df19, which contains all the rows in our dataframe df, that have the value 2019 in the ‘year’ column. To do that we write the following line of code. This notation can be slightly confusing but here we simply are saying, get all the rows with the data frame df where the ‘year’ column equals 2019 and assign it to a new data frame called df19."
},
{
"code": null,
"e": 8432,
"s": 8349,
"text": "df19 = df[df[\"year\"] == 2019]df19.reset_index(inplace=True, drop=True)df19.head()"
},
{
"code": null,
"e": 8512,
"s": 8432,
"text": "Now we can plot just like before the data but this time just for the year 2019."
},
{
"code": null,
"e": 8556,
"s": 8512,
"text": "df19.plot(x=\"Timestamp\",y=\"Weighted_Price\")"
},
{
"code": null,
"e": 9095,
"s": 8556,
"text": "So now you have clean data and perhaps you have added to the data or made a subset. It is common that you want to save this data so then you don’t have to run this code again. This is very easy using the .to_csv() method on the data frame. Below is the code I use to save the df19 data frame so I can use it easily in the future. The first argument you pass to the method is the filename you wish to save it as and the index=False tells Python not to save the index of the data frame to a column in the csv file which is usually unwanted."
},
{
"code": null,
"e": 9133,
"s": 9095,
"text": "df19.to_csv('btc19.csv', index=False)"
}
] |
Get a list of Constraints from MySQL Database?
|
To get a list of constraints from MySQL database, use the following syntax −
select *from information_schema.table_constraints where constraint_schema = 'yourDatabaseName';
Here, we will get the constraints from the database “business”. The following is the query to list the constraints of all the tables in the database “business” −
mysql> select *
−> from information_schema.table_constraints
−> where constraint_schema = 'business';
The following is the output displaying all the constraints −
+--------------------+-------------------+--------------------------+--------------+------------------------------+-----------------+
| CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME | CONSTRAINT_TYPE |
+--------------------+-------------------+--------------------------+--------------+------------------------------+-----------------+
| def | business | PRIMARY | business | primarytable | PRIMARY KEY |
| def | business | PRIMARY | business | primarytable1 | PRIMARY KEY |
| def | business | PRIMARY | business | autoincrementtable | PRIMARY KEY |
| def | business | PRIMARY | business | demoauto | PRIMARY KEY |
| def | business | PRIMARY | business | autoincrement | PRIMARY KEY |
| def | business | PRIMARY | business | primarytabledemo | PRIMARY KEY |
| def | business | PRIMARY | business | sequencedemo | PRIMARY KEY |
| def | business | PRIMARY | business | updtable | PRIMARY KEY |
| def | business | PRIMARY | business | transcationdemo | PRIMARY KEY |
| def | business | PRIMARY | business | triggedemo | PRIMARY KEY |
| def | business | PRIMARY | business | usernameandpassworddemo | PRIMARY KEY |
| def | business | UserId | business | usernameandpassworddemo | UNIQUE |
| def | business | PRIMARY | business | tblp | PRIMARY KEY |
| def | business | name | business | uniquedemo | UNIQUE |
| def | business | name | business | uniqueconstdemo | UNIQUE |
| def | business | PRIMARY | business | keydemo | PRIMARY KEY |
| def | business | PRIMARY | business | nextiddemo | PRIMARY KEY |
| def | business | PRIMARY | business | tablepri | PRIMARY KEY |
| def | business | ConstFK | business | tabledemo2 | UNIQUE |
| def | business | ConstFK | business | tabledemo3 | UNIQUE |
| def | business | PRIMARY | business | college | PRIMARY KEY |
| def | business | id | business | uniquedemo1 | UNIQUE |
| def | business | id | business | uniqueautoid | UNIQUE |
| def | business | PRIMARY | business | schemadatabasemethoddemo | PRIMARY KEY |
| def | business | PRIMARY | business | employeeinformation | PRIMARY KEY |
| def | business | name | business | addingunique | UNIQUE |
| def | business | PRIMARY | business | parentdemo | PRIMARY KEY |
| def | business | PRIMARY | business | lastinsertrecordiddemo | PRIMARY KEY |
| def | business | PRIMARY | business | demoindex | PRIMARY KEY |
| def | business | PRIMARY | business | compositeprimarykey | PRIMARY KEY |
| def | business | PRIMARY | business | addingautoincrement | PRIMARY KEY |
| def | business | Id | business | uniqueconstrainttable | UNIQUE |
| def | business | PRIMARY | business | mergedemo1 | PRIMARY KEY |
| def | business | PRIMARY | business | mergedemo2 | PRIMARY KEY |
| def | business | PRIMARY | business | foreigntable1 | PRIMARY KEY |
| def | business | PRIMARY | business | twoprimarykeytabledemo | PRIMARY KEY |
| def | business | PRIMARY | business | showconstraintsdemo | PRIMARY KEY |
| def | business | BookAuthor | business | showconstraintsdemo | UNIQUE |
| def | business | PRIMARY | business | autoincrementtozero | PRIMARY KEY |
| def | business | PRIMARY | business | altertabletoaddautoincrement | PRIMARY KEY |
| def | business | PRIMARY | business | addingprimarykeydemo | PRIMARY KEY |
| def | business | PRIMARY | business | resetprimarykey | PRIMARY KEY |
| def | business | constFKPK | business | foreigntable | FOREIGN KEY |
| def | business | FKConst | business | foreigntabledemo | FOREIGN KEY |
| def | business | ConstFK | business | tblf | FOREIGN KEY |
| def | business | StudCollegeConst | business | studentenrollment | FOREIGN KEY |
| def | business | ConstChild | business | childdemo | FOREIGN KEY |
| def | business | primarytable1demo_ibfk_1 | business | primarytable1demo | FOREIGN KEY |
+--------------------+-------------------+--------------------------+--------------+------------------------------+-----------------+
48 rows in set, 2 warnings (0.24 sec)
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To get a list of constraints from MySQL database, use the following syntax −"
},
{
"code": null,
"e": 1235,
"s": 1139,
"text": "select *from information_schema.table_constraints where constraint_schema = 'yourDatabaseName';"
},
{
"code": null,
"e": 1397,
"s": 1235,
"text": "Here, we will get the constraints from the database “business”. The following is the query to list the constraints of all the tables in the database “business” −"
},
{
"code": null,
"e": 1505,
"s": 1397,
"text": "mysql> select *\n −> from information_schema.table_constraints\n −> where constraint_schema = 'business';"
},
{
"code": null,
"e": 1566,
"s": 1505,
"text": "The following is the output displaying all the constraints −"
},
{
"code": null,
"e": 8575,
"s": 1566,
"text": "+--------------------+-------------------+--------------------------+--------------+------------------------------+-----------------+\n| CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME | CONSTRAINT_TYPE |\n+--------------------+-------------------+--------------------------+--------------+------------------------------+-----------------+\n| def | business | PRIMARY | business | primarytable | PRIMARY KEY |\n| def | business | PRIMARY | business | primarytable1 | PRIMARY KEY |\n| def | business | PRIMARY | business | autoincrementtable | PRIMARY KEY |\n| def | business | PRIMARY | business | demoauto | PRIMARY KEY |\n| def | business | PRIMARY | business | autoincrement | PRIMARY KEY |\n| def | business | PRIMARY | business | primarytabledemo | PRIMARY KEY |\n| def | business | PRIMARY | business | sequencedemo | PRIMARY KEY |\n| def | business | PRIMARY | business | updtable | PRIMARY KEY |\n| def | business | PRIMARY | business | transcationdemo | PRIMARY KEY |\n| def | business | PRIMARY | business | triggedemo | PRIMARY KEY |\n| def | business | PRIMARY | business | usernameandpassworddemo | PRIMARY KEY |\n| def | business | UserId | business | usernameandpassworddemo | UNIQUE |\n| def | business | PRIMARY | business | tblp | PRIMARY KEY |\n| def | business | name | business | uniquedemo | UNIQUE |\n| def | business | name | business | uniqueconstdemo | UNIQUE |\n| def | business | PRIMARY | business | keydemo | PRIMARY KEY |\n| def | business | PRIMARY | business | nextiddemo | PRIMARY KEY |\n| def | business | PRIMARY | business | tablepri | PRIMARY KEY |\n| def | business | ConstFK | business | tabledemo2 | UNIQUE |\n| def | business | ConstFK | business | tabledemo3 | UNIQUE |\n| def | business | PRIMARY | business | college | PRIMARY KEY |\n| def | business | id | business | uniquedemo1 | UNIQUE |\n| def | business | id | business | uniqueautoid | UNIQUE |\n| def | business | PRIMARY | business | schemadatabasemethoddemo | PRIMARY KEY |\n| def | business | PRIMARY | business | employeeinformation | PRIMARY KEY |\n| def | business | name | business | addingunique | UNIQUE |\n| def | business | PRIMARY | business | parentdemo | PRIMARY KEY |\n| def | business | PRIMARY | business | lastinsertrecordiddemo | PRIMARY KEY |\n| def | business | PRIMARY | business | demoindex | PRIMARY KEY |\n| def | business | PRIMARY | business | compositeprimarykey | PRIMARY KEY |\n| def | business | PRIMARY | business | addingautoincrement | PRIMARY KEY | \n| def | business | Id | business | uniqueconstrainttable | UNIQUE |\n| def | business | PRIMARY | business | mergedemo1 | PRIMARY KEY |\n| def | business | PRIMARY | business | mergedemo2 | PRIMARY KEY |\n| def | business | PRIMARY | business | foreigntable1 | PRIMARY KEY |\n| def | business | PRIMARY | business | twoprimarykeytabledemo | PRIMARY KEY |\n| def | business | PRIMARY | business | showconstraintsdemo | PRIMARY KEY |\n| def | business | BookAuthor | business | showconstraintsdemo | UNIQUE |\n| def | business | PRIMARY | business | autoincrementtozero | PRIMARY KEY |\n| def | business | PRIMARY | business | altertabletoaddautoincrement | PRIMARY KEY |\n| def | business | PRIMARY | business | addingprimarykeydemo | PRIMARY KEY |\n| def | business | PRIMARY | business | resetprimarykey | PRIMARY KEY |\n| def | business | constFKPK | business | foreigntable | FOREIGN KEY |\n| def | business | FKConst | business | foreigntabledemo | FOREIGN KEY |\n| def | business | ConstFK | business | tblf | FOREIGN KEY |\n| def | business | StudCollegeConst | business | studentenrollment | FOREIGN KEY |\n| def | business | ConstChild | business | childdemo | FOREIGN KEY |\n| def | business | primarytable1demo_ibfk_1 | business | primarytable1demo | FOREIGN KEY |\n+--------------------+-------------------+--------------------------+--------------+------------------------------+-----------------+\n48 rows in set, 2 warnings (0.24 sec)"
}
] |
CSS background-image Property - GeeksforGeeks
|
11 Oct, 2021
The background-image property is used to set one or more background images for an element. By default, it places the image on the top left corner. To specify two or more images, we need to specify the separate URLs with a comma for both images.
Syntax:
background-image: url('url')|none|initial|inherit;
Property values:
url(‘url’): This specifies the URL of the image. In order to specify the URL of more than one image then separate the URLs using a comma.
none: This is the default case where no image can be displayed.
initial: It is used to set the property to its default value.
inherit: It inherits the property from its parent element.
The background-image property can also be used with the following values:
linear-gradient(): It is used to set the linear-gradient background-image that is defined at least 2 color from top to bottom.
radial-gradient(): It is used to set the radial-gradient background-image that is defined at least 2 color from center to edge.
We will utilize the above property values & understand them through the examples.
url(‘url’): When the background-image has an URL.
Syntax:
background-image: url('url')
Example 1: This example illustrates the background-image property by setting the url value as url.
HTML
<!DOCTYPE html><html><head> <title>background-image property</title> <style> body { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/rk.png"); } h1, h3 { color: green; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>background-image:url;</h3> <div> GeeksforGeeks: A computer science portal for geeks </div></body></html>
Output:
none: This property is used for setting no background image & will not be displayed anything and this is by default property.
Syntax:
background-image: url('url') none
Example 2: This example illustrates the background-image property by setting the url value as none.
HTML
<!DOCTYPE html><html><head> <title>background-image property</title> <style> body { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/rk.png") none; } h1, h3 { color: green; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>background-image:url none;</h3> <div> GeeksforGeeks: A computer science portal for geeks </div></body></html>
Output:
initial: It sets the property to its default value.
Syntax:
background-image: url('url') initial;
Example 3: This example illustrates the background-image property by setting the url value as initial.
HTML
<!DOCTYPE html><html><head> <title>CSS background-image property</title> <style> body { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/rk.png") initial; } h1, h3 { color: green; } body { text-align: center; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>CSS background-image:url initial;</h3> </center></body></html>
Output:
Supported Browsers: The browser supported by background-image Property are listed below:
Google Chrome 1.0
Microsoft Edge 4.0
Firefox 1.0
Opera 3.5
Safari 1.0
shubham_singh
bhaskargeeksforgeeks
CSS-Properties
Picked
Web technologies
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 23596,
"s": 23568,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 23841,
"s": 23596,
"text": "The background-image property is used to set one or more background images for an element. By default, it places the image on the top left corner. To specify two or more images, we need to specify the separate URLs with a comma for both images."
},
{
"code": null,
"e": 23850,
"s": 23841,
"text": "Syntax: "
},
{
"code": null,
"e": 23901,
"s": 23850,
"text": "background-image: url('url')|none|initial|inherit;"
},
{
"code": null,
"e": 23918,
"s": 23901,
"text": "Property values:"
},
{
"code": null,
"e": 24056,
"s": 23918,
"text": "url(‘url’): This specifies the URL of the image. In order to specify the URL of more than one image then separate the URLs using a comma."
},
{
"code": null,
"e": 24120,
"s": 24056,
"text": "none: This is the default case where no image can be displayed."
},
{
"code": null,
"e": 24182,
"s": 24120,
"text": "initial: It is used to set the property to its default value."
},
{
"code": null,
"e": 24241,
"s": 24182,
"text": "inherit: It inherits the property from its parent element."
},
{
"code": null,
"e": 24315,
"s": 24241,
"text": "The background-image property can also be used with the following values:"
},
{
"code": null,
"e": 24442,
"s": 24315,
"text": "linear-gradient(): It is used to set the linear-gradient background-image that is defined at least 2 color from top to bottom."
},
{
"code": null,
"e": 24570,
"s": 24442,
"text": "radial-gradient(): It is used to set the radial-gradient background-image that is defined at least 2 color from center to edge."
},
{
"code": null,
"e": 24652,
"s": 24570,
"text": "We will utilize the above property values & understand them through the examples."
},
{
"code": null,
"e": 24702,
"s": 24652,
"text": "url(‘url’): When the background-image has an URL."
},
{
"code": null,
"e": 24710,
"s": 24702,
"text": "Syntax:"
},
{
"code": null,
"e": 24739,
"s": 24710,
"text": "background-image: url('url')"
},
{
"code": null,
"e": 24838,
"s": 24739,
"text": "Example 1: This example illustrates the background-image property by setting the url value as url."
},
{
"code": null,
"e": 24843,
"s": 24838,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>background-image property</title> <style> body { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/rk.png\"); } h1, h3 { color: green; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>background-image:url;</h3> <div> GeeksforGeeks: A computer science portal for geeks </div></body></html>",
"e": 25300,
"s": 24843,
"text": null
},
{
"code": null,
"e": 25308,
"s": 25300,
"text": "Output:"
},
{
"code": null,
"e": 25434,
"s": 25308,
"text": "none: This property is used for setting no background image & will not be displayed anything and this is by default property."
},
{
"code": null,
"e": 25443,
"s": 25434,
"text": "Syntax: "
},
{
"code": null,
"e": 25477,
"s": 25443,
"text": "background-image: url('url') none"
},
{
"code": null,
"e": 25577,
"s": 25477,
"text": "Example 2: This example illustrates the background-image property by setting the url value as none."
},
{
"code": null,
"e": 25582,
"s": 25577,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>background-image property</title> <style> body { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/rk.png\") none; } h1, h3 { color: green; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>background-image:url none;</h3> <div> GeeksforGeeks: A computer science portal for geeks </div></body></html>",
"e": 26049,
"s": 25582,
"text": null
},
{
"code": null,
"e": 26057,
"s": 26049,
"text": "Output:"
},
{
"code": null,
"e": 26109,
"s": 26057,
"text": "initial: It sets the property to its default value."
},
{
"code": null,
"e": 26117,
"s": 26109,
"text": "Syntax:"
},
{
"code": null,
"e": 26155,
"s": 26117,
"text": "background-image: url('url') initial;"
},
{
"code": null,
"e": 26258,
"s": 26155,
"text": "Example 3: This example illustrates the background-image property by setting the url value as initial."
},
{
"code": null,
"e": 26263,
"s": 26258,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>CSS background-image property</title> <style> body { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/rk.png\") initial; } h1, h3 { color: green; } body { text-align: center; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>CSS background-image:url initial;</h3> </center></body></html>",
"e": 26701,
"s": 26263,
"text": null
},
{
"code": null,
"e": 26709,
"s": 26701,
"text": "Output:"
},
{
"code": null,
"e": 26799,
"s": 26709,
"text": "Supported Browsers: The browser supported by background-image Property are listed below: "
},
{
"code": null,
"e": 26817,
"s": 26799,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 26836,
"s": 26817,
"text": "Microsoft Edge 4.0"
},
{
"code": null,
"e": 26848,
"s": 26836,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 26858,
"s": 26848,
"text": "Opera 3.5"
},
{
"code": null,
"e": 26869,
"s": 26858,
"text": "Safari 1.0"
},
{
"code": null,
"e": 26883,
"s": 26869,
"text": "shubham_singh"
},
{
"code": null,
"e": 26904,
"s": 26883,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 26919,
"s": 26904,
"text": "CSS-Properties"
},
{
"code": null,
"e": 26926,
"s": 26919,
"text": "Picked"
},
{
"code": null,
"e": 26943,
"s": 26926,
"text": "Web technologies"
},
{
"code": null,
"e": 26947,
"s": 26943,
"text": "CSS"
},
{
"code": null,
"e": 26964,
"s": 26947,
"text": "Web Technologies"
},
{
"code": null,
"e": 27062,
"s": 26964,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27112,
"s": 27062,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27174,
"s": 27112,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27232,
"s": 27174,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27280,
"s": 27232,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27330,
"s": 27280,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27372,
"s": 27330,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27405,
"s": 27372,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27448,
"s": 27405,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27498,
"s": 27448,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to customize the axis of a Bar Plot in R - GeeksforGeeks
|
18 Jul, 2021
Barplots in R programming language can be created using the barplot() method. It takes as input a matrix or vector of values. The bar heights are equivalent to the values contained in the vector.
Syntax: barplot(H, xlab, ylab, main, names.arg, col)
The names.args attribute in the barplot() method can be used to assign names to the x-axis labels. Numeric or character labels can be assigned which are plotted alternatively on the display window.
Example: Labeling the X-axis of the barplot
R
# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1)
Output
The ylim parameter of the barplot() method can be used to set limits to portray on the display window. It contains a vector containing lower and higher limit.
Example: Setting the Y-axis limit of the bar plot
R
# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , ylim= c(0,50) )
Output
The xlim parameter of the barplot() method can be used to set limits to portray on the display window. It contains a vector containing lower and higher limit.
Example: Setting the X-axis limit
R
# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , xlim= c(0,50) )
Output
The log parameter can be set to display the axis and its corresponding values on the logarithmic scale. Setting the log value equivalent to character string y displays the modifications on the y axis.
Example: Plotting logarithmic Y-axis
R
# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , log = "y" )
Output
The log parameter can be set to display the axis and its corresponding values on the logarithmic scale. Setting the log value equivalent to character string x displays the modifications on the x-axis.
Example: Plotting logarithmic X-axis
R
# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , log = "x" )
Output
The names.arg attribute can be renamed to assign a new set of labels to the x-axis arguments.
Example: Renaming the group labels
R
# creating a data framedata_frame <- data.frame(col1 = 1:5, col2 = 5:9, col3 = 1) # printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg =c( "Grp1","Grp2","Grp3","Grp4","Grp5"))
Output
The orientation of the axis labels can be changed using the las attribute. The following specification symbols are used to specify the orientation :
0: always parallel to the axis
1: always horizontal
2: always perpendicular to the axis
3: always vertical.
Example: Adding label orientation
R
# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , las=3)
Output
The xlab and ylab attributes contain character strings, which assign the respective names to the axes of the bar plots.
Example: Adding axis labels
R
# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , xlab = "Integers", ylab = "Numbers")
Output:
Picked
R-Charts
R-Graphs
R-plots
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 Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 25439,
"s": 25242,
"text": "Barplots in R programming language can be created using the barplot() method. It takes as input a matrix or vector of values. The bar heights are equivalent to the values contained in the vector. "
},
{
"code": null,
"e": 25492,
"s": 25439,
"text": "Syntax: barplot(H, xlab, ylab, main, names.arg, col)"
},
{
"code": null,
"e": 25691,
"s": 25492,
"text": "The names.args attribute in the barplot() method can be used to assign names to the x-axis labels. Numeric or character labels can be assigned which are plotted alternatively on the display window. "
},
{
"code": null,
"e": 25735,
"s": 25691,
"text": "Example: Labeling the X-axis of the barplot"
},
{
"code": null,
"e": 25737,
"s": 25735,
"text": "R"
},
{
"code": "# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1)",
"e": 26017,
"s": 25737,
"text": null
},
{
"code": null,
"e": 26024,
"s": 26017,
"text": "Output"
},
{
"code": null,
"e": 26184,
"s": 26024,
"text": "The ylim parameter of the barplot() method can be used to set limits to portray on the display window. It contains a vector containing lower and higher limit. "
},
{
"code": null,
"e": 26234,
"s": 26184,
"text": "Example: Setting the Y-axis limit of the bar plot"
},
{
"code": null,
"e": 26236,
"s": 26234,
"text": "R"
},
{
"code": "# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , ylim= c(0,50) )",
"e": 26533,
"s": 26236,
"text": null
},
{
"code": null,
"e": 26540,
"s": 26533,
"text": "Output"
},
{
"code": null,
"e": 26700,
"s": 26540,
"text": "The xlim parameter of the barplot() method can be used to set limits to portray on the display window. It contains a vector containing lower and higher limit. "
},
{
"code": null,
"e": 26734,
"s": 26700,
"text": "Example: Setting the X-axis limit"
},
{
"code": null,
"e": 26736,
"s": 26734,
"text": "R"
},
{
"code": "# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , xlim= c(0,50) )",
"e": 27033,
"s": 26736,
"text": null
},
{
"code": null,
"e": 27040,
"s": 27033,
"text": "Output"
},
{
"code": null,
"e": 27242,
"s": 27040,
"text": "The log parameter can be set to display the axis and its corresponding values on the logarithmic scale. Setting the log value equivalent to character string y displays the modifications on the y axis. "
},
{
"code": null,
"e": 27279,
"s": 27242,
"text": "Example: Plotting logarithmic Y-axis"
},
{
"code": null,
"e": 27281,
"s": 27279,
"text": "R"
},
{
"code": "# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , log = \"y\" )",
"e": 27574,
"s": 27281,
"text": null
},
{
"code": null,
"e": 27581,
"s": 27574,
"text": "Output"
},
{
"code": null,
"e": 27783,
"s": 27581,
"text": "The log parameter can be set to display the axis and its corresponding values on the logarithmic scale. Setting the log value equivalent to character string x displays the modifications on the x-axis. "
},
{
"code": null,
"e": 27820,
"s": 27783,
"text": "Example: Plotting logarithmic X-axis"
},
{
"code": null,
"e": 27822,
"s": 27820,
"text": "R"
},
{
"code": "# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , log = \"x\" )",
"e": 28115,
"s": 27822,
"text": null
},
{
"code": null,
"e": 28122,
"s": 28115,
"text": "Output"
},
{
"code": null,
"e": 28216,
"s": 28122,
"text": "The names.arg attribute can be renamed to assign a new set of labels to the x-axis arguments."
},
{
"code": null,
"e": 28251,
"s": 28216,
"text": "Example: Renaming the group labels"
},
{
"code": null,
"e": 28253,
"s": 28251,
"text": "R"
},
{
"code": "# creating a data framedata_frame <- data.frame(col1 = 1:5, col2 = 5:9, col3 = 1) # printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg =c( \"Grp1\",\"Grp2\",\"Grp3\",\"Grp4\",\"Grp5\"))",
"e": 28554,
"s": 28253,
"text": null
},
{
"code": null,
"e": 28561,
"s": 28554,
"text": "Output"
},
{
"code": null,
"e": 28711,
"s": 28561,
"text": "The orientation of the axis labels can be changed using the las attribute. The following specification symbols are used to specify the orientation : "
},
{
"code": null,
"e": 28742,
"s": 28711,
"text": "0: always parallel to the axis"
},
{
"code": null,
"e": 28763,
"s": 28742,
"text": "1: always horizontal"
},
{
"code": null,
"e": 28799,
"s": 28763,
"text": "2: always perpendicular to the axis"
},
{
"code": null,
"e": 28819,
"s": 28799,
"text": "3: always vertical."
},
{
"code": null,
"e": 28853,
"s": 28819,
"text": "Example: Adding label orientation"
},
{
"code": null,
"e": 28855,
"s": 28853,
"text": "R"
},
{
"code": "# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , las=3)",
"e": 29143,
"s": 28855,
"text": null
},
{
"code": null,
"e": 29150,
"s": 29143,
"text": "Output"
},
{
"code": null,
"e": 29271,
"s": 29150,
"text": "The xlab and ylab attributes contain character strings, which assign the respective names to the axes of the bar plots. "
},
{
"code": null,
"e": 29299,
"s": 29271,
"text": "Example: Adding axis labels"
},
{
"code": null,
"e": 29301,
"s": 29299,
"text": "R"
},
{
"code": "# creating a data framedata_frame <- data.frame(col1 = 1:20, col2 = 1:20, col3 = 1) # printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplotbarplot(data_frame$col2, names.arg = data_frame$col1 , xlab = \"Integers\", ylab = \"Numbers\")",
"e": 29626,
"s": 29301,
"text": null
},
{
"code": null,
"e": 29634,
"s": 29626,
"text": "Output:"
},
{
"code": null,
"e": 29641,
"s": 29634,
"text": "Picked"
},
{
"code": null,
"e": 29650,
"s": 29641,
"text": "R-Charts"
},
{
"code": null,
"e": 29659,
"s": 29650,
"text": "R-Graphs"
},
{
"code": null,
"e": 29667,
"s": 29659,
"text": "R-plots"
},
{
"code": null,
"e": 29678,
"s": 29667,
"text": "R Language"
},
{
"code": null,
"e": 29776,
"s": 29678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29828,
"s": 29776,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29866,
"s": 29828,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29901,
"s": 29866,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29959,
"s": 29901,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30008,
"s": 29959,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30045,
"s": 30008,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30095,
"s": 30045,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 30138,
"s": 30095,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30164,
"s": 30138,
"text": "Time Series Analysis in R"
}
] |
Components of convolutional neural networks | by John Olafenwa | Towards Data Science
|
Recent state-of-the-art architectures have employed a number of additional components to complement the convolution operation. In this post, I would be explaining some of the most important components that have improved both the speed and accuracy of modern convolutional neural networks. I would begin by explaining the theory of each of the components and finalize with a practical implementation in keras.
The first secret sauce that has made CNNs very effective is pooling. Pooling is a vector to scalar transformation that operates on each local region of an image, just like convolutions do, however, unlike convolutions, they do not have filters and do not compute dot products with the local region, instead they compute the average of the pixels in the region (Average Pooling) or simply picks the pixel with the highest intensity and discards the rest (Max Pooling).
The above is a 2 x 2 pooling, it will effectively reduce the size of feature maps by a factor of 2.
The very idea of pooling can seem counter-productive as it leads to loss of information, however it has proven to be very effective in practice because, it makes covnets invariant to variations in the presentation of an image and it also reduces the effects of background noise. Max Pooling has worked best in recent years, it is based on the idea that the maximum pixel in a region represents the most important feature in that region. Often images of objects we wish to classify could contain a number of other objects, for example, a cat appearing somewhere in the picture of a car could mislead the classifier. Pooling helps to alleviate the effects of this, and makes covnets generalize better.
It also greatly reduces the computational cost of the covnet. Generally, the size of images at each layer in the network is directly proportional to the computational cost (flops) of each layer. Pooling reduces the dimensions of the image as the layers get deeper, hence, it helps prevent an explosion of the number of flops a network requires. Strided convolutions are sometimes used as an alternative to pooling.
Overfitting is a phenomenon whereby a network works well on the training set, but performs poorly on the test set. This is often due to excessive dependence on the presence of specific features in the training set. Dropout is a technique for combating over-fitting. It works by randomly setting some activations to 0, essentially killing them. By doing this, the network is forced to explore more ways of classifying the images instead of over-depending on some features. This was one of the key elements in the AlexNet.
A major problem with neural networks is vanishing gradients. This is a situation whereby the gradients become too small, hence, training surfers terribly. Ioffe and Szegedy from Google Brain discovered that this was largely due to internal covariate shift, a situation that arises from the change data distribution as information flows through the network. What they did was to device the technique known as batch normalization. This works by normalizing every batch of the image to have zero mean and unit variance.
It is usually placed before non-linearity(relu) in cnns. It greatly improves accuracy while incredibly speeding up the training process.
The last ingredient required or modern covnets is data augmentation. The human vision system is excellent at adapting to image translations, rotations and other forms of distortions. Take an image and flip it anyway, most people can still recognize it. However, covnets are not very good at handling such distortions, they could fail terribly due to minor translations. They key to resolving this is to randomly distort the training images, using horizontal flipping, vertical flipping, rotation, whitening, shifting and other distortions. This would enable covnets to learn how to handle this distortions, hence, they would be able to work well in the real world.
Another common technique is to subtract the mean image from every image and also divide by the standard deviation.
Having bored you with the explanations of what these components are and why they work well, I shall now explain how to implement them in keras.
In this post, all experiments would be on CIFAR10, a data set of 60,000 32 x 32 RGB images. It is divided into 50,000 training images images and 10, 000 test images
To make things more modular, let’s create a simple function for each layer
def Unit(x,filters): out = BatchNormalization()(x) out = Activation("relu")(out) out = Conv2D(filters=filters, kernel_size=[3, 3], strides=[1, 1], padding="same")(out) return out
Here is the most vital aspect of our code, the Unit function defines a simple layer that contains three layers, first is BatchNormalization which i earlier explained, next we add RELU activation and finally, we add the convolution, notice how i put RELU before conv, it is a recent practice called “Pre-Activation”
Now we shall combine many of this unit layer into a single model
def MiniModel(input_shape): images = Input(input_shape) net = Unit(images,64) net = Unit(net,64) net = Unit(net,64) net = MaxPooling2D(pool_size=(2,2))(net) net = Unit(net,128) net = Unit(net,128) net = Unit(net,128) net = MaxPooling2D(pool_size=(2, 2))(net) net = Unit(net,256) net = Unit(net,256) net = Unit(net,256) net = Dropout(0.5)(net) net = AveragePooling2D(pool_size=(8,8))(net) net = Flatten()(net) net = Dense(units=10,activation="softmax")(net) model = Model(inputs=images,outputs=net) return model
Here we use the functional API to define our model, we begin with three Unit cells with 64 filters each, a Max Pooling layer follows, reducing our 32 x 32 images to 16 by 16. Next is 3, 128 filters Units followed by pooling, at this point, our images become 8 x 8, finally, we have another 3 units with 256 channels. Notice that each time we reduce our image dimensions by a factor of 2, we double the number of channels.
We add dropout with a ratio of 0.5, this would randomly deactivate 50% of our parameters, as i earlier explained, it combats overfitting.
Next we need to load the cifar10 dataset and perform some data augmentation
#load the cifar10 dataset(train_x, train_y) , (test_x, test_y) = cifar10.load_data()#normalize the datatrain_x = train_x.astype('float32') / 255test_x = test_x.astype('float32') / 255#Subtract the mean image from both train and test settrain_x = train_x - train_x.mean()test_x = test_x - test_x.mean()#Divide by the standard deviationtrain_x = train_x / train_x.std(axis=0)test_x = test_x / test_x.std(axis=0)
In the code above, after loading the train and test data, we subtract the mean image from each image and divide by the standard deviation, this is a basic data augmentation technique, sometimes, we might subtract the mean only and skip the standard deviation part, whichever works best should be used.
For more advance data augmentation, our image loading process would slighly change, keras has a very useful Data Augmentation utility that simplifies the whole process.
The code below would do the trick
datagen = ImageDataGenerator(rotation_range=10, width_shift_range=5. / 32, height_shift_range=5. / 32, horizontal_flip=True)# Compute quantities required for featurewise normalization# (std, mean, and principal components if ZCA whitening is applied).datagen.fit(train_x)
In the above, first, we specify a rotation angle of 10 degrees, a shift of 5/32 for both height and width and finally horizontal flip, all these transformations would be randomly applied to the images in the training set. Note that many more transformations exist, you can take a look at all parameters you can specify for the class. Bear in mind that over use of data augmentation might be detrimental.
Next, we have to convert the labels to one-hot encoding
#Encode the labels to vectorstrain_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)
I already explained this in my previous tutorials, so I won’t be explaining them here again. Infact, almost everything else that makes up the training process is exactly as in my previous tutorials, hence, here is the full code
#import needed classesimport kerasfrom keras.datasets import cifar10from keras.layers import Dense,Conv2D,MaxPooling2D,Flatten,AveragePooling2D,Dropout,BatchNormalization,Activationfrom keras.models import Model,Inputfrom keras.optimizers import Adamfrom keras.callbacks import LearningRateSchedulerfrom keras.callbacks import ModelCheckpointfrom math import ceilimport osfrom keras.preprocessing.image import ImageDataGeneratordef Unit(x,filters): out = BatchNormalization()(x) out = Activation("relu")(out) out = Conv2D(filters=filters, kernel_size=[3, 3], strides=[1, 1], padding="same")(out) return out#Define the modeldef MiniModel(input_shape): images = Input(input_shape) net = Unit(images,64) net = Unit(net,64) net = Unit(net,64) net = MaxPooling2D(pool_size=(2,2))(net) net = Unit(net,128) net = Unit(net,128) net = Unit(net,128) net = MaxPooling2D(pool_size=(2, 2))(net) net = Unit(net,256) net = Unit(net,256) net = Unit(net,256) net = Dropout(0.25)(net) net = AveragePooling2D(pool_size=(8,8))(net) net = Flatten()(net) net = Dense(units=10,activation="softmax")(net) model = Model(inputs=images,outputs=net) return model#load the cifar10 dataset(train_x, train_y) , (test_x, test_y) = cifar10.load_data()#normalize the datatrain_x = train_x.astype('float32') / 255test_x = test_x.astype('float32') / 255#Subtract the mean image from both train and test settrain_x = train_x - train_x.mean()test_x = test_x - test_x.mean()#Divide by the standard deviationtrain_x = train_x / train_x.std(axis=0)test_x = test_x / test_x.std(axis=0)datagen = ImageDataGenerator(rotation_range=10, width_shift_range=5. / 32, height_shift_range=5. / 32, horizontal_flip=True)# Compute quantities required for featurewise normalization# (std, mean, and principal components if ZCA whitening is applied).datagen.fit(train_x)#Encode the labels to vectorstrain_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)#define a common unitinput_shape = (32,32,3)model = MiniModel(input_shape)#Print a Summary of the modelmodel.summary()#Specify the training componentsmodel.compile(optimizer=Adam(0.001),loss="categorical_crossentropy",metrics=["accuracy"])epochs = 20steps_per_epoch = ceil(50000/128)# Fit the model on the batches generated by datagen.flow().model.fit_generator(datagen.flow(train_x, train_y, batch_size=128), validation_data=[test_x,test_y], epochs=epochs,steps_per_epoch=steps_per_epoch, verbose=1, workers=4)#Evaluate the accuracy of the test datasetaccuracy = model.evaluate(x=test_x,y=test_y,batch_size=128)model.save("cifar10model.h5")
A few things are different here, first
input_shape = (32,32,3)model = MiniModel(input_shape)#Print a Summary of the modelmodel.summary()
As i earlier explained, cifar 10 is made up of 32 x 32 RGB images, hence, the input shape has 3 channels. This is quite self-explanatory.
The next line creates an instance of the model we defined and we pass in the input shape
Finally, the last line would print out a full summary of our network including the number of parameters.
The last part that needs explaining is
epochs = 20steps_per_epoch = ceil(50000/128)# Fit the model on the batches generated by datagen.flow().model.fit_generator(datagen.flow(train_x, train_y, batch_size=128), validation_data=[test_x,test_y], epochs=epochs,steps_per_epoch=steps_per_epoch, verbose=1, workers=4)#Evaluate the accuracy of the test datasetaccuracy = model.evaluate(x=test_x,y=test_y,batch_size=128)model.save("cifar10model.h5")
First we define the number of epochs to run and also, the number of steps per epoch, don’t get confused with the numbers
steps_per_epoch = ceil(50000/128)
50000 here is the number of training images in total, here we are using a batch size of 128, that means, for each of the 20 epochs, the network would have to go over 50000/128 batches of images.
Next is the fit function, this is clearly different from the fit function i explained in my earlier tutorials.
A second look below would help
Fit the model on the batches generated by datagen.flow().model.fit_generator(datagen.flow(train_x, train_y, batch_size=128), validation_data=[test_x,test_y], epochs=epochs,steps_per_epoch=steps_per_epoch, verbose=1, workers=4)
Due to our use of the data generator class for data augmentation purposes, we have to use the fit_generator function, also we do not pass in train_x and train_y directly, instead we pass them via the flow function from the data generator, we also specify the batch size, next we state the validation data which in this case is the test data. All other things remain same.
This setup yields 82% after 20 epochs.
You can try tweaking the parameters and the network to see how much you can improve the accuracy. In the next tutorial i would be explaining some other tricks and techniques required to truly build very efficient cnn architectures. The purpose of this tutorial is to introduce you to the basic components.
If you want to get deeper into computer vision. download my free ebook “Introduction to Deep Computer Vision” from https://john.specpal.science
If you have any questions, comment below or reach to me on twitter via @johnolafenwa
|
[
{
"code": null,
"e": 456,
"s": 47,
"text": "Recent state-of-the-art architectures have employed a number of additional components to complement the convolution operation. In this post, I would be explaining some of the most important components that have improved both the speed and accuracy of modern convolutional neural networks. I would begin by explaining the theory of each of the components and finalize with a practical implementation in keras."
},
{
"code": null,
"e": 924,
"s": 456,
"text": "The first secret sauce that has made CNNs very effective is pooling. Pooling is a vector to scalar transformation that operates on each local region of an image, just like convolutions do, however, unlike convolutions, they do not have filters and do not compute dot products with the local region, instead they compute the average of the pixels in the region (Average Pooling) or simply picks the pixel with the highest intensity and discards the rest (Max Pooling)."
},
{
"code": null,
"e": 1024,
"s": 924,
"text": "The above is a 2 x 2 pooling, it will effectively reduce the size of feature maps by a factor of 2."
},
{
"code": null,
"e": 1724,
"s": 1024,
"text": "The very idea of pooling can seem counter-productive as it leads to loss of information, however it has proven to be very effective in practice because, it makes covnets invariant to variations in the presentation of an image and it also reduces the effects of background noise. Max Pooling has worked best in recent years, it is based on the idea that the maximum pixel in a region represents the most important feature in that region. Often images of objects we wish to classify could contain a number of other objects, for example, a cat appearing somewhere in the picture of a car could mislead the classifier. Pooling helps to alleviate the effects of this, and makes covnets generalize better."
},
{
"code": null,
"e": 2139,
"s": 1724,
"text": "It also greatly reduces the computational cost of the covnet. Generally, the size of images at each layer in the network is directly proportional to the computational cost (flops) of each layer. Pooling reduces the dimensions of the image as the layers get deeper, hence, it helps prevent an explosion of the number of flops a network requires. Strided convolutions are sometimes used as an alternative to pooling."
},
{
"code": null,
"e": 2660,
"s": 2139,
"text": "Overfitting is a phenomenon whereby a network works well on the training set, but performs poorly on the test set. This is often due to excessive dependence on the presence of specific features in the training set. Dropout is a technique for combating over-fitting. It works by randomly setting some activations to 0, essentially killing them. By doing this, the network is forced to explore more ways of classifying the images instead of over-depending on some features. This was one of the key elements in the AlexNet."
},
{
"code": null,
"e": 3177,
"s": 2660,
"text": "A major problem with neural networks is vanishing gradients. This is a situation whereby the gradients become too small, hence, training surfers terribly. Ioffe and Szegedy from Google Brain discovered that this was largely due to internal covariate shift, a situation that arises from the change data distribution as information flows through the network. What they did was to device the technique known as batch normalization. This works by normalizing every batch of the image to have zero mean and unit variance."
},
{
"code": null,
"e": 3314,
"s": 3177,
"text": "It is usually placed before non-linearity(relu) in cnns. It greatly improves accuracy while incredibly speeding up the training process."
},
{
"code": null,
"e": 3979,
"s": 3314,
"text": "The last ingredient required or modern covnets is data augmentation. The human vision system is excellent at adapting to image translations, rotations and other forms of distortions. Take an image and flip it anyway, most people can still recognize it. However, covnets are not very good at handling such distortions, they could fail terribly due to minor translations. They key to resolving this is to randomly distort the training images, using horizontal flipping, vertical flipping, rotation, whitening, shifting and other distortions. This would enable covnets to learn how to handle this distortions, hence, they would be able to work well in the real world."
},
{
"code": null,
"e": 4094,
"s": 3979,
"text": "Another common technique is to subtract the mean image from every image and also divide by the standard deviation."
},
{
"code": null,
"e": 4238,
"s": 4094,
"text": "Having bored you with the explanations of what these components are and why they work well, I shall now explain how to implement them in keras."
},
{
"code": null,
"e": 4403,
"s": 4238,
"text": "In this post, all experiments would be on CIFAR10, a data set of 60,000 32 x 32 RGB images. It is divided into 50,000 training images images and 10, 000 test images"
},
{
"code": null,
"e": 4478,
"s": 4403,
"text": "To make things more modular, let’s create a simple function for each layer"
},
{
"code": null,
"e": 4669,
"s": 4478,
"text": "def Unit(x,filters): out = BatchNormalization()(x) out = Activation(\"relu\")(out) out = Conv2D(filters=filters, kernel_size=[3, 3], strides=[1, 1], padding=\"same\")(out) return out"
},
{
"code": null,
"e": 4984,
"s": 4669,
"text": "Here is the most vital aspect of our code, the Unit function defines a simple layer that contains three layers, first is BatchNormalization which i earlier explained, next we add RELU activation and finally, we add the convolution, notice how i put RELU before conv, it is a recent practice called “Pre-Activation”"
},
{
"code": null,
"e": 5049,
"s": 4984,
"text": "Now we shall combine many of this unit layer into a single model"
},
{
"code": null,
"e": 5614,
"s": 5049,
"text": "def MiniModel(input_shape): images = Input(input_shape) net = Unit(images,64) net = Unit(net,64) net = Unit(net,64) net = MaxPooling2D(pool_size=(2,2))(net) net = Unit(net,128) net = Unit(net,128) net = Unit(net,128) net = MaxPooling2D(pool_size=(2, 2))(net) net = Unit(net,256) net = Unit(net,256) net = Unit(net,256) net = Dropout(0.5)(net) net = AveragePooling2D(pool_size=(8,8))(net) net = Flatten()(net) net = Dense(units=10,activation=\"softmax\")(net) model = Model(inputs=images,outputs=net) return model"
},
{
"code": null,
"e": 6036,
"s": 5614,
"text": "Here we use the functional API to define our model, we begin with three Unit cells with 64 filters each, a Max Pooling layer follows, reducing our 32 x 32 images to 16 by 16. Next is 3, 128 filters Units followed by pooling, at this point, our images become 8 x 8, finally, we have another 3 units with 256 channels. Notice that each time we reduce our image dimensions by a factor of 2, we double the number of channels."
},
{
"code": null,
"e": 6174,
"s": 6036,
"text": "We add dropout with a ratio of 0.5, this would randomly deactivate 50% of our parameters, as i earlier explained, it combats overfitting."
},
{
"code": null,
"e": 6250,
"s": 6174,
"text": "Next we need to load the cifar10 dataset and perform some data augmentation"
},
{
"code": null,
"e": 6660,
"s": 6250,
"text": "#load the cifar10 dataset(train_x, train_y) , (test_x, test_y) = cifar10.load_data()#normalize the datatrain_x = train_x.astype('float32') / 255test_x = test_x.astype('float32') / 255#Subtract the mean image from both train and test settrain_x = train_x - train_x.mean()test_x = test_x - test_x.mean()#Divide by the standard deviationtrain_x = train_x / train_x.std(axis=0)test_x = test_x / test_x.std(axis=0)"
},
{
"code": null,
"e": 6962,
"s": 6660,
"text": "In the code above, after loading the train and test data, we subtract the mean image from each image and divide by the standard deviation, this is a basic data augmentation technique, sometimes, we might subtract the mean only and skip the standard deviation part, whichever works best should be used."
},
{
"code": null,
"e": 7131,
"s": 6962,
"text": "For more advance data augmentation, our image loading process would slighly change, keras has a very useful Data Augmentation utility that simplifies the whole process."
},
{
"code": null,
"e": 7165,
"s": 7131,
"text": "The code below would do the trick"
},
{
"code": null,
"e": 7521,
"s": 7165,
"text": "datagen = ImageDataGenerator(rotation_range=10, width_shift_range=5. / 32, height_shift_range=5. / 32, horizontal_flip=True)# Compute quantities required for featurewise normalization# (std, mean, and principal components if ZCA whitening is applied).datagen.fit(train_x)"
},
{
"code": null,
"e": 7925,
"s": 7521,
"text": "In the above, first, we specify a rotation angle of 10 degrees, a shift of 5/32 for both height and width and finally horizontal flip, all these transformations would be randomly applied to the images in the training set. Note that many more transformations exist, you can take a look at all parameters you can specify for the class. Bear in mind that over use of data augmentation might be detrimental."
},
{
"code": null,
"e": 7981,
"s": 7925,
"text": "Next, we have to convert the labels to one-hot encoding"
},
{
"code": null,
"e": 8105,
"s": 7981,
"text": "#Encode the labels to vectorstrain_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)"
},
{
"code": null,
"e": 8333,
"s": 8105,
"text": "I already explained this in my previous tutorials, so I won’t be explaining them here again. Infact, almost everything else that makes up the training process is exactly as in my previous tutorials, hence, here is the full code"
},
{
"code": null,
"e": 11100,
"s": 8333,
"text": "#import needed classesimport kerasfrom keras.datasets import cifar10from keras.layers import Dense,Conv2D,MaxPooling2D,Flatten,AveragePooling2D,Dropout,BatchNormalization,Activationfrom keras.models import Model,Inputfrom keras.optimizers import Adamfrom keras.callbacks import LearningRateSchedulerfrom keras.callbacks import ModelCheckpointfrom math import ceilimport osfrom keras.preprocessing.image import ImageDataGeneratordef Unit(x,filters): out = BatchNormalization()(x) out = Activation(\"relu\")(out) out = Conv2D(filters=filters, kernel_size=[3, 3], strides=[1, 1], padding=\"same\")(out) return out#Define the modeldef MiniModel(input_shape): images = Input(input_shape) net = Unit(images,64) net = Unit(net,64) net = Unit(net,64) net = MaxPooling2D(pool_size=(2,2))(net) net = Unit(net,128) net = Unit(net,128) net = Unit(net,128) net = MaxPooling2D(pool_size=(2, 2))(net) net = Unit(net,256) net = Unit(net,256) net = Unit(net,256) net = Dropout(0.25)(net) net = AveragePooling2D(pool_size=(8,8))(net) net = Flatten()(net) net = Dense(units=10,activation=\"softmax\")(net) model = Model(inputs=images,outputs=net) return model#load the cifar10 dataset(train_x, train_y) , (test_x, test_y) = cifar10.load_data()#normalize the datatrain_x = train_x.astype('float32') / 255test_x = test_x.astype('float32') / 255#Subtract the mean image from both train and test settrain_x = train_x - train_x.mean()test_x = test_x - test_x.mean()#Divide by the standard deviationtrain_x = train_x / train_x.std(axis=0)test_x = test_x / test_x.std(axis=0)datagen = ImageDataGenerator(rotation_range=10, width_shift_range=5. / 32, height_shift_range=5. / 32, horizontal_flip=True)# Compute quantities required for featurewise normalization# (std, mean, and principal components if ZCA whitening is applied).datagen.fit(train_x)#Encode the labels to vectorstrain_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)#define a common unitinput_shape = (32,32,3)model = MiniModel(input_shape)#Print a Summary of the modelmodel.summary()#Specify the training componentsmodel.compile(optimizer=Adam(0.001),loss=\"categorical_crossentropy\",metrics=[\"accuracy\"])epochs = 20steps_per_epoch = ceil(50000/128)# Fit the model on the batches generated by datagen.flow().model.fit_generator(datagen.flow(train_x, train_y, batch_size=128), validation_data=[test_x,test_y], epochs=epochs,steps_per_epoch=steps_per_epoch, verbose=1, workers=4)#Evaluate the accuracy of the test datasetaccuracy = model.evaluate(x=test_x,y=test_y,batch_size=128)model.save(\"cifar10model.h5\")"
},
{
"code": null,
"e": 11139,
"s": 11100,
"text": "A few things are different here, first"
},
{
"code": null,
"e": 11237,
"s": 11139,
"text": "input_shape = (32,32,3)model = MiniModel(input_shape)#Print a Summary of the modelmodel.summary()"
},
{
"code": null,
"e": 11375,
"s": 11237,
"text": "As i earlier explained, cifar 10 is made up of 32 x 32 RGB images, hence, the input shape has 3 channels. This is quite self-explanatory."
},
{
"code": null,
"e": 11464,
"s": 11375,
"text": "The next line creates an instance of the model we defined and we pass in the input shape"
},
{
"code": null,
"e": 11569,
"s": 11464,
"text": "Finally, the last line would print out a full summary of our network including the number of parameters."
},
{
"code": null,
"e": 11608,
"s": 11569,
"text": "The last part that needs explaining is"
},
{
"code": null,
"e": 12049,
"s": 11608,
"text": "epochs = 20steps_per_epoch = ceil(50000/128)# Fit the model on the batches generated by datagen.flow().model.fit_generator(datagen.flow(train_x, train_y, batch_size=128), validation_data=[test_x,test_y], epochs=epochs,steps_per_epoch=steps_per_epoch, verbose=1, workers=4)#Evaluate the accuracy of the test datasetaccuracy = model.evaluate(x=test_x,y=test_y,batch_size=128)model.save(\"cifar10model.h5\")"
},
{
"code": null,
"e": 12170,
"s": 12049,
"text": "First we define the number of epochs to run and also, the number of steps per epoch, don’t get confused with the numbers"
},
{
"code": null,
"e": 12204,
"s": 12170,
"text": "steps_per_epoch = ceil(50000/128)"
},
{
"code": null,
"e": 12399,
"s": 12204,
"text": "50000 here is the number of training images in total, here we are using a batch size of 128, that means, for each of the 20 epochs, the network would have to go over 50000/128 batches of images."
},
{
"code": null,
"e": 12510,
"s": 12399,
"text": "Next is the fit function, this is clearly different from the fit function i explained in my earlier tutorials."
},
{
"code": null,
"e": 12541,
"s": 12510,
"text": "A second look below would help"
},
{
"code": null,
"e": 12806,
"s": 12541,
"text": "Fit the model on the batches generated by datagen.flow().model.fit_generator(datagen.flow(train_x, train_y, batch_size=128), validation_data=[test_x,test_y], epochs=epochs,steps_per_epoch=steps_per_epoch, verbose=1, workers=4)"
},
{
"code": null,
"e": 13178,
"s": 12806,
"text": "Due to our use of the data generator class for data augmentation purposes, we have to use the fit_generator function, also we do not pass in train_x and train_y directly, instead we pass them via the flow function from the data generator, we also specify the batch size, next we state the validation data which in this case is the test data. All other things remain same."
},
{
"code": null,
"e": 13217,
"s": 13178,
"text": "This setup yields 82% after 20 epochs."
},
{
"code": null,
"e": 13523,
"s": 13217,
"text": "You can try tweaking the parameters and the network to see how much you can improve the accuracy. In the next tutorial i would be explaining some other tricks and techniques required to truly build very efficient cnn architectures. The purpose of this tutorial is to introduce you to the basic components."
},
{
"code": null,
"e": 13667,
"s": 13523,
"text": "If you want to get deeper into computer vision. download my free ebook “Introduction to Deep Computer Vision” from https://john.specpal.science"
}
] |
CSS - text-indent
|
The text-indent property defines an indentation distance for the first line of text in a block-level element.
length − Any length value. Negative lengths are permitted for the property, and will produce a "hanging indent" effect.
length − Any length value. Negative lengths are permitted for the property, and will produce a "hanging indent" effect.
percentage − The first line of text is indented by a distance relative to the width of the element's containing block.
percentage − The first line of text is indented by a distance relative to the width of the element's containing block.
All the block-level elements.
object.style.textIndent = "20px";
Following is the example which demonstrates how to indent the first line of a paragraph −
<html>
<head>
</head>
<body>
<p style = "text-indent:1cm;">
This text will have first line indented by 1cm
</p>
<p style = "text-indent:1cm;">
this line will remain at its actual position this is done by
CSS text-indent property.
</p>
</body>
</html>
This will produce following result −
This text will have first line indented by 1cm
this line will remain at its actual position this is done by CSS text-indent property.
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2737,
"s": 2626,
"text": "The text-indent property defines an indentation distance for the first line of text in a block-level element."
},
{
"code": null,
"e": 2857,
"s": 2737,
"text": "length − Any length value. Negative lengths are permitted for the property, and will produce a \"hanging indent\" effect."
},
{
"code": null,
"e": 2977,
"s": 2857,
"text": "length − Any length value. Negative lengths are permitted for the property, and will produce a \"hanging indent\" effect."
},
{
"code": null,
"e": 3096,
"s": 2977,
"text": "percentage − The first line of text is indented by a distance relative to the width of the element's containing block."
},
{
"code": null,
"e": 3215,
"s": 3096,
"text": "percentage − The first line of text is indented by a distance relative to the width of the element's containing block."
},
{
"code": null,
"e": 3245,
"s": 3215,
"text": "All the block-level elements."
},
{
"code": null,
"e": 3280,
"s": 3245,
"text": "object.style.textIndent = \"20px\";\n"
},
{
"code": null,
"e": 3370,
"s": 3280,
"text": "Following is the example which demonstrates how to indent the first line of a paragraph −"
},
{
"code": null,
"e": 3695,
"s": 3370,
"text": "<html>\n <head>\n </head>\n\n <body>\n <p style = \"text-indent:1cm;\">\n This text will have first line indented by 1cm \n </p>\n \n <p style = \"text-indent:1cm;\">\n this line will remain at its actual position this is done by \n CSS text-indent property.\n </p>\n </body>\n</html> "
},
{
"code": null,
"e": 3732,
"s": 3695,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3784,
"s": 3732,
"text": "\n This text will have first line indented by 1cm\n"
},
{
"code": null,
"e": 3873,
"s": 3784,
"text": "\nthis line will remain at its actual position this is done by CSS text-indent property.\n"
},
{
"code": null,
"e": 3908,
"s": 3873,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3922,
"s": 3908,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3957,
"s": 3922,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3974,
"s": 3957,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4009,
"s": 3974,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4040,
"s": 4009,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4075,
"s": 4040,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4106,
"s": 4075,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4141,
"s": 4106,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4172,
"s": 4141,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4205,
"s": 4172,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4236,
"s": 4205,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4243,
"s": 4236,
"text": " Print"
},
{
"code": null,
"e": 4254,
"s": 4243,
"text": " Add Notes"
}
] |
A guide to XGBoost hyperparameters | by Mahbubul Alam | Towards Data Science
|
What is the one machine learning algorithm — if you ask — that consistently gives superior performance in regression and classification?
XGBoost it is. It is arguably the most powerful algorithm and is increasingly being used in all industries and in all problem domains —from customer analytics and sales prediction to fraud detection and credit approval and more.
It is also a winning algorithm in many machine learning competitions. In fact, XGBoost was used in 17 out of 29 data science competitions on the Kaggle platform.
Not just in businesses and competitions, XGBoost has been used in scientific experiments such as the Large Hadron Collider (the Higgs Boson machine learning challenge).
A key to its performance is its hyperparameters. While XGBoost is extremely easy to implement, the hard part is tuning the hyperparameters. In this article, I will talk about some of the key hyperparameters, their role and how to choose their values.
But before I go there, let’s talk about how XGBoost works under the hood.
XGBoost (or eXtreme Gradient Boost) is not a standalone algorithm in the conventional sense. It is rather an open-source library that “boosts” the performance of other algorithms. It optimizes the performance of algorithms, primarily decision trees, in a gradient boosting framework while minimizing overfitting/bias through regularization.
The key strengths of XGBoost are:
Flexibility: It can perform machine learning tasks such as regression, classification, ranking and other user-defined objectives.
Portability: It runs on Windows, Linux and OS X as well as on cloud platforms.
Languages support: It supports multiple languages including C++, Python, R, Java, Scala, Julia.
Distributed training on cloud systems: XGBoost supports distributed training on multiple machines, including AWS, GCE, Azure, and Yarn clusters.
Other important features of XGBoost include:
parallel processing capabilities for large dataset
can handle missing values
allows for regularization to prevent overfitting
has built-in cross-validation
Below I’ll first walk through a simple 5-step implementation of XGBoost and then we can talk about the hyperparameters and how to use them to optimize performance.
For this demo we do not need much. From sklearn library we can import modules for splitting training and testing data and the accuracy metrics. Note that, first you need to install (pip install) the XGBoost library before you can import it.
# loading datafrom sklearn.datasets import load_iris# to split data into training and testing setfrom sklearn.model_selection import train_test_split# XGBoost libraryimport xgboost as xgb# evaluation metricsfrom sklearn.metrics import accuracy_score
We are using the built-in iris dataset from Scikit Learn library, so we do not need to do data pre-processing. After loading data we just need to store input features and the target variable separately.
df = load_iris()X = df.datay = df.target
The dataset has 4 features (predictors):
df.feature_names>> ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
The target has 3 classes.
df.target_names>> array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
First, we are going to split data into training (70%) and testing (30%) sets. As an extra step, we need to store data into a compatible DMatrix object for XGBoost compatibility.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state = 1)train = xgb.DMatrix(X_train, label = y_train)test = xgb.DMatrix(X_test, label = y_test)
Since this is a simple demonstration, let’s choose just 3 hyperparameters.
# specify hyperparametersparams = { 'max_depth': 4, 'eta': 0.3, 'num_class': 3}epochs = 10
5. Modeling
Now that you have specified the hyperparameters, rudding the model and making a prediction takes just a couple more lines.
# train modelmodel = xgb.train(params, train, epochs)# predictiony_pred = model.predict(test)
So even with this simple implementation, the model was able to gain 98% accuracy.
Now let’s get to the core of this article — the hyperparameters.
There are many different parameters in XGBoost and they are broadly classified into 3 types:
General parameters
Booster parameters
Task parameters
There are more or less 35 different hyperparameters listed in the XGBoost documentation. However, not all of them are equally important, some are more impactful than others.
Below are some parameters that are frequently tuned in a grid search to find an optimal balance.
Frequently tuned hyperparameters
n_estimators: specifies the number of decision trees to be boosted. If n_estimator = 1, it means only 1 tree is generated, thus no boosting is at work. The default value is 100, but you can play with this number for optimal performance.
subsample: it represents the subsample ratio of the training sample. A subsample = 0.5 means that 50% of training data is used prior to growing a tree. The value can be any fraction but the default value is 1.
max_depth: it limits how deep each tree can grow. The default value is 6 but you can try other values if overfitting is an issue in your model.
learning_rate (alias: eta): it is a regularization parameter that shrinks feature weights in each boosting step. The default value is 0.3 but people generally tune with values such as 0.01, 0.1, 0.2 etc.
gamma (alias: min_split_loss): it’s another regularization parameter for tree pruning. It specifies the minimum loss reduction required to grow a tree. The default value is set at 0.
reg_alpha (alias: alpha): it is the L1 regularization parameter, increasing its value makes the model more conservative. Default is 0.
reg_lambda (alias: lambda): L2 regularization parameter, increasing its value also makes the model conservative. Default is 1.
Special use hyperparameters
The above set of parameters are “general purpose” parameters that you can always tune to optimize model performance. There are some special purpose hyperparameters that are used in particular situations:
scale_pos_weight: This parameter is useful in case you have an imbalanced dataset, particularly in classification problems, where the proportion of one class is a small fraction of total observations (e.g. credit card fraud). The default value is 1, but you can use the following ratio: total negative instance (e.g. no-fraud)/ total positive instance (e.g. fraud).
monotone_constraints: You can activate this parameter if you want to increase the constraint on the predictors, for example, a non-linear, increasing likelihood of credit-loan approval with a higher credit score.
booster: you can choose what kind of booster method to use. You have three options: ‘dart’, ‘gbtree ’ (tree-based) and ‘gblinear ’ (Ridge regression).
missing: it’s not missing value treatment exactly, it’s rather used to specify under what circumstances the algorithm should treat a value as missing (e.g. a negative value of the age of a customer certainly is impossible, thus the algorithm treats it as a missing value).
eval_metric: it specifies what loss function to use, e.g MAE, MSE, RMSE for regression and log loss for classification.
Just 5 years ago not many people knew about XGBoost (it was initially released in 2014) and now it is revolutionizing the field of data science and machine learning and applied in all kinds of industries. It is super simple to train XGBoost but the hardest part is parameter tuning. In this article I’ve shown a simple demo implementation along with a discussion on the most frequently used hyperparameters.
Thanks for reading. Feel free to subscribe to get notified of my medium articles or connect with me via Twitter, or LinkedIn.
|
[
{
"code": null,
"e": 309,
"s": 172,
"text": "What is the one machine learning algorithm — if you ask — that consistently gives superior performance in regression and classification?"
},
{
"code": null,
"e": 538,
"s": 309,
"text": "XGBoost it is. It is arguably the most powerful algorithm and is increasingly being used in all industries and in all problem domains —from customer analytics and sales prediction to fraud detection and credit approval and more."
},
{
"code": null,
"e": 700,
"s": 538,
"text": "It is also a winning algorithm in many machine learning competitions. In fact, XGBoost was used in 17 out of 29 data science competitions on the Kaggle platform."
},
{
"code": null,
"e": 869,
"s": 700,
"text": "Not just in businesses and competitions, XGBoost has been used in scientific experiments such as the Large Hadron Collider (the Higgs Boson machine learning challenge)."
},
{
"code": null,
"e": 1120,
"s": 869,
"text": "A key to its performance is its hyperparameters. While XGBoost is extremely easy to implement, the hard part is tuning the hyperparameters. In this article, I will talk about some of the key hyperparameters, their role and how to choose their values."
},
{
"code": null,
"e": 1194,
"s": 1120,
"text": "But before I go there, let’s talk about how XGBoost works under the hood."
},
{
"code": null,
"e": 1535,
"s": 1194,
"text": "XGBoost (or eXtreme Gradient Boost) is not a standalone algorithm in the conventional sense. It is rather an open-source library that “boosts” the performance of other algorithms. It optimizes the performance of algorithms, primarily decision trees, in a gradient boosting framework while minimizing overfitting/bias through regularization."
},
{
"code": null,
"e": 1569,
"s": 1535,
"text": "The key strengths of XGBoost are:"
},
{
"code": null,
"e": 1699,
"s": 1569,
"text": "Flexibility: It can perform machine learning tasks such as regression, classification, ranking and other user-defined objectives."
},
{
"code": null,
"e": 1778,
"s": 1699,
"text": "Portability: It runs on Windows, Linux and OS X as well as on cloud platforms."
},
{
"code": null,
"e": 1874,
"s": 1778,
"text": "Languages support: It supports multiple languages including C++, Python, R, Java, Scala, Julia."
},
{
"code": null,
"e": 2019,
"s": 1874,
"text": "Distributed training on cloud systems: XGBoost supports distributed training on multiple machines, including AWS, GCE, Azure, and Yarn clusters."
},
{
"code": null,
"e": 2064,
"s": 2019,
"text": "Other important features of XGBoost include:"
},
{
"code": null,
"e": 2115,
"s": 2064,
"text": "parallel processing capabilities for large dataset"
},
{
"code": null,
"e": 2141,
"s": 2115,
"text": "can handle missing values"
},
{
"code": null,
"e": 2190,
"s": 2141,
"text": "allows for regularization to prevent overfitting"
},
{
"code": null,
"e": 2220,
"s": 2190,
"text": "has built-in cross-validation"
},
{
"code": null,
"e": 2384,
"s": 2220,
"text": "Below I’ll first walk through a simple 5-step implementation of XGBoost and then we can talk about the hyperparameters and how to use them to optimize performance."
},
{
"code": null,
"e": 2625,
"s": 2384,
"text": "For this demo we do not need much. From sklearn library we can import modules for splitting training and testing data and the accuracy metrics. Note that, first you need to install (pip install) the XGBoost library before you can import it."
},
{
"code": null,
"e": 2875,
"s": 2625,
"text": "# loading datafrom sklearn.datasets import load_iris# to split data into training and testing setfrom sklearn.model_selection import train_test_split# XGBoost libraryimport xgboost as xgb# evaluation metricsfrom sklearn.metrics import accuracy_score"
},
{
"code": null,
"e": 3078,
"s": 2875,
"text": "We are using the built-in iris dataset from Scikit Learn library, so we do not need to do data pre-processing. After loading data we just need to store input features and the target variable separately."
},
{
"code": null,
"e": 3119,
"s": 3078,
"text": "df = load_iris()X = df.datay = df.target"
},
{
"code": null,
"e": 3160,
"s": 3119,
"text": "The dataset has 4 features (predictors):"
},
{
"code": null,
"e": 3262,
"s": 3160,
"text": "df.feature_names>> ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']"
},
{
"code": null,
"e": 3288,
"s": 3262,
"text": "The target has 3 classes."
},
{
"code": null,
"e": 3365,
"s": 3288,
"text": "df.target_names>> array(['setosa', 'versicolor', 'virginica'], dtype='<U10')"
},
{
"code": null,
"e": 3543,
"s": 3365,
"text": "First, we are going to split data into training (70%) and testing (30%) sets. As an extra step, we need to store data into a compatible DMatrix object for XGBoost compatibility."
},
{
"code": null,
"e": 3721,
"s": 3543,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state = 1)train = xgb.DMatrix(X_train, label = y_train)test = xgb.DMatrix(X_test, label = y_test)"
},
{
"code": null,
"e": 3796,
"s": 3721,
"text": "Since this is a simple demonstration, let’s choose just 3 hyperparameters."
},
{
"code": null,
"e": 3896,
"s": 3796,
"text": "# specify hyperparametersparams = { 'max_depth': 4, 'eta': 0.3, 'num_class': 3}epochs = 10"
},
{
"code": null,
"e": 3908,
"s": 3896,
"text": "5. Modeling"
},
{
"code": null,
"e": 4031,
"s": 3908,
"text": "Now that you have specified the hyperparameters, rudding the model and making a prediction takes just a couple more lines."
},
{
"code": null,
"e": 4125,
"s": 4031,
"text": "# train modelmodel = xgb.train(params, train, epochs)# predictiony_pred = model.predict(test)"
},
{
"code": null,
"e": 4207,
"s": 4125,
"text": "So even with this simple implementation, the model was able to gain 98% accuracy."
},
{
"code": null,
"e": 4272,
"s": 4207,
"text": "Now let’s get to the core of this article — the hyperparameters."
},
{
"code": null,
"e": 4365,
"s": 4272,
"text": "There are many different parameters in XGBoost and they are broadly classified into 3 types:"
},
{
"code": null,
"e": 4384,
"s": 4365,
"text": "General parameters"
},
{
"code": null,
"e": 4403,
"s": 4384,
"text": "Booster parameters"
},
{
"code": null,
"e": 4419,
"s": 4403,
"text": "Task parameters"
},
{
"code": null,
"e": 4593,
"s": 4419,
"text": "There are more or less 35 different hyperparameters listed in the XGBoost documentation. However, not all of them are equally important, some are more impactful than others."
},
{
"code": null,
"e": 4690,
"s": 4593,
"text": "Below are some parameters that are frequently tuned in a grid search to find an optimal balance."
},
{
"code": null,
"e": 4723,
"s": 4690,
"text": "Frequently tuned hyperparameters"
},
{
"code": null,
"e": 4960,
"s": 4723,
"text": "n_estimators: specifies the number of decision trees to be boosted. If n_estimator = 1, it means only 1 tree is generated, thus no boosting is at work. The default value is 100, but you can play with this number for optimal performance."
},
{
"code": null,
"e": 5170,
"s": 4960,
"text": "subsample: it represents the subsample ratio of the training sample. A subsample = 0.5 means that 50% of training data is used prior to growing a tree. The value can be any fraction but the default value is 1."
},
{
"code": null,
"e": 5314,
"s": 5170,
"text": "max_depth: it limits how deep each tree can grow. The default value is 6 but you can try other values if overfitting is an issue in your model."
},
{
"code": null,
"e": 5518,
"s": 5314,
"text": "learning_rate (alias: eta): it is a regularization parameter that shrinks feature weights in each boosting step. The default value is 0.3 but people generally tune with values such as 0.01, 0.1, 0.2 etc."
},
{
"code": null,
"e": 5701,
"s": 5518,
"text": "gamma (alias: min_split_loss): it’s another regularization parameter for tree pruning. It specifies the minimum loss reduction required to grow a tree. The default value is set at 0."
},
{
"code": null,
"e": 5836,
"s": 5701,
"text": "reg_alpha (alias: alpha): it is the L1 regularization parameter, increasing its value makes the model more conservative. Default is 0."
},
{
"code": null,
"e": 5963,
"s": 5836,
"text": "reg_lambda (alias: lambda): L2 regularization parameter, increasing its value also makes the model conservative. Default is 1."
},
{
"code": null,
"e": 5991,
"s": 5963,
"text": "Special use hyperparameters"
},
{
"code": null,
"e": 6195,
"s": 5991,
"text": "The above set of parameters are “general purpose” parameters that you can always tune to optimize model performance. There are some special purpose hyperparameters that are used in particular situations:"
},
{
"code": null,
"e": 6561,
"s": 6195,
"text": "scale_pos_weight: This parameter is useful in case you have an imbalanced dataset, particularly in classification problems, where the proportion of one class is a small fraction of total observations (e.g. credit card fraud). The default value is 1, but you can use the following ratio: total negative instance (e.g. no-fraud)/ total positive instance (e.g. fraud)."
},
{
"code": null,
"e": 6774,
"s": 6561,
"text": "monotone_constraints: You can activate this parameter if you want to increase the constraint on the predictors, for example, a non-linear, increasing likelihood of credit-loan approval with a higher credit score."
},
{
"code": null,
"e": 6925,
"s": 6774,
"text": "booster: you can choose what kind of booster method to use. You have three options: ‘dart’, ‘gbtree ’ (tree-based) and ‘gblinear ’ (Ridge regression)."
},
{
"code": null,
"e": 7198,
"s": 6925,
"text": "missing: it’s not missing value treatment exactly, it’s rather used to specify under what circumstances the algorithm should treat a value as missing (e.g. a negative value of the age of a customer certainly is impossible, thus the algorithm treats it as a missing value)."
},
{
"code": null,
"e": 7318,
"s": 7198,
"text": "eval_metric: it specifies what loss function to use, e.g MAE, MSE, RMSE for regression and log loss for classification."
},
{
"code": null,
"e": 7726,
"s": 7318,
"text": "Just 5 years ago not many people knew about XGBoost (it was initially released in 2014) and now it is revolutionizing the field of data science and machine learning and applied in all kinds of industries. It is super simple to train XGBoost but the hardest part is parameter tuning. In this article I’ve shown a simple demo implementation along with a discussion on the most frequently used hyperparameters."
}
] |
Calculate Running Total in SQL - GeeksforGeeks
|
27 Apr, 2021
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. In this article, we will be using the Microsoft SQL Server.Here we are going to see how to get the running salary total of each department. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table.
Creating Database:
CREATE geeks;
To use this database:
USE geeks;
This is our table in the geek’s database:
CREATE TABLE department(
ID int,
SALARY int,
NAME Varchar(20),
DEPT_ID Varchar(255));
Output:Command(s) completed successfully.
Add value into the table:
INSERT INTO department
VALUES (1, 34000, 'ANURAG', 'UI DEVELOPERS');
INSERT INTO department
VALUES (2, 33000, 'harsh', 'BACKEND DEVELOPERS');
INSERT INTO department
VALUES (3, 36000, 'SUMIT', 'BACKEND DEVELOPERS');
INSERT INTO department
VALUES (4, 36000, 'RUHI', 'UI DEVELOPERS');
INSERT INTO department
VALUES (5, 37000, 'KAE', 'UI DEVELOPERS');
Output:(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)
Select in SQL Server Management Studio:
This is our data inside the table:
SELECT * FROM department;
Select in SQL Server Management Studio:
Example 1:Query to Calculate Running Total in SQL Server
SELECT * ,(
SELECT SUM(T2.[SALARY])
FROM [department] AS T2
WHERE T2.[ID] <= T1.[ID]
) AS [Running Total]
FROM [department] AS T1
Output:
Select in SQL Server Management Studio:
Example 2In this SQL Server example, we’ll use the SUM Function and OVER to find the Running Total.Query to Calculate Running Total in SQL Server
SELECT *
,SUM([SALARY]) OVER (
ORDER BY [ID]
) AS [Running Total]
FROM department
Output:
Select in SQL Server Management Studio:
Example 3:In this SQL Server example, we will use PARTITION BY with OVER to find the Running Total.Query to Calculate Running Total in SQL Server
SELECT *
,SUM([SALARY]) OVER (
PARTITION BY DEPT_ID ORDER BY Id
) AS [Running Total]
FROM department
Output:
Select in SQL Server Management Studio:
DBMS-SQL
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?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25623,
"s": 25595,
"text": "\n27 Apr, 2021"
},
{
"code": null,
"e": 26098,
"s": 25623,
"text": "Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. In this article, we will be using the Microsoft SQL Server.Here we are going to see how to get the running salary total of each department. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table."
},
{
"code": null,
"e": 26117,
"s": 26098,
"text": "Creating Database:"
},
{
"code": null,
"e": 26131,
"s": 26117,
"text": "CREATE geeks;"
},
{
"code": null,
"e": 26153,
"s": 26131,
"text": "To use this database:"
},
{
"code": null,
"e": 26164,
"s": 26153,
"text": "USE geeks;"
},
{
"code": null,
"e": 26206,
"s": 26164,
"text": "This is our table in the geek’s database:"
},
{
"code": null,
"e": 26292,
"s": 26206,
"text": "CREATE TABLE department(\nID int,\nSALARY int,\nNAME Varchar(20),\nDEPT_ID Varchar(255));"
},
{
"code": null,
"e": 26334,
"s": 26292,
"text": "Output:Command(s) completed successfully."
},
{
"code": null,
"e": 26360,
"s": 26334,
"text": "Add value into the table:"
},
{
"code": null,
"e": 26717,
"s": 26360,
"text": "INSERT INTO department \nVALUES (1, 34000, 'ANURAG', 'UI DEVELOPERS');\n\nINSERT INTO department \nVALUES (2, 33000, 'harsh', 'BACKEND DEVELOPERS');\n\nINSERT INTO department \nVALUES (3, 36000, 'SUMIT', 'BACKEND DEVELOPERS');\n\nINSERT INTO department \nVALUES (4, 36000, 'RUHI', 'UI DEVELOPERS');\n\nINSERT INTO department \nVALUES (5, 37000, 'KAE', 'UI DEVELOPERS');"
},
{
"code": null,
"e": 26820,
"s": 26717,
"text": "Output:(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)"
},
{
"code": null,
"e": 26860,
"s": 26820,
"text": "Select in SQL Server Management Studio:"
},
{
"code": null,
"e": 26895,
"s": 26860,
"text": "This is our data inside the table:"
},
{
"code": null,
"e": 26921,
"s": 26895,
"text": "SELECT * FROM department;"
},
{
"code": null,
"e": 26961,
"s": 26921,
"text": "Select in SQL Server Management Studio:"
},
{
"code": null,
"e": 27018,
"s": 26961,
"text": "Example 1:Query to Calculate Running Total in SQL Server"
},
{
"code": null,
"e": 27158,
"s": 27018,
"text": "SELECT * ,(\nSELECT SUM(T2.[SALARY]) \n FROM [department] AS T2\n WHERE T2.[ID] <= T1.[ID]\n) AS [Running Total]\nFROM [department] AS T1"
},
{
"code": null,
"e": 27167,
"s": 27158,
"text": "Output: "
},
{
"code": null,
"e": 27207,
"s": 27167,
"text": "Select in SQL Server Management Studio:"
},
{
"code": null,
"e": 27353,
"s": 27207,
"text": "Example 2In this SQL Server example, we’ll use the SUM Function and OVER to find the Running Total.Query to Calculate Running Total in SQL Server"
},
{
"code": null,
"e": 27453,
"s": 27353,
"text": "SELECT *\n ,SUM([SALARY]) OVER (\n ORDER BY [ID]\n ) AS [Running Total]\nFROM department"
},
{
"code": null,
"e": 27461,
"s": 27453,
"text": "Output:"
},
{
"code": null,
"e": 27501,
"s": 27461,
"text": "Select in SQL Server Management Studio:"
},
{
"code": null,
"e": 27648,
"s": 27501,
"text": "Example 3:In this SQL Server example, we will use PARTITION BY with OVER to find the Running Total.Query to Calculate Running Total in SQL Server"
},
{
"code": null,
"e": 27754,
"s": 27648,
"text": "SELECT *\n ,SUM([SALARY]) OVER (\nPARTITION BY DEPT_ID ORDER BY Id\n) AS [Running Total]\nFROM department"
},
{
"code": null,
"e": 27763,
"s": 27754,
"text": "Output: "
},
{
"code": null,
"e": 27803,
"s": 27763,
"text": "Select in SQL Server Management Studio:"
},
{
"code": null,
"e": 27812,
"s": 27803,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 27816,
"s": 27812,
"text": "SQL"
},
{
"code": null,
"e": 27820,
"s": 27816,
"text": "SQL"
},
{
"code": null,
"e": 27918,
"s": 27820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27984,
"s": 27918,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28041,
"s": 27984,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28073,
"s": 28041,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28088,
"s": 28073,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 28166,
"s": 28088,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 28202,
"s": 28166,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 28219,
"s": 28202,
"text": "SQL using Python"
},
{
"code": null,
"e": 28285,
"s": 28219,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 28347,
"s": 28285,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Installing Apache Pig 0.17.0 on Windows 10 | by Hadi Fadlallah | Towards Data Science
|
This article is a part of a series that we are publishing on TowardsDataScience.com that aims to illustrate how to install Big Data technologies on Windows operating system.
Previously published:
Installing Hadoop 3.2.1 Single node cluster on Windows 10
Installing Apache Hive 3.1.2 on Windows 10
In this article, we will provide a step-by-step guide to install Apache Pig 0.17.0 on Windows 10.
Apache Pig is a platform build on the top of Hadoop. You can refer to our previously published article to install a Hadoop single node cluster on Windows 10.
Note that the Apache Pig latest version 0.17.0 supports Hadoop 2.x versions and still facing some compatibility issues with Hadoop 3.x. In this article, we will only illustrate the installation since we are working with Hadoop 3.2.1
7zip is needed to extract .tar.gz archives we will be downloading in this guide.
To download the Apache Pig, you should go to the following link:
https://downloads.apache.org/pig/
If you are looking for the latest version, navigate to “latest” directory, then download the pig-x.xx.x.tar.gz file.
After the file is downloaded, we should extract it twice using 7zip (using 7zip: the first time we extract the .tar.gz file, the second time we extract the .tar file). We will extract the Pig folder into “E:\hadoop-env” directory as used in the previous articles.
After extracting Derby and Hive archives, we should go to Control Panel > System and Security > System. Then Click on “Advanced system settings”.
In the advanced system settings dialog, click on “Environment variables” button.
Now we should add the following user variables:
PIG_HOME: “E:\hadoop-env\pig-0.17.0”
Now, we should edit the Path user variable to add the following paths:
%PIG_HOME%\bin
After setting environment variables, let's try to run Apache Pig.
Note: Hadoop Services must be running
Open a command prompt as administrator, and execute the following command
pig -version
You will receive the following exception:
'E:\hadoop-env\hadoop-3.2.1\bin\hadoop-config.cmd' is not recognized as an internal or external command,operable program or batch file.'-Xmx1000M' is not recognized as an internal or external command,operable program or batch file.
To fix this error, we should edit the pig.cmd file located in the “pig-0.17.0\bin” directory by changing the HADOOP_BIN_PATH value from “%HADOOP_HOME%\bin” to “%HADOOP_HOME%\libexec”.
Now, let's try to run the “pig -version” command again:
The simplest way to write PigLatin statements is using Grunt shell which is an interactive tool where we write a statement and get the desired output. There are two modes to involve Grunt Shell:
Local: All scripts are executed on a single machine without requiring Hadoop. (command: pig -x local)MapReduce: Scripts are executed on a Hadoop cluster (command: pig -x MapReduce)
Local: All scripts are executed on a single machine without requiring Hadoop. (command: pig -x local)
MapReduce: Scripts are executed on a Hadoop cluster (command: pig -x MapReduce)
Since we have installed Apache Hadoop 3.2.1 which is not compatible with Pig 0.17.0, we will try to run Pig using local mode.
Stackoverflow.com QA WebsiteApache Pig official websiteSolutionMandi: Pig Installation on Windows 10
Stackoverflow.com QA Website
Apache Pig official website
SolutionMandi: Pig Installation on Windows 10
|
[
{
"code": null,
"e": 345,
"s": 171,
"text": "This article is a part of a series that we are publishing on TowardsDataScience.com that aims to illustrate how to install Big Data technologies on Windows operating system."
},
{
"code": null,
"e": 367,
"s": 345,
"text": "Previously published:"
},
{
"code": null,
"e": 425,
"s": 367,
"text": "Installing Hadoop 3.2.1 Single node cluster on Windows 10"
},
{
"code": null,
"e": 468,
"s": 425,
"text": "Installing Apache Hive 3.1.2 on Windows 10"
},
{
"code": null,
"e": 566,
"s": 468,
"text": "In this article, we will provide a step-by-step guide to install Apache Pig 0.17.0 on Windows 10."
},
{
"code": null,
"e": 724,
"s": 566,
"text": "Apache Pig is a platform build on the top of Hadoop. You can refer to our previously published article to install a Hadoop single node cluster on Windows 10."
},
{
"code": null,
"e": 957,
"s": 724,
"text": "Note that the Apache Pig latest version 0.17.0 supports Hadoop 2.x versions and still facing some compatibility issues with Hadoop 3.x. In this article, we will only illustrate the installation since we are working with Hadoop 3.2.1"
},
{
"code": null,
"e": 1038,
"s": 957,
"text": "7zip is needed to extract .tar.gz archives we will be downloading in this guide."
},
{
"code": null,
"e": 1103,
"s": 1038,
"text": "To download the Apache Pig, you should go to the following link:"
},
{
"code": null,
"e": 1137,
"s": 1103,
"text": "https://downloads.apache.org/pig/"
},
{
"code": null,
"e": 1254,
"s": 1137,
"text": "If you are looking for the latest version, navigate to “latest” directory, then download the pig-x.xx.x.tar.gz file."
},
{
"code": null,
"e": 1518,
"s": 1254,
"text": "After the file is downloaded, we should extract it twice using 7zip (using 7zip: the first time we extract the .tar.gz file, the second time we extract the .tar file). We will extract the Pig folder into “E:\\hadoop-env” directory as used in the previous articles."
},
{
"code": null,
"e": 1664,
"s": 1518,
"text": "After extracting Derby and Hive archives, we should go to Control Panel > System and Security > System. Then Click on “Advanced system settings”."
},
{
"code": null,
"e": 1745,
"s": 1664,
"text": "In the advanced system settings dialog, click on “Environment variables” button."
},
{
"code": null,
"e": 1793,
"s": 1745,
"text": "Now we should add the following user variables:"
},
{
"code": null,
"e": 1830,
"s": 1793,
"text": "PIG_HOME: “E:\\hadoop-env\\pig-0.17.0”"
},
{
"code": null,
"e": 1901,
"s": 1830,
"text": "Now, we should edit the Path user variable to add the following paths:"
},
{
"code": null,
"e": 1916,
"s": 1901,
"text": "%PIG_HOME%\\bin"
},
{
"code": null,
"e": 1982,
"s": 1916,
"text": "After setting environment variables, let's try to run Apache Pig."
},
{
"code": null,
"e": 2020,
"s": 1982,
"text": "Note: Hadoop Services must be running"
},
{
"code": null,
"e": 2094,
"s": 2020,
"text": "Open a command prompt as administrator, and execute the following command"
},
{
"code": null,
"e": 2107,
"s": 2094,
"text": "pig -version"
},
{
"code": null,
"e": 2149,
"s": 2107,
"text": "You will receive the following exception:"
},
{
"code": null,
"e": 2381,
"s": 2149,
"text": "'E:\\hadoop-env\\hadoop-3.2.1\\bin\\hadoop-config.cmd' is not recognized as an internal or external command,operable program or batch file.'-Xmx1000M' is not recognized as an internal or external command,operable program or batch file."
},
{
"code": null,
"e": 2565,
"s": 2381,
"text": "To fix this error, we should edit the pig.cmd file located in the “pig-0.17.0\\bin” directory by changing the HADOOP_BIN_PATH value from “%HADOOP_HOME%\\bin” to “%HADOOP_HOME%\\libexec”."
},
{
"code": null,
"e": 2621,
"s": 2565,
"text": "Now, let's try to run the “pig -version” command again:"
},
{
"code": null,
"e": 2816,
"s": 2621,
"text": "The simplest way to write PigLatin statements is using Grunt shell which is an interactive tool where we write a statement and get the desired output. There are two modes to involve Grunt Shell:"
},
{
"code": null,
"e": 2997,
"s": 2816,
"text": "Local: All scripts are executed on a single machine without requiring Hadoop. (command: pig -x local)MapReduce: Scripts are executed on a Hadoop cluster (command: pig -x MapReduce)"
},
{
"code": null,
"e": 3099,
"s": 2997,
"text": "Local: All scripts are executed on a single machine without requiring Hadoop. (command: pig -x local)"
},
{
"code": null,
"e": 3179,
"s": 3099,
"text": "MapReduce: Scripts are executed on a Hadoop cluster (command: pig -x MapReduce)"
},
{
"code": null,
"e": 3305,
"s": 3179,
"text": "Since we have installed Apache Hadoop 3.2.1 which is not compatible with Pig 0.17.0, we will try to run Pig using local mode."
},
{
"code": null,
"e": 3406,
"s": 3305,
"text": "Stackoverflow.com QA WebsiteApache Pig official websiteSolutionMandi: Pig Installation on Windows 10"
},
{
"code": null,
"e": 3435,
"s": 3406,
"text": "Stackoverflow.com QA Website"
},
{
"code": null,
"e": 3463,
"s": 3435,
"text": "Apache Pig official website"
}
] |
jQuery | index() with examples - GeeksforGeeks
|
13 Feb, 2019
The index() is an inbuilt method in jQuery which is used to return the index of the a specified elements with respect to selector.Syntax:
$(selector).index(element)
Parameter: It accepts an optional parameter “element” which is used to get the position of the element.Return value: It returns an integer denoting the index of the specified element.
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> <!--jQuery code to demonstrate index function --> // document ready $(document).ready(function() { // if the list is clicked $("li").click(function() { // index() // to return the index of the clicked // element of the list document.getElementById("demo").innerHTML = "Clicked Index " + $(this).index(); }); }); </script></head> <body> <p>Click on the elements of the list to display their index number with respect to the other elements in the list.</p> <ul> <li>Geeks</li> <li>for</li> <li>Geeks</li> </ul> <p id="demo"></p></body> </html>
Output:Before clicking on any element on the list
Click on the elements of the list to display their index number with
respect to the other elements in the list.
GeeksforGeeks
Click on the elements of the list to display their index number with
respect to the other elements in the list.
Geeks
for
Geeks
After clicking on “for”-
Click on the elements of the list to display their index number with
respect with the other elements in the list.
GeeksforGeeks
Clicked Index 1
Click on the elements of the list to display their index number with
respect with the other elements in the list.
Geeks
for
Geeks
Code #2:
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> <!--jQuery code to demonstrate index function --> // document ready $(document).ready(function() { // if the list is clicked $("li").click(function() { // index() // to return the index of the clicked // element of the list document.getElementById("demo").innerHTML = "Clicked Index " + $($(".myclass")).index($("#id")); }); }); </script></head> <body> <p>Click on the elements of the list to display their index number with respect with the other elements in the list.</p> <ul> <li>Geeks</li> <li class="myclass">for</li> <li class="myclass" id="id">Geeks</li> </ul> <p id="demo"></p></body> </html>
Output:Before clicking on any element on the list-
Click on the elements of the list to display their index number with
respect with the other elements in the list.
GeeksforGeeks
Click on the elements of the list to display their index number with
respect with the other elements in the list.
Geeks
for
Geeks
After clicking on any element of the list-
Click on the elements of the list to display their index number with
respect with the other elements in the list.
GeeksforGeeks
Clicked Index 1
Click on the elements of the list to display their index number with
respect with the other elements in the list.
Geeks
for
Geeks
jQuery-Misc
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to fetch data from JSON file and display in HTML table using jQuery ?
How to Dynamically Add/Remove Table Rows using jQuery ?
|
[
{
"code": null,
"e": 26716,
"s": 26688,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 26854,
"s": 26716,
"text": "The index() is an inbuilt method in jQuery which is used to return the index of the a specified elements with respect to selector.Syntax:"
},
{
"code": null,
"e": 26882,
"s": 26854,
"text": "$(selector).index(element)\n"
},
{
"code": null,
"e": 27066,
"s": 26882,
"text": "Parameter: It accepts an optional parameter “element” which is used to get the position of the element.Return value: It returns an integer denoting the index of the specified element."
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> <!--jQuery code to demonstrate index function --> // document ready $(document).ready(function() { // if the list is clicked $(\"li\").click(function() { // index() // to return the index of the clicked // element of the list document.getElementById(\"demo\").innerHTML = \"Clicked Index \" + $(this).index(); }); }); </script></head> <body> <p>Click on the elements of the list to display their index number with respect to the other elements in the list.</p> <ul> <li>Geeks</li> <li>for</li> <li>Geeks</li> </ul> <p id=\"demo\"></p></body> </html>",
"e": 27983,
"s": 27066,
"text": null
},
{
"code": null,
"e": 28033,
"s": 27983,
"text": "Output:Before clicking on any element on the list"
},
{
"code": null,
"e": 28160,
"s": 28033,
"text": "Click on the elements of the list to display their index number with \nrespect to the other elements in the list.\nGeeksforGeeks"
},
{
"code": null,
"e": 28274,
"s": 28160,
"text": "Click on the elements of the list to display their index number with \nrespect to the other elements in the list.\n"
},
{
"code": null,
"e": 28280,
"s": 28274,
"text": "Geeks"
},
{
"code": null,
"e": 28284,
"s": 28280,
"text": "for"
},
{
"code": null,
"e": 28290,
"s": 28284,
"text": "Geeks"
},
{
"code": null,
"e": 28315,
"s": 28290,
"text": "After clicking on “for”-"
},
{
"code": null,
"e": 28461,
"s": 28315,
"text": "Click on the elements of the list to display their index number with \nrespect with the other elements in the list.\nGeeksforGeeks\nClicked Index 1\n"
},
{
"code": null,
"e": 28577,
"s": 28461,
"text": "Click on the elements of the list to display their index number with \nrespect with the other elements in the list.\n"
},
{
"code": null,
"e": 28583,
"s": 28577,
"text": "Geeks"
},
{
"code": null,
"e": 28587,
"s": 28583,
"text": "for"
},
{
"code": null,
"e": 28593,
"s": 28587,
"text": "Geeks"
},
{
"code": null,
"e": 28602,
"s": 28593,
"text": "Code #2:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> <!--jQuery code to demonstrate index function --> // document ready $(document).ready(function() { // if the list is clicked $(\"li\").click(function() { // index() // to return the index of the clicked // element of the list document.getElementById(\"demo\").innerHTML = \"Clicked Index \" + $($(\".myclass\")).index($(\"#id\")); }); }); </script></head> <body> <p>Click on the elements of the list to display their index number with respect with the other elements in the list.</p> <ul> <li>Geeks</li> <li class=\"myclass\">for</li> <li class=\"myclass\" id=\"id\">Geeks</li> </ul> <p id=\"demo\"></p></body> </html>",
"e": 29554,
"s": 28602,
"text": null
},
{
"code": null,
"e": 29605,
"s": 29554,
"text": "Output:Before clicking on any element on the list-"
},
{
"code": null,
"e": 29735,
"s": 29605,
"text": "Click on the elements of the list to display their index number with \nrespect with the other elements in the list.\nGeeksforGeeks\n"
},
{
"code": null,
"e": 29851,
"s": 29735,
"text": "Click on the elements of the list to display their index number with \nrespect with the other elements in the list.\n"
},
{
"code": null,
"e": 29857,
"s": 29851,
"text": "Geeks"
},
{
"code": null,
"e": 29861,
"s": 29857,
"text": "for"
},
{
"code": null,
"e": 29867,
"s": 29861,
"text": "Geeks"
},
{
"code": null,
"e": 29910,
"s": 29867,
"text": "After clicking on any element of the list-"
},
{
"code": null,
"e": 30056,
"s": 29910,
"text": "Click on the elements of the list to display their index number with \nrespect with the other elements in the list.\nGeeksforGeeks\nClicked Index 1\n"
},
{
"code": null,
"e": 30172,
"s": 30056,
"text": "Click on the elements of the list to display their index number with \nrespect with the other elements in the list.\n"
},
{
"code": null,
"e": 30178,
"s": 30172,
"text": "Geeks"
},
{
"code": null,
"e": 30182,
"s": 30178,
"text": "for"
},
{
"code": null,
"e": 30188,
"s": 30182,
"text": "Geeks"
},
{
"code": null,
"e": 30200,
"s": 30188,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 30211,
"s": 30200,
"text": "JavaScript"
},
{
"code": null,
"e": 30218,
"s": 30211,
"text": "JQuery"
},
{
"code": null,
"e": 30316,
"s": 30218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30356,
"s": 30316,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30417,
"s": 30356,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30458,
"s": 30417,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30480,
"s": 30458,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 30534,
"s": 30480,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30580,
"s": 30534,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 30609,
"s": 30580,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30672,
"s": 30609,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 30746,
"s": 30672,
"text": "How to fetch data from JSON file and display in HTML table using jQuery ?"
}
] |
True, False, and Nil In Ruby - GeeksforGeeks
|
02 Sep, 2021
Ruby is an open-sourced object-oriented programming language developed by Yukihiro Matsumoto. In Ruby, everything is treated as an object. true, false and nil are built-in data types of Ruby. Note: Always remember in Ruby true, false, and nil are objects, not numbers. Whenever Ruby requires a Boolean value, then nil behaves like false and values other than nil or false behave like true.
In Ruby, true and false are boolean values that represent yes and no. true is an object of TrueClass and false is an object of FalseClass. Note: Ruby does not contain Boolean class. Let’s see a few examples of true and false in Ruby. Example 1:
Ruby
# Ruby program to illustrate the use# of true and falsea = 4b = 4 if a == b # If Condition is true puts "True! a and b are equal" else # If Condition is false puts "False! a and b are not equal" end
Output:
True! a and b are equal
Example 2:
Ruby
# Ruby program to illustrate the use# of true and falsea1 = "GeeksforGeeks"b1 = "GeeksforGeeks"result1 = a1 == b1 puts result1 a2 = "GeeksforGeeks"b2 = "geeks"result2 = a2 == b2 puts result2
Output:
true
false
Example 3:
Ruby
# Ruby program to illustrate the use# of true and false # If condition is trueif 55 == 55 puts "GeeksforGeeks !" # If Condition is falseelse puts " A Computer Science Portal for Geeks!" end
Output:
GeeksforGeeks !
In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby’s way of referring to nothing or void. Ruby also provide a nil? method to detect if any object is nil or not. Example 1:
Ruby
# Checking for nil's classa = nil.classputs a
Output:
NilClass
Example 2:
Ruby
# Ruby program to illustrate nil? method# Checking for Nilarray = [ 1, 2, 3, 4, 5 ] # Since array[5] does not exist so, it is nil.result1 = array[5].nil?puts result1 # Since array[2] exists so, it is not nil.result2 = array[2].nil?puts result2
Output:
true
false
surindertarika1234
Picked
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Types of Iterators
Ruby | Types of Variables
Ruby | String concat Method
Ruby | Array collect() operation
Ruby | Enumerator each_with_index function
Ruby | Class Method and Variables
Ruby | Array reverse() function
Ruby | Operators
Ruby | Module
Ruby on Rails Introduction
|
[
{
"code": null,
"e": 23906,
"s": 23878,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 24297,
"s": 23906,
"text": "Ruby is an open-sourced object-oriented programming language developed by Yukihiro Matsumoto. In Ruby, everything is treated as an object. true, false and nil are built-in data types of Ruby. Note: Always remember in Ruby true, false, and nil are objects, not numbers. Whenever Ruby requires a Boolean value, then nil behaves like false and values other than nil or false behave like true. "
},
{
"code": null,
"e": 24544,
"s": 24297,
"text": "In Ruby, true and false are boolean values that represent yes and no. true is an object of TrueClass and false is an object of FalseClass. Note: Ruby does not contain Boolean class. Let’s see a few examples of true and false in Ruby. Example 1: "
},
{
"code": null,
"e": 24549,
"s": 24544,
"text": "Ruby"
},
{
"code": "# Ruby program to illustrate the use# of true and falsea = 4b = 4 if a == b # If Condition is true puts \"True! a and b are equal\" else # If Condition is false puts \"False! a and b are not equal\" end",
"e": 24778,
"s": 24549,
"text": null
},
{
"code": null,
"e": 24788,
"s": 24778,
"text": "Output: "
},
{
"code": null,
"e": 24812,
"s": 24788,
"text": "True! a and b are equal"
},
{
"code": null,
"e": 24825,
"s": 24812,
"text": "Example 2: "
},
{
"code": null,
"e": 24830,
"s": 24825,
"text": "Ruby"
},
{
"code": "# Ruby program to illustrate the use# of true and falsea1 = \"GeeksforGeeks\"b1 = \"GeeksforGeeks\"result1 = a1 == b1 puts result1 a2 = \"GeeksforGeeks\"b2 = \"geeks\"result2 = a2 == b2 puts result2",
"e": 25021,
"s": 24830,
"text": null
},
{
"code": null,
"e": 25031,
"s": 25021,
"text": "Output: "
},
{
"code": null,
"e": 25042,
"s": 25031,
"text": "true\nfalse"
},
{
"code": null,
"e": 25055,
"s": 25042,
"text": "Example 3: "
},
{
"code": null,
"e": 25060,
"s": 25055,
"text": "Ruby"
},
{
"code": "# Ruby program to illustrate the use# of true and false # If condition is trueif 55 == 55 puts \"GeeksforGeeks !\" # If Condition is falseelse puts \" A Computer Science Portal for Geeks!\" end",
"e": 25256,
"s": 25060,
"text": null
},
{
"code": null,
"e": 25266,
"s": 25256,
"text": "Output: "
},
{
"code": null,
"e": 25282,
"s": 25266,
"text": "GeeksforGeeks !"
},
{
"code": null,
"e": 25520,
"s": 25284,
"text": "In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby’s way of referring to nothing or void. Ruby also provide a nil? method to detect if any object is nil or not. Example 1: "
},
{
"code": null,
"e": 25525,
"s": 25520,
"text": "Ruby"
},
{
"code": "# Checking for nil's classa = nil.classputs a",
"e": 25571,
"s": 25525,
"text": null
},
{
"code": null,
"e": 25581,
"s": 25571,
"text": "Output: "
},
{
"code": null,
"e": 25591,
"s": 25581,
"text": " NilClass"
},
{
"code": null,
"e": 25604,
"s": 25591,
"text": "Example 2: "
},
{
"code": null,
"e": 25609,
"s": 25604,
"text": "Ruby"
},
{
"code": "# Ruby program to illustrate nil? method# Checking for Nilarray = [ 1, 2, 3, 4, 5 ] # Since array[5] does not exist so, it is nil.result1 = array[5].nil?puts result1 # Since array[2] exists so, it is not nil.result2 = array[2].nil?puts result2",
"e": 25853,
"s": 25609,
"text": null
},
{
"code": null,
"e": 25863,
"s": 25853,
"text": "Output: "
},
{
"code": null,
"e": 25874,
"s": 25863,
"text": "true\nfalse"
},
{
"code": null,
"e": 25895,
"s": 25876,
"text": "surindertarika1234"
},
{
"code": null,
"e": 25902,
"s": 25895,
"text": "Picked"
},
{
"code": null,
"e": 25907,
"s": 25902,
"text": "Ruby"
},
{
"code": null,
"e": 26005,
"s": 25907,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26014,
"s": 26005,
"text": "Comments"
},
{
"code": null,
"e": 26027,
"s": 26014,
"text": "Old Comments"
},
{
"code": null,
"e": 26053,
"s": 26027,
"text": "Ruby | Types of Iterators"
},
{
"code": null,
"e": 26079,
"s": 26053,
"text": "Ruby | Types of Variables"
},
{
"code": null,
"e": 26107,
"s": 26079,
"text": "Ruby | String concat Method"
},
{
"code": null,
"e": 26140,
"s": 26107,
"text": "Ruby | Array collect() operation"
},
{
"code": null,
"e": 26183,
"s": 26140,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 26217,
"s": 26183,
"text": "Ruby | Class Method and Variables"
},
{
"code": null,
"e": 26249,
"s": 26217,
"text": "Ruby | Array reverse() function"
},
{
"code": null,
"e": 26266,
"s": 26249,
"text": "Ruby | Operators"
},
{
"code": null,
"e": 26280,
"s": 26266,
"text": "Ruby | Module"
}
] |
C# - Variables
|
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.
The basic value types provided in C# can be categorized as −
C# also allows defining other value types of variable such as enum and reference types of variables such as class, which we will cover in subsequent chapters.
Syntax for variable definition in C# is −
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas.
Some valid variable definitions are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
You can initialize a variable at the time of definition as −
int i = 100;
Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is −
variable_name = value;
Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as −
<data_type> <variable_name> = value;
Some examples are −
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result.
The following example uses various types of variables −
using System;
namespace VariableDefinition {
class Program {
static void Main(string[] args) {
short a;
int b ;
double c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
The Console class in the System namespace provides a function ReadLine() for accepting input from the user and store it into a variable.
For example,
int num;
num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.
There are two kinds of expressions in C# −
lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and hence they may appear on the left-hand side of an assignment. Numeric literals are rvalues and hence they may not be assigned and can not appear on the left-hand side. Following is a valid C# statement −
int g = 20;
But following is not a valid statement and would generate compile-time error −
10 = 20;
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2585,
"s": 2270,
"text": "A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 2646,
"s": 2585,
"text": "The basic value types provided in C# can be categorized as −"
},
{
"code": null,
"e": 2806,
"s": 2646,
"text": "C# also allows defining other value types of variable such as enum and reference types of variables such as class, which we will cover in subsequent chapters."
},
{
"code": null,
"e": 2848,
"s": 2806,
"text": "Syntax for variable definition in C# is −"
},
{
"code": null,
"e": 2878,
"s": 2848,
"text": "<data_type> <variable_list>;\n"
},
{
"code": null,
"e": 3073,
"s": 2878,
"text": "Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas."
},
{
"code": null,
"e": 3122,
"s": 3073,
"text": "Some valid variable definitions are shown here −"
},
{
"code": null,
"e": 3175,
"s": 3122,
"text": "int i, j, k;\nchar c, ch;\nfloat f, salary;\ndouble d;\n"
},
{
"code": null,
"e": 3236,
"s": 3175,
"text": "You can initialize a variable at the time of definition as −"
},
{
"code": null,
"e": 3250,
"s": 3236,
"text": "int i = 100;\n"
},
{
"code": null,
"e": 3389,
"s": 3250,
"text": "Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is −"
},
{
"code": null,
"e": 3413,
"s": 3389,
"text": "variable_name = value;\n"
},
{
"code": null,
"e": 3545,
"s": 3413,
"text": "Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as −"
},
{
"code": null,
"e": 3583,
"s": 3545,
"text": "<data_type> <variable_name> = value;\n"
},
{
"code": null,
"e": 3603,
"s": 3583,
"text": "Some examples are −"
},
{
"code": null,
"e": 3815,
"s": 3603,
"text": "int d = 3, f = 5; /* initializing d and f. */\nbyte z = 22; /* initializes z. */\ndouble pi = 3.14159; /* declares an approximation of pi. */\nchar x = 'x'; /* the variable x has the value 'x'. */"
},
{
"code": null,
"e": 3942,
"s": 3815,
"text": "It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result."
},
{
"code": null,
"e": 3998,
"s": 3942,
"text": "The following example uses various types of variables −"
},
{
"code": null,
"e": 4359,
"s": 3998,
"text": "using System;\n\nnamespace VariableDefinition {\n class Program {\n static void Main(string[] args) {\n short a;\n int b ;\n double c;\n\n /* actual initialization */\n a = 10;\n b = 20;\n c = a + b;\n Console.WriteLine(\"a = {0}, b = {1}, c = {2}\", a, b, c);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 4440,
"s": 4359,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4464,
"s": 4440,
"text": "a = 10, b = 20, c = 30\n"
},
{
"code": null,
"e": 4601,
"s": 4464,
"text": "The Console class in the System namespace provides a function ReadLine() for accepting input from the user and store it into a variable."
},
{
"code": null,
"e": 4614,
"s": 4601,
"text": "For example,"
},
{
"code": null,
"e": 4666,
"s": 4614,
"text": "int num;\nnum = Convert.ToInt32(Console.ReadLine());"
},
{
"code": null,
"e": 4815,
"s": 4666,
"text": "The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format."
},
{
"code": null,
"e": 4858,
"s": 4815,
"text": "There are two kinds of expressions in C# −"
},
{
"code": null,
"e": 4971,
"s": 4858,
"text": "lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 5084,
"s": 4971,
"text": "lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 5191,
"s": 5084,
"text": "rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 5298,
"s": 5191,
"text": "rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 5528,
"s": 5298,
"text": "Variables are lvalues and hence they may appear on the left-hand side of an assignment. Numeric literals are rvalues and hence they may not be assigned and can not appear on the left-hand side. Following is a valid C# statement −"
},
{
"code": null,
"e": 5541,
"s": 5528,
"text": "int g = 20;\n"
},
{
"code": null,
"e": 5620,
"s": 5541,
"text": "But following is not a valid statement and would generate compile-time error −"
},
{
"code": null,
"e": 5630,
"s": 5620,
"text": "10 = 20;\n"
},
{
"code": null,
"e": 5667,
"s": 5630,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 5680,
"s": 5667,
"text": " Raja Biswas"
},
{
"code": null,
"e": 5714,
"s": 5680,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5732,
"s": 5714,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 5765,
"s": 5732,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5779,
"s": 5765,
"text": " Peter Jepson"
},
{
"code": null,
"e": 5816,
"s": 5779,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 5831,
"s": 5816,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 5866,
"s": 5831,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 5881,
"s": 5866,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5916,
"s": 5881,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5928,
"s": 5916,
"text": " Eric Frick"
},
{
"code": null,
"e": 5935,
"s": 5928,
"text": " Print"
},
{
"code": null,
"e": 5946,
"s": 5935,
"text": " Add Notes"
}
] |
Program to concatenate two given Matrices of same size
|
12 Apr, 2021
Given two matrices A and B of size M x N, the task is to concatenate them into one matrix.Concatenation of matrix: The process of appending elements of every row of the matrix one after the other is known as the Concatenation of matrix. Examples:
Input:
A[][] = {{1, 2},
{3, 4}},
B[][] = {{5, 6},
{7, 8}}
Output:
1 2 5 6
3 4 7 8
Explanation:
Elements of every row of the matrix B
is appended into the row of matrix A.
Input:
A[][] = {{2, 4},
{3, 4}}
B[][] = {{1, 2},
{1, 3}}
Output:
2 4 1 2
3 4 1 3
Approach: The idea is to declare a matrix of size N x 2*M, then traverse over matrix A and store the elements in the first half of the matrix and then similarly iterate over matrix B and store the elements in another half of the matrix with the help of the below formulae:
// For filling the
// first half of matrix
matrix[i][j] = A[i][j]
// For filling the
// second half of matrix
matrix[i][j+N] = A[i][j + N]
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to concatenate// two matrices of size N x M #include <bits/stdc++.h> using namespace std; #define M 2#define N 2 // Function to concatenate two// matrices A[][] and B[][]void mergeMatrix(int A[M][N], int B[M][N]){ // Matrix to store // the result int C[M][2 * N]; // Merge the two matrices for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { // To store elements // of matrix A C[i][j] = A[i][j]; // To store elements // of matrix B C[i][j + N] = B[i][j]; } } // Print the result for (int i = 0; i < M; i++) { for (int j = 0; j < 2 * N; j++) cout << C[i][j] << " "; cout << endl; }} // Driven Codeint main(){ int A[M][N] = { { 1, 2 }, { 3, 4 } }; int B[M][N] = { { 5, 6 }, { 7, 8 } }; // Find the merge of // the 2 matrices mergeMatrix(A, B); return 0;}
// Java implementation to concatenate// two matrices of size N x Mclass GFG{ static final int M = 2;static final int N = 2; // Function to concatenate two// matrices A[][] and B[][]static void mergeMatrix(int A[][], int B[][]){ // Matrix to store // the result int [][]C = new int[M][2 * N]; // Merge the two matrices for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { // To store elements // of matrix A C[i][j] = A[i][j]; // To store elements // of matrix B C[i][j + N] = B[i][j]; } } // Print the result for(int i = 0; i < M; i++) { for(int j = 0; j < 2 * N; j++) System.out.print(C[i][j] + " "); System.out.println(); }} // Driven Codepublic static void main(String[] args){ int A[][] = { { 1, 2 }, { 3, 4 } }; int B[][] = { { 5, 6 }, { 7, 8 } }; // Find the merge of // the 2 matrices mergeMatrix(A, B);}} // This code is contributed by gauravrajput1
# Python3 implementation to concatenate# two matrices of size N x M M = 2N = 2 # Function to concatenate two# matrices A[][] and B[][]def mergeMatrix(A, B): # Matrix to store # the result C = [[0 for j in range(2 * N)] for i in range(M)] # Merge the two matrices for i in range(M): for j in range(N): # To store elements # of matrix A C[i][j] = A[i][j] # To store elements # of matrix B C[i][j + N] = B[i][j] # Print the result for i in range(M): for j in range(2 * N): print(C[i][j], end = ' ') print() # Driver codeif __name__=='__main__': A = [ [1, 2], [3, 4] ] B = [ [5, 6], [7, 8] ] # Find the merge of # the 2 matrices mergeMatrix(A, B) # This code is contributed by rutvik_56
// C# implementation to concatenate// two matrices of size N x Musing System; class GFG{ const int M = 2;const int N = 2; // Function to concatenate two// matrices A[][] and B[][]static void mergeMatrix(int[,] A, int[,] B){ // Matrix to store // the result int[,] C = new int[M, 2 * N]; // Merge the two matrices for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { // To store elements // of matrix A C[i, j] = A[i, j]; // To store elements // of matrix B C[i, j + N] = B[i, j]; } } // Print the result for(int i = 0; i < M; i++) { for(int j = 0; j < 2 * N; j++) Console.Write(C[i, j] + " "); Console.WriteLine(); }} // Driver codestatic void Main(){ int[,] A = { { 1, 2 }, { 3, 4 } }; int[,] B = { { 5, 6 }, { 7, 8 } }; // Find the merge of // the 2 matrices mergeMatrix(A, B);}} // This code is contributed by divyeshrabadiya07
<script>// Javascript implementation to concatenate// two matrices of size N x MM = 2N = 2 // Function to concatenate two// matrices A[][] and B[][]function mergeMatrix(A,B){ // Matrix to store // the result var C = [[0,0,0,0], [0,0,0,0]] // Merge the two matrices for (var i = 0; i < M; i++) { for (var j = 0; j < N; j++) { // To store elements // of matrix A C[i][j] = A[i][j]; // To store elements // of matrix B C[i][j + N] = B[i][j]; } } // Print the result for (var i = 0; i < M; i++) { for (var j = 0; j < 2 * N; j++) document.write( C[i][j] + " "); document.write("<br>"); }} // Driven Codevar A = [ [ 1, 2 ], [ 3, 4 ] ];var B = [ [ 5, 6 ], [ 7, 8 ] ]; // Find the merge of// the 2 matricesmergeMatrix(A, B); // This code is contributed by noob2000.</script>
1 2 5 6
3 4 7 8
Time Complexity: O(M * N)
Auxiliary Space: O(M * N)
GauravRajput1
rutvik_56
divyeshrabadiya07
subhammahato348
noob2000
Arrays
Matrix
School Programming
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Find duplicates in O(n) time and O(1) extra space | Set 1
Chocolate Distribution Problem
Matrix Chain Multiplication | DP-8
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem
Find the number of islands | Set 1 (Using DFS)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 276,
"s": 28,
"text": "Given two matrices A and B of size M x N, the task is to concatenate them into one matrix.Concatenation of matrix: The process of appending elements of every row of the matrix one after the other is known as the Concatenation of matrix. Examples: "
},
{
"code": null,
"e": 581,
"s": 276,
"text": "Input:\nA[][] = {{1, 2}, \n {3, 4}},\nB[][] = {{5, 6}, \n {7, 8}}\nOutput: \n1 2 5 6\n3 4 7 8\nExplanation:\nElements of every row of the matrix B \nis appended into the row of matrix A.\n\nInput: \nA[][] = {{2, 4}, \n {3, 4}}\nB[][] = {{1, 2}, \n {1, 3}} \nOutput: \n2 4 1 2 \n3 4 1 3"
},
{
"code": null,
"e": 855,
"s": 581,
"text": "Approach: The idea is to declare a matrix of size N x 2*M, then traverse over matrix A and store the elements in the first half of the matrix and then similarly iterate over matrix B and store the elements in another half of the matrix with the help of the below formulae: "
},
{
"code": null,
"e": 995,
"s": 855,
"text": "// For filling the\n// first half of matrix\nmatrix[i][j] = A[i][j]\n\n// For filling the\n// second half of matrix\nmatrix[i][j+N] = A[i][j + N]"
},
{
"code": null,
"e": 1047,
"s": 995,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1051,
"s": 1047,
"text": "C++"
},
{
"code": null,
"e": 1056,
"s": 1051,
"text": "Java"
},
{
"code": null,
"e": 1064,
"s": 1056,
"text": "Python3"
},
{
"code": null,
"e": 1067,
"s": 1064,
"text": "C#"
},
{
"code": null,
"e": 1078,
"s": 1067,
"text": "Javascript"
},
{
"code": "// C++ implementation to concatenate// two matrices of size N x M #include <bits/stdc++.h> using namespace std; #define M 2#define N 2 // Function to concatenate two// matrices A[][] and B[][]void mergeMatrix(int A[M][N], int B[M][N]){ // Matrix to store // the result int C[M][2 * N]; // Merge the two matrices for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { // To store elements // of matrix A C[i][j] = A[i][j]; // To store elements // of matrix B C[i][j + N] = B[i][j]; } } // Print the result for (int i = 0; i < M; i++) { for (int j = 0; j < 2 * N; j++) cout << C[i][j] << \" \"; cout << endl; }} // Driven Codeint main(){ int A[M][N] = { { 1, 2 }, { 3, 4 } }; int B[M][N] = { { 5, 6 }, { 7, 8 } }; // Find the merge of // the 2 matrices mergeMatrix(A, B); return 0;}",
"e": 2086,
"s": 1078,
"text": null
},
{
"code": "// Java implementation to concatenate// two matrices of size N x Mclass GFG{ static final int M = 2;static final int N = 2; // Function to concatenate two// matrices A[][] and B[][]static void mergeMatrix(int A[][], int B[][]){ // Matrix to store // the result int [][]C = new int[M][2 * N]; // Merge the two matrices for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { // To store elements // of matrix A C[i][j] = A[i][j]; // To store elements // of matrix B C[i][j + N] = B[i][j]; } } // Print the result for(int i = 0; i < M; i++) { for(int j = 0; j < 2 * N; j++) System.out.print(C[i][j] + \" \"); System.out.println(); }} // Driven Codepublic static void main(String[] args){ int A[][] = { { 1, 2 }, { 3, 4 } }; int B[][] = { { 5, 6 }, { 7, 8 } }; // Find the merge of // the 2 matrices mergeMatrix(A, B);}} // This code is contributed by gauravrajput1",
"e": 3176,
"s": 2086,
"text": null
},
{
"code": "# Python3 implementation to concatenate# two matrices of size N x M M = 2N = 2 # Function to concatenate two# matrices A[][] and B[][]def mergeMatrix(A, B): # Matrix to store # the result C = [[0 for j in range(2 * N)] for i in range(M)] # Merge the two matrices for i in range(M): for j in range(N): # To store elements # of matrix A C[i][j] = A[i][j] # To store elements # of matrix B C[i][j + N] = B[i][j] # Print the result for i in range(M): for j in range(2 * N): print(C[i][j], end = ' ') print() # Driver codeif __name__=='__main__': A = [ [1, 2], [3, 4] ] B = [ [5, 6], [7, 8] ] # Find the merge of # the 2 matrices mergeMatrix(A, B) # This code is contributed by rutvik_56",
"e": 4068,
"s": 3176,
"text": null
},
{
"code": "// C# implementation to concatenate// two matrices of size N x Musing System; class GFG{ const int M = 2;const int N = 2; // Function to concatenate two// matrices A[][] and B[][]static void mergeMatrix(int[,] A, int[,] B){ // Matrix to store // the result int[,] C = new int[M, 2 * N]; // Merge the two matrices for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { // To store elements // of matrix A C[i, j] = A[i, j]; // To store elements // of matrix B C[i, j + N] = B[i, j]; } } // Print the result for(int i = 0; i < M; i++) { for(int j = 0; j < 2 * N; j++) Console.Write(C[i, j] + \" \"); Console.WriteLine(); }} // Driver codestatic void Main(){ int[,] A = { { 1, 2 }, { 3, 4 } }; int[,] B = { { 5, 6 }, { 7, 8 } }; // Find the merge of // the 2 matrices mergeMatrix(A, B);}} // This code is contributed by divyeshrabadiya07",
"e": 5134,
"s": 4068,
"text": null
},
{
"code": "<script>// Javascript implementation to concatenate// two matrices of size N x MM = 2N = 2 // Function to concatenate two// matrices A[][] and B[][]function mergeMatrix(A,B){ // Matrix to store // the result var C = [[0,0,0,0], [0,0,0,0]] // Merge the two matrices for (var i = 0; i < M; i++) { for (var j = 0; j < N; j++) { // To store elements // of matrix A C[i][j] = A[i][j]; // To store elements // of matrix B C[i][j + N] = B[i][j]; } } // Print the result for (var i = 0; i < M; i++) { for (var j = 0; j < 2 * N; j++) document.write( C[i][j] + \" \"); document.write(\"<br>\"); }} // Driven Codevar A = [ [ 1, 2 ], [ 3, 4 ] ];var B = [ [ 5, 6 ], [ 7, 8 ] ]; // Find the merge of// the 2 matricesmergeMatrix(A, B); // This code is contributed by noob2000.</script>",
"e": 6109,
"s": 5134,
"text": null
},
{
"code": null,
"e": 6126,
"s": 6109,
"text": "1 2 5 6 \n3 4 7 8"
},
{
"code": null,
"e": 6154,
"s": 6128,
"text": "Time Complexity: O(M * N)"
},
{
"code": null,
"e": 6180,
"s": 6154,
"text": "Auxiliary Space: O(M * N)"
},
{
"code": null,
"e": 6194,
"s": 6180,
"text": "GauravRajput1"
},
{
"code": null,
"e": 6204,
"s": 6194,
"text": "rutvik_56"
},
{
"code": null,
"e": 6222,
"s": 6204,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 6238,
"s": 6222,
"text": "subhammahato348"
},
{
"code": null,
"e": 6247,
"s": 6238,
"text": "noob2000"
},
{
"code": null,
"e": 6254,
"s": 6247,
"text": "Arrays"
},
{
"code": null,
"e": 6261,
"s": 6254,
"text": "Matrix"
},
{
"code": null,
"e": 6280,
"s": 6261,
"text": "School Programming"
},
{
"code": null,
"e": 6287,
"s": 6280,
"text": "Arrays"
},
{
"code": null,
"e": 6294,
"s": 6287,
"text": "Matrix"
},
{
"code": null,
"e": 6392,
"s": 6294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6424,
"s": 6392,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 6471,
"s": 6424,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 6496,
"s": 6471,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 6554,
"s": 6496,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 6585,
"s": 6554,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 6620,
"s": 6585,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 6651,
"s": 6620,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 6675,
"s": 6651,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 6697,
"s": 6675,
"text": "The Celebrity Problem"
}
] |
How to Ignore Unknown Properties While Parsing JSON in Java?
|
21 Apr, 2021
There are unknown properties while parsing JSON in java of which the most common problem while parsing JSON in Java using Jackson API is that it fails when JSON contains unknown properties which means the Java class doesn’t have all the field corresponding to all JSON properties. For example, if you are consuming JSON from a REST Web Service and the next day they added a new field into JSON then the code will break because Jackson will throw UnrecognizedPropertyException and stop parsing JSON. This is troublesome and can cause problems in production if one is not aware. The issue could have simply been avoided if one is familiar with Jackson library.
Methods:
There are two ways to ignore Unknown fields are provided by Jackson API. Both approaches will be discussed here and we will also see how to use them and when to use @JsonIgnoreProperties and when to ignore unknown fields in JSON globally at the ObjectMapper level. They are as follows:
At the class level using @JsonIgnoreProperties annotation.At the ObjectMapper level using configure() method.
At the class level using @JsonIgnoreProperties annotation.
At the ObjectMapper level using configure() method.
Method 1: Using @JsonIgnoreProperties
If a Model class is being created to represent the JSON in Java, then the class can be annotated as @JsonIgnoreProperties(ignoreUnknown = true) to ignore any unknown field. It means that if a new field is added later on JSON which represents this model then Jackson will not throw UnrecognizedPropertyException while parsing JSON in Java. This approach not only ignores unknown properties for that model class but also provides more control.
Example:
Java
// Java Program that demonstrates the use of// @JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import com.fasterxml.jackson.databind.ObjectMapper;import java.io.IOException;import java.io.Serializable; /* * Java Program to iterate over JSONObject of json-simple */@JsonIgnoreProperties(ignoreUnknown = true)class Student implements Serializable { private static final long serialVersionUID = -740085147914603262L; private String id; private String name; private String school; private String section; private String major; // getters and setters public String getID() { return id; } public void setID(String id) { this.id = id; } public String getName() { return name; } public void setName(String id) { this.name = name; } public String getSchool() { return school; } public void setSchool(String id) { this.id = id; } public String getSection() { return id; } public void setSection(String id) { this.id = id; } public String getMajor() { return id; } public void setMajor(String id) { this.id = id; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", id='" + id + '\'' + ", school='" + school + '\'' + ", section='" + section + '\'' + ", major='" + major + '\'' + '}'; }} class StudentMain { public static void main(String[] args) throws IOException { // JSON string String jsonString = "{\"name\":\"Krish\",\"id\":\"2019071075\"\"phone\":\"111-111-1111\"}"; System.out.println("Input json string : "); System.out.println(jsonString); System.out.println(""); // convert to object; Student s = toStudent(jsonString); // print information System.out.println("Generated java class:"); System.out.println(s); } private static Student toStudent(String jsonData) throws IOException { // create object mapper instance ObjectMapper om = new ObjectMapper(); // convert JSON string to Java Object return om.readValue(jsonData, Student.class); }}
Output:
Input json string :
{"name":"Krish","phone":"111-111-1111"}
Generated java class:
Employee{name='Krish', id='2019071075', school='null', section='null', major='null'}
Output Explanation:
The approach of annotating classes with @JsonIgnoreProperties allows for finer control over which objects should ignore unknown fields and which should not. On the other hand, a developer may forget to put the annotation to a class, and then the problem could occur.
Method 2: Using Jackson
Configuring ObjectMapper is another way to deal with unknown properties in JSON while parsing so that it does not fail when it encounters an unknown property. This also solves the problem of UnrecognizedPropertyException.
This setting is enabled by calling configure() method as shown below:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Note: Unknown properties will be ignored by this for any JSON it’s going to parse. This option should only be used if you can’t annotate a class with @JsonIgnoreProperties annotation.
Example:
Java
// Java Program that demonstrates the use of ObjectMapper// Configuration import com.fasterxml.jackson.core.JsonParseException;import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.databind.DeserializationContext;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.JsonMappingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.deser.std.StdDeserializer;import java.io.IOException; /* * Java Program to iterate over JSONObject of json-simple */class JacksonTest { // JSON string private static String json = "{\r\n" + "\"name\" : \"Jack Ryan\",\r\n" + "\"id\" : \"2019071075\",\r\n" + "\"school\" : St. Jude's School,\r\n" + "\"section\" : B\r\n" + "}"; public static void main(String args[]) throws IOException { // create object mapper instance ObjectMapper om = new ObjectMapper(); // configure ignore unknown properties om.configure(DeserializationFeature .FAIL_ON_UNKNOWN_PROPERTIES, false); // convert JSON string to Java Object Student effectiveJava = om.readValue(json, Student.class); System.out.println("Input json string"); System.out.println(json); System.out.println("Generated java class: "); System.out.println(effectiveJava); }} class Student { private String name; private String id; private String school; public Student() { // no argument constructor required by Jackson } public Student(String name, String id, String school) { this.name = name; this.id = id; this.school = school; } // getters and setters public String getID() { return id; } public void setID(String id) { this.id = id; } public String getName() { return name; } public void setName(String id) { this.name = name; } public String getSchool() { return school; } public void setSchool(String id) { this.id = id; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", id='" + id + '\'' + ", school='" + school + '\'' + '}'; }}
Output :
Input json string
{
"name" : "Jack Ryan",
"id" : "2019071075",
"school" : "St. Jude's School",
"section" : "B"
}
Generated java class:
Student [name=Jack Ryan, id=2019071075, school=St. Jude's School]
Output Explanation:
The approach of configuring the object mapper in line with a dependency injection framework, ensuring that the same object mapper is used throughout the whole system, will guarantee the extinction of the exception throughout the application, but leaving the developers blindfolded in relation to the evolves that occur in API being consumed.
However, the preferred approach is to ignore unknown properties at the class level using @JsonIgnoreProperties(ignoreUnknown = true) and only do this on the ObjectMapper level if you can’t annotate your class with this annotation i.e. you don’t own the class. It’s also a best practice to annotated your model class with @JsonIgnoreProperties to avoid issues.
Picked
How To
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Permanently Disable Swap in Linux?
How to Import JSON Data into SQL Server?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 687,
"s": 28,
"text": "There are unknown properties while parsing JSON in java of which the most common problem while parsing JSON in Java using Jackson API is that it fails when JSON contains unknown properties which means the Java class doesn’t have all the field corresponding to all JSON properties. For example, if you are consuming JSON from a REST Web Service and the next day they added a new field into JSON then the code will break because Jackson will throw UnrecognizedPropertyException and stop parsing JSON. This is troublesome and can cause problems in production if one is not aware. The issue could have simply been avoided if one is familiar with Jackson library."
},
{
"code": null,
"e": 696,
"s": 687,
"text": "Methods:"
},
{
"code": null,
"e": 982,
"s": 696,
"text": "There are two ways to ignore Unknown fields are provided by Jackson API. Both approaches will be discussed here and we will also see how to use them and when to use @JsonIgnoreProperties and when to ignore unknown fields in JSON globally at the ObjectMapper level. They are as follows:"
},
{
"code": null,
"e": 1092,
"s": 982,
"text": "At the class level using @JsonIgnoreProperties annotation.At the ObjectMapper level using configure() method."
},
{
"code": null,
"e": 1151,
"s": 1092,
"text": "At the class level using @JsonIgnoreProperties annotation."
},
{
"code": null,
"e": 1203,
"s": 1151,
"text": "At the ObjectMapper level using configure() method."
},
{
"code": null,
"e": 1241,
"s": 1203,
"text": "Method 1: Using @JsonIgnoreProperties"
},
{
"code": null,
"e": 1683,
"s": 1241,
"text": "If a Model class is being created to represent the JSON in Java, then the class can be annotated as @JsonIgnoreProperties(ignoreUnknown = true) to ignore any unknown field. It means that if a new field is added later on JSON which represents this model then Jackson will not throw UnrecognizedPropertyException while parsing JSON in Java. This approach not only ignores unknown properties for that model class but also provides more control."
},
{
"code": null,
"e": 1692,
"s": 1683,
"text": "Example:"
},
{
"code": null,
"e": 1697,
"s": 1692,
"text": "Java"
},
{
"code": "// Java Program that demonstrates the use of// @JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import com.fasterxml.jackson.databind.ObjectMapper;import java.io.IOException;import java.io.Serializable; /* * Java Program to iterate over JSONObject of json-simple */@JsonIgnoreProperties(ignoreUnknown = true)class Student implements Serializable { private static final long serialVersionUID = -740085147914603262L; private String id; private String name; private String school; private String section; private String major; // getters and setters public String getID() { return id; } public void setID(String id) { this.id = id; } public String getName() { return name; } public void setName(String id) { this.name = name; } public String getSchool() { return school; } public void setSchool(String id) { this.id = id; } public String getSection() { return id; } public void setSection(String id) { this.id = id; } public String getMajor() { return id; } public void setMajor(String id) { this.id = id; } @Override public String toString() { return \"Student{\" + \"name='\" + name + '\\'' + \", id='\" + id + '\\'' + \", school='\" + school + '\\'' + \", section='\" + section + '\\'' + \", major='\" + major + '\\'' + '}'; }} class StudentMain { public static void main(String[] args) throws IOException { // JSON string String jsonString = \"{\\\"name\\\":\\\"Krish\\\",\\\"id\\\":\\\"2019071075\\\"\\\"phone\\\":\\\"111-111-1111\\\"}\"; System.out.println(\"Input json string : \"); System.out.println(jsonString); System.out.println(\"\"); // convert to object; Student s = toStudent(jsonString); // print information System.out.println(\"Generated java class:\"); System.out.println(s); } private static Student toStudent(String jsonData) throws IOException { // create object mapper instance ObjectMapper om = new ObjectMapper(); // convert JSON string to Java Object return om.readValue(jsonData, Student.class); }}",
"e": 3920,
"s": 1697,
"text": null
},
{
"code": null,
"e": 3928,
"s": 3920,
"text": "Output:"
},
{
"code": null,
"e": 4096,
"s": 3928,
"text": "Input json string :\n{\"name\":\"Krish\",\"phone\":\"111-111-1111\"}\n\nGenerated java class:\nEmployee{name='Krish', id='2019071075', school='null', section='null', major='null'}"
},
{
"code": null,
"e": 4116,
"s": 4096,
"text": "Output Explanation:"
},
{
"code": null,
"e": 4383,
"s": 4116,
"text": "The approach of annotating classes with @JsonIgnoreProperties allows for finer control over which objects should ignore unknown fields and which should not. On the other hand, a developer may forget to put the annotation to a class, and then the problem could occur."
},
{
"code": null,
"e": 4407,
"s": 4383,
"text": "Method 2: Using Jackson"
},
{
"code": null,
"e": 4630,
"s": 4407,
"text": "Configuring ObjectMapper is another way to deal with unknown properties in JSON while parsing so that it does not fail when it encounters an unknown property. This also solves the problem of UnrecognizedPropertyException. "
},
{
"code": null,
"e": 4701,
"s": 4630,
"text": "This setting is enabled by calling configure() method as shown below: "
},
{
"code": null,
"e": 4949,
"s": 4701,
"text": "import com.fasterxml.jackson.databind.DeserializationFeature; \nimport com.fasterxml.jackson.databind.ObjectMapper; \n\nObjectMapper objectMapper = new ObjectMapper(); \nobjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);"
},
{
"code": null,
"e": 5133,
"s": 4949,
"text": "Note: Unknown properties will be ignored by this for any JSON it’s going to parse. This option should only be used if you can’t annotate a class with @JsonIgnoreProperties annotation."
},
{
"code": null,
"e": 5142,
"s": 5133,
"text": "Example:"
},
{
"code": null,
"e": 5147,
"s": 5142,
"text": "Java"
},
{
"code": "// Java Program that demonstrates the use of ObjectMapper// Configuration import com.fasterxml.jackson.core.JsonParseException;import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.databind.DeserializationContext;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.JsonMappingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.deser.std.StdDeserializer;import java.io.IOException; /* * Java Program to iterate over JSONObject of json-simple */class JacksonTest { // JSON string private static String json = \"{\\r\\n\" + \"\\\"name\\\" : \\\"Jack Ryan\\\",\\r\\n\" + \"\\\"id\\\" : \\\"2019071075\\\",\\r\\n\" + \"\\\"school\\\" : St. Jude's School,\\r\\n\" + \"\\\"section\\\" : B\\r\\n\" + \"}\"; public static void main(String args[]) throws IOException { // create object mapper instance ObjectMapper om = new ObjectMapper(); // configure ignore unknown properties om.configure(DeserializationFeature .FAIL_ON_UNKNOWN_PROPERTIES, false); // convert JSON string to Java Object Student effectiveJava = om.readValue(json, Student.class); System.out.println(\"Input json string\"); System.out.println(json); System.out.println(\"Generated java class: \"); System.out.println(effectiveJava); }} class Student { private String name; private String id; private String school; public Student() { // no argument constructor required by Jackson } public Student(String name, String id, String school) { this.name = name; this.id = id; this.school = school; } // getters and setters public String getID() { return id; } public void setID(String id) { this.id = id; } public String getName() { return name; } public void setName(String id) { this.name = name; } public String getSchool() { return school; } public void setSchool(String id) { this.id = id; } @Override public String toString() { return \"Student{\" + \"name='\" + name + '\\'' + \", id='\" + id + '\\'' + \", school='\" + school + '\\'' + '}'; }}",
"e": 7438,
"s": 5147,
"text": null
},
{
"code": null,
"e": 7447,
"s": 7438,
"text": "Output :"
},
{
"code": null,
"e": 7667,
"s": 7447,
"text": "Input json string\n {\n \"name\" : \"Jack Ryan\",\n \"id\" : \"2019071075\",\n \"school\" : \"St. Jude's School\",\n \"section\" : \"B\" \n } \n Generated java class:\n Student [name=Jack Ryan, id=2019071075, school=St. Jude's School]"
},
{
"code": null,
"e": 7687,
"s": 7667,
"text": "Output Explanation:"
},
{
"code": null,
"e": 8029,
"s": 7687,
"text": "The approach of configuring the object mapper in line with a dependency injection framework, ensuring that the same object mapper is used throughout the whole system, will guarantee the extinction of the exception throughout the application, but leaving the developers blindfolded in relation to the evolves that occur in API being consumed."
},
{
"code": null,
"e": 8389,
"s": 8029,
"text": "However, the preferred approach is to ignore unknown properties at the class level using @JsonIgnoreProperties(ignoreUnknown = true) and only do this on the ObjectMapper level if you can’t annotate your class with this annotation i.e. you don’t own the class. It’s also a best practice to annotated your model class with @JsonIgnoreProperties to avoid issues."
},
{
"code": null,
"e": 8396,
"s": 8389,
"text": "Picked"
},
{
"code": null,
"e": 8403,
"s": 8396,
"text": "How To"
},
{
"code": null,
"e": 8408,
"s": 8403,
"text": "Java"
},
{
"code": null,
"e": 8422,
"s": 8408,
"text": "Java Programs"
},
{
"code": null,
"e": 8427,
"s": 8422,
"text": "Java"
},
{
"code": null,
"e": 8525,
"s": 8427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8574,
"s": 8525,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 8613,
"s": 8574,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 8655,
"s": 8613,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 8697,
"s": 8655,
"text": "How to Permanently Disable Swap in Linux?"
},
{
"code": null,
"e": 8738,
"s": 8697,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 8753,
"s": 8738,
"text": "Arrays in Java"
},
{
"code": null,
"e": 8797,
"s": 8753,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 8833,
"s": 8797,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 8884,
"s": 8833,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
lsusb command in Linux with Examples
|
23 Apr, 2019
The lsusb command in Linux is used to display the information about USB buses and the devices connected to them. The properties displayed are speed, BUS, class, type details, etc.
Syntax:
lsusb [ options ]
Example:
Options:
-v : This option is used to display the output in verbose mode and also display detailed information about the devices connected.lsusb -v
lsusb -v
-s : This option is used to display the only device specified by the bus and/or device number.Example:lsusb -s 2:4
Example:
lsusb -s 2:4
-t : This option is used to dump the physical USB device hierarchy as a tree.Example:lsusb -t
Example:
lsusb -t
-D : This option is used to display information about the specified device file. The device file should be like /dev/usb/002/004.Example:lsusb -D /dev/bus/usb/002/004
Example:
lsusb -D /dev/bus/usb/002/004
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Apr, 2019"
},
{
"code": null,
"e": 233,
"s": 53,
"text": "The lsusb command in Linux is used to display the information about USB buses and the devices connected to them. The properties displayed are speed, BUS, class, type details, etc."
},
{
"code": null,
"e": 241,
"s": 233,
"text": "Syntax:"
},
{
"code": null,
"e": 259,
"s": 241,
"text": "lsusb [ options ]"
},
{
"code": null,
"e": 268,
"s": 259,
"text": "Example:"
},
{
"code": null,
"e": 277,
"s": 268,
"text": "Options:"
},
{
"code": null,
"e": 415,
"s": 277,
"text": "-v : This option is used to display the output in verbose mode and also display detailed information about the devices connected.lsusb -v"
},
{
"code": null,
"e": 424,
"s": 415,
"text": "lsusb -v"
},
{
"code": null,
"e": 539,
"s": 424,
"text": "-s : This option is used to display the only device specified by the bus and/or device number.Example:lsusb -s 2:4"
},
{
"code": null,
"e": 548,
"s": 539,
"text": "Example:"
},
{
"code": null,
"e": 561,
"s": 548,
"text": "lsusb -s 2:4"
},
{
"code": null,
"e": 655,
"s": 561,
"text": "-t : This option is used to dump the physical USB device hierarchy as a tree.Example:lsusb -t"
},
{
"code": null,
"e": 664,
"s": 655,
"text": "Example:"
},
{
"code": null,
"e": 673,
"s": 664,
"text": "lsusb -t"
},
{
"code": null,
"e": 840,
"s": 673,
"text": "-D : This option is used to display information about the specified device file. The device file should be like /dev/usb/002/004.Example:lsusb -D /dev/bus/usb/002/004"
},
{
"code": null,
"e": 849,
"s": 840,
"text": "Example:"
},
{
"code": null,
"e": 879,
"s": 849,
"text": "lsusb -D /dev/bus/usb/002/004"
},
{
"code": null,
"e": 893,
"s": 879,
"text": "linux-command"
},
{
"code": null,
"e": 915,
"s": 893,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 926,
"s": 915,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1024,
"s": 926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1059,
"s": 1024,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1085,
"s": 1059,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1122,
"s": 1085,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1151,
"s": 1122,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1188,
"s": 1151,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1225,
"s": 1188,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1265,
"s": 1225,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 1299,
"s": 1265,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1338,
"s": 1299,
"text": "Introduction to Linux Operating System"
}
] |
How to find the age when date of birth is known? Using Java?
|
Java provides a class named Period in the java.time package. This is used to calculate the time period between two given dates as days, months and, years etc.
The between() method of this class accepts two LocalDate objects and finds out the period between the two given dates (number of years, months, and days) and returns as a period object.
From this, you can extract the number of days, months and, years of the period in between using the getDays(), getMonths() and, getYears() respectively.
If you already have the date of birth of a person, to find the age −
Get the date of birth from the user.
Convert it to LocalDate object.
Get the current date (as LocalDate object)
Find the period between these two dates using the between() method as −
Period period = Period.between(dateOfBirth, LocalDate.now());
Get the days, months, years from the Period object using the getDays(), getMonths() and, getYears() methods as −
Get the days, months, years from the Period object using the getDays(), getMonths() and, getYears() methods as −
period.getYears();
period.getMonths();
period.getDays();
Following example reads the name and date of birth from the user, converts it to LocalDate object, gets the current date, finds out the period between these two dates and prints it as days, months and years.
Live Demo
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Scanner;
public class CalculatingAge {
public static Date StringToDate(String dob) throws ParseException{
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
//Parsing the given String to Date object
Date date = formatter.parse(dob);
System.out.println("Date object value: "+date);
return date;
}
public static void main(String args[]) throws ParseException {
//Reading name and date of birth from the user
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your date of birth (dd-MM-yyyy): ");
String dob = sc.next();
//Converting String to Date
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(dob);
//Converting obtained Date object to LocalDate object
Instant instant = date.toInstant();
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
LocalDate givenDate = zone.toLocalDate();
//Calculating the difference between given date to current date.
Period period = Period.between(givenDate, LocalDate.now());
System.out.print("Hello "+name+" your current age is: ");
System.out.print(period.getYears()+" years "+period.getMonths()+" and "+period.getDays()+" days");
}
}
Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-07-1989
Hello Krishna your current age is: 29 years 10 and 5 days
|
[
{
"code": null,
"e": 1346,
"s": 1187,
"text": "Java provides a class named Period in the java.time package. This is used to calculate the time period between two given dates as days, months and, years etc."
},
{
"code": null,
"e": 1532,
"s": 1346,
"text": "The between() method of this class accepts two LocalDate objects and finds out the period between the two given dates (number of years, months, and days) and returns as a period object."
},
{
"code": null,
"e": 1685,
"s": 1532,
"text": "From this, you can extract the number of days, months and, years of the period in between using the getDays(), getMonths() and, getYears() respectively."
},
{
"code": null,
"e": 1754,
"s": 1685,
"text": "If you already have the date of birth of a person, to find the age −"
},
{
"code": null,
"e": 1791,
"s": 1754,
"text": "Get the date of birth from the user."
},
{
"code": null,
"e": 1823,
"s": 1791,
"text": "Convert it to LocalDate object."
},
{
"code": null,
"e": 1866,
"s": 1823,
"text": "Get the current date (as LocalDate object)"
},
{
"code": null,
"e": 1938,
"s": 1866,
"text": "Find the period between these two dates using the between() method as −"
},
{
"code": null,
"e": 2000,
"s": 1938,
"text": "Period period = Period.between(dateOfBirth, LocalDate.now());"
},
{
"code": null,
"e": 2113,
"s": 2000,
"text": "Get the days, months, years from the Period object using the getDays(), getMonths() and, getYears() methods as −"
},
{
"code": null,
"e": 2226,
"s": 2113,
"text": "Get the days, months, years from the Period object using the getDays(), getMonths() and, getYears() methods as −"
},
{
"code": null,
"e": 2283,
"s": 2226,
"text": "period.getYears();\nperiod.getMonths();\nperiod.getDays();"
},
{
"code": null,
"e": 2491,
"s": 2283,
"text": "Following example reads the name and date of birth from the user, converts it to LocalDate object, gets the current date, finds out the period between these two dates and prints it as days, months and years."
},
{
"code": null,
"e": 2502,
"s": 2491,
"text": " Live Demo"
},
{
"code": null,
"e": 4155,
"s": 2502,
"text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.time.Instant;\nimport java.time.LocalDate;\nimport java.time.Period;\nimport java.time.ZoneId;\nimport java.time.ZonedDateTime;\nimport java.util.Date;\nimport java.util.Scanner;\npublic class CalculatingAge {\n public static Date StringToDate(String dob) throws ParseException{\n //Instantiating the SimpleDateFormat class\n SimpleDateFormat formatter = new SimpleDateFormat(\"dd-MM-yyyy\");\n //Parsing the given String to Date object\n Date date = formatter.parse(dob);\n System.out.println(\"Date object value: \"+date);\n return date;\n }\n public static void main(String args[]) throws ParseException {\n //Reading name and date of birth from the user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String name = sc.next();\n System.out.println(\"Enter your date of birth (dd-MM-yyyy): \");\n String dob = sc.next();\n //Converting String to Date\n SimpleDateFormat formatter = new SimpleDateFormat(\"dd-MM-yyyy\");\n Date date = formatter.parse(dob);\n //Converting obtained Date object to LocalDate object\n Instant instant = date.toInstant();\n ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());\n LocalDate givenDate = zone.toLocalDate();\n //Calculating the difference between given date to current date.\n Period period = Period.between(givenDate, LocalDate.now());\n System.out.print(\"Hello \"+name+\" your current age is: \");\n System.out.print(period.getYears()+\" years \"+period.getMonths()+\" and \"+period.getDays()+\" days\");\n }\n}"
},
{
"code": null,
"e": 4288,
"s": 4155,
"text": "Enter your name:\nKrishna\nEnter your date of birth (dd-MM-yyyy):\n26-07-1989\nHello Krishna your current age is: 29 years 10 and 5 days"
}
] |
How to invert key value in JavaScript object ?
|
03 Dec, 2020
JavaScript is a high level, interpreted and dynamically typed client-side scripting language. JavaScript is used to add dynamic features to the static HTML. Everything is an object in JavaScript. Objects in JavaScript can be declared using figure brackets {..} and the objects may comprise certain properties. These properties are basically key-value pairs. The key is an identifier which is used to store and retrieve values. Inverting key-value pairs is tedious using conventional methods. But with the advent of “underscore.js”, inversion of key values can be performed using the inbuilt method _.invert(). In this article, we shall discuss both the methods of inverting key value pairs of JavaScript objects.
First Approach: In this example, we will demonstrate the conventional method of inverting key-value pairs. At first, a student object is created with properties “name”, “age”, “std” and “fees”. An inverse() function is defined which takes the student object as a parameter and loops through each key of the object. A new object retobj is defined which stores the inverted key value pairs.
Code Implementation:
Javascript
function inverse(obj){ var retobj = {}; for(var key in obj){ retobj[obj[key]] = key; } return retobj;} var student = { name : "Jack", age: 18, std : 12, fees : 5000}console.log("Object before inversion");console.log(student);student = inverse(student);console.log("Object after inversion");console.log(student);
Output:
Second Approach: In this example, we use the _.invert() method of “underscore.js” to invert the key value pairs of the object. The method takes the object as a parameter and returns a copy of the object with the keys as values and values as keys. The “student” object is passed to the _.invert() method. The method returns the inverted copy of the “student” object. The program imports the external “underscore.js” library to use inbuilt methods. The results are displayed on the webpage.
Syntax:
_.invert(object)
Code Implementation:
HTML
<!DOCTYPE html><html> <head> <script src="https://cdn.jsdelivr.net/npm/underscore@1.12.0/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var student = { name : "Jack", age: 18, std : 12, fees : 5000 } document.write("<h1>Object before inversion</h1>"); document.write("<br>"); document.write(JSON.stringify(student)); document.write("<br>"); student = JSON.stringify(_.invert(student)); document.write("<h1>Object after inversion</h1>"); document.write("<br>"); document.write(student); </script></body> </html>
Output:
HTML-Misc
JavaScript-Misc
Picked
Technical Scripter 2020
HTML
JavaScript
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Dec, 2020"
},
{
"code": null,
"e": 742,
"s": 28,
"text": "JavaScript is a high level, interpreted and dynamically typed client-side scripting language. JavaScript is used to add dynamic features to the static HTML. Everything is an object in JavaScript. Objects in JavaScript can be declared using figure brackets {..} and the objects may comprise certain properties. These properties are basically key-value pairs. The key is an identifier which is used to store and retrieve values. Inverting key-value pairs is tedious using conventional methods. But with the advent of “underscore.js”, inversion of key values can be performed using the inbuilt method _.invert(). In this article, we shall discuss both the methods of inverting key value pairs of JavaScript objects. "
},
{
"code": null,
"e": 1131,
"s": 742,
"text": "First Approach: In this example, we will demonstrate the conventional method of inverting key-value pairs. At first, a student object is created with properties “name”, “age”, “std” and “fees”. An inverse() function is defined which takes the student object as a parameter and loops through each key of the object. A new object retobj is defined which stores the inverted key value pairs."
},
{
"code": null,
"e": 1152,
"s": 1131,
"text": "Code Implementation:"
},
{
"code": null,
"e": 1163,
"s": 1152,
"text": "Javascript"
},
{
"code": "function inverse(obj){ var retobj = {}; for(var key in obj){ retobj[obj[key]] = key; } return retobj;} var student = { name : \"Jack\", age: 18, std : 12, fees : 5000}console.log(\"Object before inversion\");console.log(student);student = inverse(student);console.log(\"Object after inversion\");console.log(student);",
"e": 1495,
"s": 1163,
"text": null
},
{
"code": null,
"e": 1503,
"s": 1495,
"text": "Output:"
},
{
"code": null,
"e": 1992,
"s": 1503,
"text": "Second Approach: In this example, we use the _.invert() method of “underscore.js” to invert the key value pairs of the object. The method takes the object as a parameter and returns a copy of the object with the keys as values and values as keys. The “student” object is passed to the _.invert() method. The method returns the inverted copy of the “student” object. The program imports the external “underscore.js” library to use inbuilt methods. The results are displayed on the webpage."
},
{
"code": null,
"e": 2000,
"s": 1992,
"text": "Syntax:"
},
{
"code": null,
"e": 2017,
"s": 2000,
"text": "_.invert(object)"
},
{
"code": null,
"e": 2038,
"s": 2017,
"text": "Code Implementation:"
},
{
"code": null,
"e": 2043,
"s": 2038,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://cdn.jsdelivr.net/npm/underscore@1.12.0/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var student = { name : \"Jack\", age: 18, std : 12, fees : 5000 } document.write(\"<h1>Object before inversion</h1>\"); document.write(\"<br>\"); document.write(JSON.stringify(student)); document.write(\"<br>\"); student = JSON.stringify(_.invert(student)); document.write(\"<h1>Object after inversion</h1>\"); document.write(\"<br>\"); document.write(student); </script></body> </html>",
"e": 2722,
"s": 2043,
"text": null
},
{
"code": null,
"e": 2730,
"s": 2722,
"text": "Output:"
},
{
"code": null,
"e": 2740,
"s": 2730,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2756,
"s": 2740,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2763,
"s": 2756,
"text": "Picked"
},
{
"code": null,
"e": 2787,
"s": 2763,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2792,
"s": 2787,
"text": "HTML"
},
{
"code": null,
"e": 2803,
"s": 2792,
"text": "JavaScript"
},
{
"code": null,
"e": 2822,
"s": 2803,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2839,
"s": 2822,
"text": "Web Technologies"
},
{
"code": null,
"e": 2844,
"s": 2839,
"text": "HTML"
}
] |
queue push() and pop() in C++ STL
|
23 Jun, 2022
The queue is a type of container which operates in a First In First Out (FIFO) type of arrangement. Elements are inserted at the back(end) and are deleted from the front of the queue.
push() function is used to insert an element at the back of the queue. This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <queue> header file. The element is added to the queue container and the size of the queue is increased by 1.
Syntax :
queuename.push(value)
Parameters: The value of the element to be inserted is passed as the parameter.
Result: Adds an element of value same as that of the parameter passed at the back of the queue.
Examples:
Input : myqueue
myqueue.push(6);
Output : 6
Input : myqueue
myqueue.push(0);
myqueue.push(1);
Output : 0, 1
Errors and Exceptions:
Shows an error if the value passed doesn’t match the queue type.Shows no exception throw guarantee if the parameter doesn’t throw any exception.
Shows an error if the value passed doesn’t match the queue type.
Shows no exception throw guarantee if the parameter doesn’t throw any exception.
CPP
// CPP program to illustrate// Implementation of push() function #include <iostream>#include <queue>using namespace std; int main(){ // Empty Queue queue<int> myqueue; myqueue.push(0); myqueue.push(1); myqueue.push(2); // Printing content of queue while (!myqueue.empty()) { cout << ' ' << myqueue.front(); myqueue.pop(); }}
0 1 2
Note: Here, output is printed on the basis of FIFO property.
pop() function is used to remove an element from the front of the queue(oldest element in the queue). This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <queue> header file. The element is removed from the queue container and the size of the queue is decreased by 1.Syntax :
queuename.pop()
Parameters: No parameters are passed
Result: Removes the oldest element in the queue or basically the front element.
Examples:
Input : myqueue = 1, 2, 3
myqueue.pop();
Output : 2, 3
Input : myqueue = 3, 2, 1
myqueue.pop();
Output : 2, 1
Errors and Exceptions:
Shows error if a parameter is passed.Shows no exception throw guarantee if the parameter doesn’t throw any exception.
Shows error if a parameter is passed.
Shows no exception throw guarantee if the parameter doesn’t throw any exception.
CPP
// CPP program to illustrate// Implementation of pop() function #include <iostream>#include <queue>using namespace std; int main(){ // Empty Queue queue<int> myqueue; myqueue.push(0); myqueue.push(1); myqueue.push(2); // queue becomes 0, 1, 2 myqueue.pop(); myqueue.pop(); // queue becomes 2 // Printing content of queue while (!myqueue.empty()) { cout << ' ' << myqueue.front(); myqueue.pop(); }}
2
Note: Here, output is printed on the basis of FIFO property.
Given a number of integers, add them to the queue and find the size of the queue without using the size function.
Input : 5, 13, 0, 9, 4
Output: 5
Algorithm: 1. Push the given elements to the queue container one by one. 2. Keep popping the elements of the queue until the queue becomes empty, and increment the counter variable. 3. Print the counter variable.
CPP
// CPP program to illustrate// Application of push() and pop() function #include <iostream>#include <queue>using namespace std; int main(){ // Empty Queue int c = 0; queue<int> myqueue; myqueue.push(5); myqueue.push(13); myqueue.push(0); myqueue.push(9); myqueue.push(4); // queue becomes 5, 13, 0, 9, 4 // Counting number of elements in queue while (!myqueue.empty()) { myqueue.pop(); c++; } cout << c;}
5
Let us see the differences in a tabular form -:
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prabhusatyam44
anshikajain26
mayank007rawa
cpp-containers-library
CPP-Library
cpp-queue
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 238,
"s": 53,
"text": "The queue is a type of container which operates in a First In First Out (FIFO) type of arrangement. Elements are inserted at the back(end) and are deleted from the front of the queue. "
},
{
"code": null,
"e": 517,
"s": 238,
"text": "push() function is used to insert an element at the back of the queue. This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <queue> header file. The element is added to the queue container and the size of the queue is increased by 1."
},
{
"code": null,
"e": 527,
"s": 517,
"text": "Syntax : "
},
{
"code": null,
"e": 549,
"s": 527,
"text": "queuename.push(value)"
},
{
"code": null,
"e": 629,
"s": 549,
"text": "Parameters: The value of the element to be inserted is passed as the parameter."
},
{
"code": null,
"e": 725,
"s": 629,
"text": "Result: Adds an element of value same as that of the parameter passed at the back of the queue."
},
{
"code": null,
"e": 736,
"s": 725,
"text": "Examples: "
},
{
"code": null,
"e": 874,
"s": 736,
"text": "Input : myqueue\n myqueue.push(6);\nOutput : 6\n\nInput : myqueue\n myqueue.push(0);\n myqueue.push(1);\nOutput : 0, 1"
},
{
"code": null,
"e": 898,
"s": 874,
"text": "Errors and Exceptions: "
},
{
"code": null,
"e": 1043,
"s": 898,
"text": "Shows an error if the value passed doesn’t match the queue type.Shows no exception throw guarantee if the parameter doesn’t throw any exception."
},
{
"code": null,
"e": 1108,
"s": 1043,
"text": "Shows an error if the value passed doesn’t match the queue type."
},
{
"code": null,
"e": 1189,
"s": 1108,
"text": "Shows no exception throw guarantee if the parameter doesn’t throw any exception."
},
{
"code": null,
"e": 1193,
"s": 1189,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of push() function #include <iostream>#include <queue>using namespace std; int main(){ // Empty Queue queue<int> myqueue; myqueue.push(0); myqueue.push(1); myqueue.push(2); // Printing content of queue while (!myqueue.empty()) { cout << ' ' << myqueue.front(); myqueue.pop(); }}",
"e": 1557,
"s": 1193,
"text": null
},
{
"code": null,
"e": 1564,
"s": 1557,
"text": " 0 1 2"
},
{
"code": null,
"e": 1625,
"s": 1564,
"text": "Note: Here, output is printed on the basis of FIFO property."
},
{
"code": null,
"e": 1948,
"s": 1625,
"text": "pop() function is used to remove an element from the front of the queue(oldest element in the queue). This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <queue> header file. The element is removed from the queue container and the size of the queue is decreased by 1.Syntax : "
},
{
"code": null,
"e": 1964,
"s": 1948,
"text": "queuename.pop()"
},
{
"code": null,
"e": 2001,
"s": 1964,
"text": "Parameters: No parameters are passed"
},
{
"code": null,
"e": 2081,
"s": 2001,
"text": "Result: Removes the oldest element in the queue or basically the front element."
},
{
"code": null,
"e": 2092,
"s": 2081,
"text": "Examples: "
},
{
"code": null,
"e": 2223,
"s": 2092,
"text": "Input : myqueue = 1, 2, 3\n myqueue.pop();\nOutput : 2, 3\n\nInput : myqueue = 3, 2, 1\n myqueue.pop();\nOutput : 2, 1"
},
{
"code": null,
"e": 2246,
"s": 2223,
"text": "Errors and Exceptions:"
},
{
"code": null,
"e": 2364,
"s": 2246,
"text": "Shows error if a parameter is passed.Shows no exception throw guarantee if the parameter doesn’t throw any exception."
},
{
"code": null,
"e": 2402,
"s": 2364,
"text": "Shows error if a parameter is passed."
},
{
"code": null,
"e": 2483,
"s": 2402,
"text": "Shows no exception throw guarantee if the parameter doesn’t throw any exception."
},
{
"code": null,
"e": 2487,
"s": 2483,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of pop() function #include <iostream>#include <queue>using namespace std; int main(){ // Empty Queue queue<int> myqueue; myqueue.push(0); myqueue.push(1); myqueue.push(2); // queue becomes 0, 1, 2 myqueue.pop(); myqueue.pop(); // queue becomes 2 // Printing content of queue while (!myqueue.empty()) { cout << ' ' << myqueue.front(); myqueue.pop(); }}",
"e": 2937,
"s": 2487,
"text": null
},
{
"code": null,
"e": 2940,
"s": 2937,
"text": " 2"
},
{
"code": null,
"e": 3001,
"s": 2940,
"text": "Note: Here, output is printed on the basis of FIFO property."
},
{
"code": null,
"e": 3116,
"s": 3001,
"text": "Given a number of integers, add them to the queue and find the size of the queue without using the size function. "
},
{
"code": null,
"e": 3149,
"s": 3116,
"text": "Input : 5, 13, 0, 9, 4\nOutput: 5"
},
{
"code": null,
"e": 3362,
"s": 3149,
"text": "Algorithm: 1. Push the given elements to the queue container one by one. 2. Keep popping the elements of the queue until the queue becomes empty, and increment the counter variable. 3. Print the counter variable."
},
{
"code": null,
"e": 3366,
"s": 3362,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Application of push() and pop() function #include <iostream>#include <queue>using namespace std; int main(){ // Empty Queue int c = 0; queue<int> myqueue; myqueue.push(5); myqueue.push(13); myqueue.push(0); myqueue.push(9); myqueue.push(4); // queue becomes 5, 13, 0, 9, 4 // Counting number of elements in queue while (!myqueue.empty()) { myqueue.pop(); c++; } cout << c;}",
"e": 3826,
"s": 3366,
"text": null
},
{
"code": null,
"e": 3828,
"s": 3826,
"text": "5"
},
{
"code": null,
"e": 3877,
"s": 3828,
"text": "Let us see the differences in a tabular form -: "
},
{
"code": null,
"e": 4003,
"s": 3877,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4018,
"s": 4003,
"text": "prabhusatyam44"
},
{
"code": null,
"e": 4032,
"s": 4018,
"text": "anshikajain26"
},
{
"code": null,
"e": 4046,
"s": 4032,
"text": "mayank007rawa"
},
{
"code": null,
"e": 4069,
"s": 4046,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 4081,
"s": 4069,
"text": "CPP-Library"
},
{
"code": null,
"e": 4091,
"s": 4081,
"text": "cpp-queue"
},
{
"code": null,
"e": 4095,
"s": 4091,
"text": "STL"
},
{
"code": null,
"e": 4099,
"s": 4095,
"text": "C++"
},
{
"code": null,
"e": 4103,
"s": 4099,
"text": "STL"
},
{
"code": null,
"e": 4107,
"s": 4103,
"text": "CPP"
}
] |
Sum of absolute differences of all pairs in a given array
|
05 Jul, 2022
Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array.
Examples:
Input : arr[] = {1, 2, 3, 4}
Output: 10
Sum of |2-1| + |3-1| + |4-1| +
|3-2| + |4-2| + |4-3| = 10
Input : arr[] = {1, 8, 9, 15, 16}
Output: 74
Input : arr[] = {1, 2, 3, 4, 5, 7, 9, 11, 14}
Output: 188
A simple solution for this problem is to one by one look for each pair take their difference and sum up them together. The time complexity for this approach is O(n2).
An efficient solution for this problem needs a simple observation. Since array is sorted and elements are distinct when we take sum of absolute difference of pairs each element in the i’th position is added ‘i’ times and subtracted ‘n-1-i’ times.
For example in {1,2,3,4} element at index 2 is arr[2] = 3 so all pairs having 3 as one element will be (1,3), (2,3) and (3,4), now when we take summation of absolute difference of pairs, then for all pairs in which 3 is present as one element summation will be = (3-1)+(3-2)+(4-3). We can see that 3 is added i = 2 times and subtracted n-1-i = (4-1-2) = 1 times.
The generalized expression for each element will be sum = sum + (i*a[i]) – (n-1-i)*a[i].
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of absolute differences// in all pairs in a sorted array of distinct numbers#include<bits/stdc++.h>using namespace std; // Function to calculate sum of absolute difference// of all pairs in array// arr[] --> array of elementsint sumPairs(int arr[],int n){ // final result int sum = 0; for (int i=n-1; i>=0; i--) sum += i*arr[i] - (n-1-i)*arr[i]; return sum;} // Driver program to run the caseint main(){ int arr[] = {1, 8, 9, 15, 16}; int n = sizeof(arr)/sizeof(arr[0]); cout << sumPairs(arr, n); return 0;} // This code is contributed by Sania Kumari Gupta
// C program to find sum of absolute differences// in all pairs in a sorted array of distinct numbers#include <stdio.h> // Function to calculate sum of absolute difference// of all pairs in array// arr[] --> array of elementsint sumPairs(int arr[], int n){ // final result int sum = 0; for (int i = n - 1; i >= 0; i--) sum += i * arr[i] - (n - 1 - i) * arr[i]; return sum;} // Driver program to run the caseint main(){ int arr[] = { 1, 8, 9, 15, 16 }; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", sumPairs(arr, n)); return 0;} // This code is contributed by Sania Kumari Gupta
// Java program to find sum of absolute differences in all// pairs in a sorted array of distinct numbersclass GFG { // Function to calculate sum of absolute // difference of all pairs in array // arr[] --> array of elements static int sumPairs(int arr[], int n) { // final result int sum = 0; for (int i = n - 1; i >= 0; i--) sum += i * arr[i] - (n - 1 - i) * arr[i]; return sum; } // Driver program public static void main(String arg[]) { int arr[] = { 1, 8, 9, 15, 16 }; int n = arr.length; System.out.print(sumPairs(arr, n)); }} // This code is contributed by Sania Kumari Gupta
# Python3 program to find sum of# absolute differences in all pairs# in a sorted array of distinct numbers # Function to calculate sum of absolute# difference of all pairs in array# arr[] --> array of elementsdef sumPairs(arr, n): # final result sum = 0 for i in range(n - 1, -1, -1): sum += i*arr[i] - (n-1-i) * arr[i] return sum # Driver programarr = [1, 8, 9, 15, 16]n = len(arr)print(sumPairs(arr, n)) # This code is contributed by Anant Agarwal.
// C# program to find sum of absolute// differences in all pairs in a sorted// array of distinct numbersusing System;class GFG { // Function to calculate sum of absolute // difference of all pairs in array // arr[] --> array of elements static int sumPairs(int []arr, int n) { // final result int sum = 0; for (int i = n - 1; i >= 0; i--) sum += i * arr[i] - (n - 1 - i) * arr[i]; return sum; } // Driver program public static void Main() { int []arr = { 1, 8, 9, 15, 16 }; int n = arr.Length; Console.Write(sumPairs(arr, n)); }} // This code is contributed by nitin mittal.
<?php // PHP program to find sum of absolute differences// in all pairs in a sorted array of distinct numbers // Function to calculate sum of absolute difference// of all pairs in array// arr[] --> array of elementsfunction sumPairs($arr,$n){ // final result $sum = 0; for ($i=$n-1; $i>=0; $i--) $sum = $sum + $i*$arr[$i] - ($n-1-$i)*$arr[$i]; return $sum;} // Driver program to run the case$arr = array(1, 8, 9, 15, 16); $n = sizeof($arr)/sizeof($arr[0]); echo sumPairs($arr, $n);?>
<script> // JavaScript program to find// sum of absolute differences// in all pairs in a sorted array// of distinct numbers // Function to calculate sum of absolute difference// of all pairs in array// arr[] --> array of elementsfunction sumPairs( arr, n){ // final result let sum = 0; for (let i=n-1; i>=0; i--) sum += i*arr[i] - (n-1-i)*arr[i]; return sum;} // Driver program to run the caselet arr = [ 1, 8, 9, 15, 16 ];let n = arr.length;document.write(sumPairs(arr, n)); </script>
74
Time Complexity: O(n) Auxiliary space: O(1)
What if array is not sorted? The efficient solution is also better for the cases where array is not sorted. We can sort the array first in O(n Log n) time and then find the required value in O(n). So overall time complexity is O(n Log n) which is still better than O(n2)
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
nitin mittal
ankita_saini
rohan07
sweetyty
krisania804
hardikkoriintern
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures
Python | Using 2D arrays/lists the right way
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 186,
"s": 52,
"text": "Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array."
},
{
"code": null,
"e": 197,
"s": 186,
"text": "Examples: "
},
{
"code": null,
"e": 407,
"s": 197,
"text": "Input : arr[] = {1, 2, 3, 4}\nOutput: 10\nSum of |2-1| + |3-1| + |4-1| +\n |3-2| + |4-2| + |4-3| = 10\n\nInput : arr[] = {1, 8, 9, 15, 16}\nOutput: 74\n\nInput : arr[] = {1, 2, 3, 4, 5, 7, 9, 11, 14}\nOutput: 188"
},
{
"code": null,
"e": 574,
"s": 407,
"text": "A simple solution for this problem is to one by one look for each pair take their difference and sum up them together. The time complexity for this approach is O(n2)."
},
{
"code": null,
"e": 822,
"s": 574,
"text": "An efficient solution for this problem needs a simple observation. Since array is sorted and elements are distinct when we take sum of absolute difference of pairs each element in the i’th position is added ‘i’ times and subtracted ‘n-1-i’ times. "
},
{
"code": null,
"e": 1186,
"s": 822,
"text": "For example in {1,2,3,4} element at index 2 is arr[2] = 3 so all pairs having 3 as one element will be (1,3), (2,3) and (3,4), now when we take summation of absolute difference of pairs, then for all pairs in which 3 is present as one element summation will be = (3-1)+(3-2)+(4-3). We can see that 3 is added i = 2 times and subtracted n-1-i = (4-1-2) = 1 times. "
},
{
"code": null,
"e": 1276,
"s": 1186,
"text": "The generalized expression for each element will be sum = sum + (i*a[i]) – (n-1-i)*a[i]. "
},
{
"code": null,
"e": 1280,
"s": 1276,
"text": "C++"
},
{
"code": null,
"e": 1282,
"s": 1280,
"text": "C"
},
{
"code": null,
"e": 1287,
"s": 1282,
"text": "Java"
},
{
"code": null,
"e": 1295,
"s": 1287,
"text": "Python3"
},
{
"code": null,
"e": 1298,
"s": 1295,
"text": "C#"
},
{
"code": null,
"e": 1302,
"s": 1298,
"text": "PHP"
},
{
"code": null,
"e": 1313,
"s": 1302,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of absolute differences// in all pairs in a sorted array of distinct numbers#include<bits/stdc++.h>using namespace std; // Function to calculate sum of absolute difference// of all pairs in array// arr[] --> array of elementsint sumPairs(int arr[],int n){ // final result int sum = 0; for (int i=n-1; i>=0; i--) sum += i*arr[i] - (n-1-i)*arr[i]; return sum;} // Driver program to run the caseint main(){ int arr[] = {1, 8, 9, 15, 16}; int n = sizeof(arr)/sizeof(arr[0]); cout << sumPairs(arr, n); return 0;} // This code is contributed by Sania Kumari Gupta",
"e": 1930,
"s": 1313,
"text": null
},
{
"code": "// C program to find sum of absolute differences// in all pairs in a sorted array of distinct numbers#include <stdio.h> // Function to calculate sum of absolute difference// of all pairs in array// arr[] --> array of elementsint sumPairs(int arr[], int n){ // final result int sum = 0; for (int i = n - 1; i >= 0; i--) sum += i * arr[i] - (n - 1 - i) * arr[i]; return sum;} // Driver program to run the caseint main(){ int arr[] = { 1, 8, 9, 15, 16 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", sumPairs(arr, n)); return 0;} // This code is contributed by Sania Kumari Gupta",
"e": 2545,
"s": 1930,
"text": null
},
{
"code": "// Java program to find sum of absolute differences in all// pairs in a sorted array of distinct numbersclass GFG { // Function to calculate sum of absolute // difference of all pairs in array // arr[] --> array of elements static int sumPairs(int arr[], int n) { // final result int sum = 0; for (int i = n - 1; i >= 0; i--) sum += i * arr[i] - (n - 1 - i) * arr[i]; return sum; } // Driver program public static void main(String arg[]) { int arr[] = { 1, 8, 9, 15, 16 }; int n = arr.length; System.out.print(sumPairs(arr, n)); }} // This code is contributed by Sania Kumari Gupta",
"e": 3219,
"s": 2545,
"text": null
},
{
"code": "# Python3 program to find sum of# absolute differences in all pairs# in a sorted array of distinct numbers # Function to calculate sum of absolute# difference of all pairs in array# arr[] --> array of elementsdef sumPairs(arr, n): # final result sum = 0 for i in range(n - 1, -1, -1): sum += i*arr[i] - (n-1-i) * arr[i] return sum # Driver programarr = [1, 8, 9, 15, 16]n = len(arr)print(sumPairs(arr, n)) # This code is contributed by Anant Agarwal.",
"e": 3690,
"s": 3219,
"text": null
},
{
"code": "// C# program to find sum of absolute// differences in all pairs in a sorted// array of distinct numbersusing System;class GFG { // Function to calculate sum of absolute // difference of all pairs in array // arr[] --> array of elements static int sumPairs(int []arr, int n) { // final result int sum = 0; for (int i = n - 1; i >= 0; i--) sum += i * arr[i] - (n - 1 - i) * arr[i]; return sum; } // Driver program public static void Main() { int []arr = { 1, 8, 9, 15, 16 }; int n = arr.Length; Console.Write(sumPairs(arr, n)); }} // This code is contributed by nitin mittal.",
"e": 4435,
"s": 3690,
"text": null
},
{
"code": "<?php // PHP program to find sum of absolute differences// in all pairs in a sorted array of distinct numbers // Function to calculate sum of absolute difference// of all pairs in array// arr[] --> array of elementsfunction sumPairs($arr,$n){ // final result $sum = 0; for ($i=$n-1; $i>=0; $i--) $sum = $sum + $i*$arr[$i] - ($n-1-$i)*$arr[$i]; return $sum;} // Driver program to run the case$arr = array(1, 8, 9, 15, 16); $n = sizeof($arr)/sizeof($arr[0]); echo sumPairs($arr, $n);?>",
"e": 4945,
"s": 4435,
"text": null
},
{
"code": "<script> // JavaScript program to find// sum of absolute differences// in all pairs in a sorted array// of distinct numbers // Function to calculate sum of absolute difference// of all pairs in array// arr[] --> array of elementsfunction sumPairs( arr, n){ // final result let sum = 0; for (let i=n-1; i>=0; i--) sum += i*arr[i] - (n-1-i)*arr[i]; return sum;} // Driver program to run the caselet arr = [ 1, 8, 9, 15, 16 ];let n = arr.length;document.write(sumPairs(arr, n)); </script>",
"e": 5451,
"s": 4945,
"text": null
},
{
"code": null,
"e": 5454,
"s": 5451,
"text": "74"
},
{
"code": null,
"e": 5498,
"s": 5454,
"text": "Time Complexity: O(n) Auxiliary space: O(1)"
},
{
"code": null,
"e": 5769,
"s": 5498,
"text": "What if array is not sorted? The efficient solution is also better for the cases where array is not sorted. We can sort the array first in O(n Log n) time and then find the required value in O(n). So overall time complexity is O(n Log n) which is still better than O(n2)"
},
{
"code": null,
"e": 6079,
"s": 5769,
"text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 6092,
"s": 6079,
"text": "nitin mittal"
},
{
"code": null,
"e": 6105,
"s": 6092,
"text": "ankita_saini"
},
{
"code": null,
"e": 6113,
"s": 6105,
"text": "rohan07"
},
{
"code": null,
"e": 6122,
"s": 6113,
"text": "sweetyty"
},
{
"code": null,
"e": 6134,
"s": 6122,
"text": "krisania804"
},
{
"code": null,
"e": 6151,
"s": 6134,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 6158,
"s": 6151,
"text": "Arrays"
},
{
"code": null,
"e": 6165,
"s": 6158,
"text": "Arrays"
},
{
"code": null,
"e": 6263,
"s": 6165,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6331,
"s": 6263,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 6375,
"s": 6331,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 6407,
"s": 6375,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6421,
"s": 6407,
"text": "Linear Search"
},
{
"code": null,
"e": 6506,
"s": 6421,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 6529,
"s": 6506,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 6585,
"s": 6529,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 6612,
"s": 6585,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 6644,
"s": 6612,
"text": "Introduction to Data Structures"
}
] |
Map entrySet() method in Java with Examples
|
20 Jan, 2022
The java.util.Map.entrySet() method in Java is used to create a set out of the same elements contained in the map. It basically returns a set view of the map or we can create a new set and store the map elements into them.
Syntax:
map.entrySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having same elements as the hash map.
Below programs illustrate the java.util.Map.entrySet() Method:
Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the entrySet() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, "Geeks"); map.put(15, "4"); map.put(20, "Geeks"); map.put(25, "Welcomes"); map.put(30, "You"); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Using entrySet() to get the set view System.out.println("The set is: " + map.entrySet()); }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The set is: [20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4]
Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the entrySet() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put("Geeks", 10); map.put("4", 15); map.put("Geeks", 20); map.put("Welcomes", 25); map.put("You", 30); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Using entrySet() to get the set view System.out.println("The set is: " + map.entrySet()); }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The set is: [4=15, Geeks=20, You=30, Welcomes=25]
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#entrySet()
simmytarika5
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
Introduction to Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 276,
"s": 53,
"text": "The java.util.Map.entrySet() method in Java is used to create a set out of the same elements contained in the map. It basically returns a set view of the map or we can create a new set and store the map elements into them."
},
{
"code": null,
"e": 284,
"s": 276,
"text": "Syntax:"
},
{
"code": null,
"e": 299,
"s": 284,
"text": "map.entrySet()"
},
{
"code": null,
"e": 351,
"s": 299,
"text": "Parameters: The method does not take any parameter."
},
{
"code": null,
"e": 428,
"s": 351,
"text": "Return Value: The method returns a set having same elements as the hash map."
},
{
"code": null,
"e": 491,
"s": 428,
"text": "Below programs illustrate the java.util.Map.entrySet() Method:"
},
{
"code": null,
"e": 541,
"s": 491,
"text": "Program 1: Mapping String Values to Integer Keys."
},
{
"code": "// Java code to illustrate the entrySet() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, \"Geeks\"); map.put(15, \"4\"); map.put(20, \"Geeks\"); map.put(25, \"Welcomes\"); map.put(30, \"You\"); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Using entrySet() to get the set view System.out.println(\"The set is: \" + map.entrySet()); }}",
"e": 1174,
"s": 541,
"text": null
},
{
"code": null,
"e": 1305,
"s": 1174,
"text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nThe set is: [20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4]\n"
},
{
"code": null,
"e": 1355,
"s": 1305,
"text": "Program 2: Mapping Integer Values to String Keys."
},
{
"code": "// Java code to illustrate the entrySet() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put(\"Geeks\", 10); map.put(\"4\", 15); map.put(\"Geeks\", 20); map.put(\"Welcomes\", 25); map.put(\"You\", 30); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Using entrySet() to get the set view System.out.println(\"The set is: \" + map.entrySet()); }}",
"e": 1986,
"s": 1355,
"text": null
},
{
"code": null,
"e": 2097,
"s": 1986,
"text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nThe set is: [4=15, Geeks=20, You=30, Welcomes=25]\n"
},
{
"code": null,
"e": 2221,
"s": 2097,
"text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types."
},
{
"code": null,
"e": 2304,
"s": 2221,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#entrySet()"
},
{
"code": null,
"e": 2317,
"s": 2304,
"text": "simmytarika5"
},
{
"code": null,
"e": 2334,
"s": 2317,
"text": "Java-Collections"
},
{
"code": null,
"e": 2349,
"s": 2334,
"text": "Java-Functions"
},
{
"code": null,
"e": 2358,
"s": 2349,
"text": "java-map"
},
{
"code": null,
"e": 2363,
"s": 2358,
"text": "Java"
},
{
"code": null,
"e": 2368,
"s": 2363,
"text": "Java"
},
{
"code": null,
"e": 2385,
"s": 2368,
"text": "Java-Collections"
},
{
"code": null,
"e": 2483,
"s": 2385,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2502,
"s": 2483,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2517,
"s": 2502,
"text": "Stream In Java"
},
{
"code": null,
"e": 2535,
"s": 2517,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2555,
"s": 2535,
"text": "Collections in Java"
},
{
"code": null,
"e": 2579,
"s": 2555,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2611,
"s": 2579,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2631,
"s": 2611,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 2663,
"s": 2631,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 2691,
"s": 2663,
"text": "Initializing a List in Java"
}
] |
Python eval()
|
The eval() method parses the expression passed on to this method and runs the expression within the program. In other words, it interprets a string as code inside a python program.
The Syntax for eval is as below −
eval(expression, globals=None, locals=None)
Where
Expression − It is the python expression passed onto the method.
Expression − It is the python expression passed onto the method.
globals − A dictionary of available global methods and variables.
globals − A dictionary of available global methods and variables.
locals − A dictionary of available local methods and variables.
locals − A dictionary of available local methods and variables.
In the below example we allow the user to cerate an expression and run a python program to evaluate that expression. So it helps in create dynamic code.
Live Demo
# expression to be evaluated
user_expr = raw_input("Enter an expression in terms of variable a):")
#nter the value of variable
a = int(raw_input("Enter the value of a:"))
# evaluate the expression
result = eval(user_expr)
# printing evaluated result
print("Result = {}".format(result))
Running the above code gives us the following result −
Enter an expression in terms of variable a):a*(a-3)+a^2
Enter the value of a:7
Result = 33
For programs involving web applications or desktop programs there is a chance that the use of such eval() method will create security vulnerabilities because the use running the program may supply expressions which are system commands to delete files or get sensitive data out of the system. As a step to prevent this we can restrict the eval() function to some selected functions or variables.
The steps to prevent these vulnerabilities are as below −
In this way it will be evaluated only in the current scope and not find other variables outside this scope.
On omitting the local variable, all the variables are scoped as global variable. Next we pass on an empty dictionary as the global variable and that allows only the built-in variables to be available even when we have imported other libraries to the program.
Live Demo
from time import *
print(eval('dir()', {}))
Running the above code gives us the following result −
['__builtins__']
Next we can also allow only certain methods from the imported library to be available to the program.
Live Demo
from time import *
print(eval('dir()', {'sleeptime': sleep, 'Localtime': localtime}))
Running the above code gives us the following result −
['Localtime', '__builtins__', 'sleeptime']
We can also restrict the availability of function in both local and global scope by allowing none of the built ins and only a few from the locally imported libraries. In the below example we have made only the gmtime method available from time library.
Live Demo
from time import *
a = 1445945763
print(eval('gmtime(a)', {'__builtins__': None}, {'a': a, 'gmtime': gmtime}))
Running the above code gives us the following result −
time.struct_time(tm_year=2015, tm_mon=10, tm_mday=27, tm_hour=11, tm_min=36, tm_sec=3, tm_wday=1, tm_yday=300, tm_isdst=0)
|
[
{
"code": null,
"e": 1368,
"s": 1187,
"text": "The eval() method parses the expression passed on to this method and runs the expression within the program. In other words, it interprets a string as code inside a python program."
},
{
"code": null,
"e": 1402,
"s": 1368,
"text": "The Syntax for eval is as below −"
},
{
"code": null,
"e": 1446,
"s": 1402,
"text": "eval(expression, globals=None, locals=None)"
},
{
"code": null,
"e": 1452,
"s": 1446,
"text": "Where"
},
{
"code": null,
"e": 1517,
"s": 1452,
"text": "Expression − It is the python expression passed onto the method."
},
{
"code": null,
"e": 1582,
"s": 1517,
"text": "Expression − It is the python expression passed onto the method."
},
{
"code": null,
"e": 1648,
"s": 1582,
"text": "globals − A dictionary of available global methods and variables."
},
{
"code": null,
"e": 1714,
"s": 1648,
"text": "globals − A dictionary of available global methods and variables."
},
{
"code": null,
"e": 1778,
"s": 1714,
"text": "locals − A dictionary of available local methods and variables."
},
{
"code": null,
"e": 1842,
"s": 1778,
"text": "locals − A dictionary of available local methods and variables."
},
{
"code": null,
"e": 1995,
"s": 1842,
"text": "In the below example we allow the user to cerate an expression and run a python program to evaluate that expression. So it helps in create dynamic code."
},
{
"code": null,
"e": 2006,
"s": 1995,
"text": " Live Demo"
},
{
"code": null,
"e": 2292,
"s": 2006,
"text": "# expression to be evaluated\nuser_expr = raw_input(\"Enter an expression in terms of variable a):\")\n#nter the value of variable\na = int(raw_input(\"Enter the value of a:\"))\n# evaluate the expression\nresult = eval(user_expr)\n# printing evaluated result\nprint(\"Result = {}\".format(result))"
},
{
"code": null,
"e": 2347,
"s": 2292,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2438,
"s": 2347,
"text": "Enter an expression in terms of variable a):a*(a-3)+a^2\nEnter the value of a:7\nResult = 33"
},
{
"code": null,
"e": 2833,
"s": 2438,
"text": "For programs involving web applications or desktop programs there is a chance that the use of such eval() method will create security vulnerabilities because the use running the program may supply expressions which are system commands to delete files or get sensitive data out of the system. As a step to prevent this we can restrict the eval() function to some selected functions or variables."
},
{
"code": null,
"e": 2891,
"s": 2833,
"text": "The steps to prevent these vulnerabilities are as below −"
},
{
"code": null,
"e": 2999,
"s": 2891,
"text": "In this way it will be evaluated only in the current scope and not find other variables outside this scope."
},
{
"code": null,
"e": 3258,
"s": 2999,
"text": "On omitting the local variable, all the variables are scoped as global variable. Next we pass on an empty dictionary as the global variable and that allows only the built-in variables to be available even when we have imported other libraries to the program."
},
{
"code": null,
"e": 3269,
"s": 3258,
"text": " Live Demo"
},
{
"code": null,
"e": 3313,
"s": 3269,
"text": "from time import *\nprint(eval('dir()', {}))"
},
{
"code": null,
"e": 3368,
"s": 3313,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3385,
"s": 3368,
"text": "['__builtins__']"
},
{
"code": null,
"e": 3487,
"s": 3385,
"text": "Next we can also allow only certain methods from the imported library to be available to the program."
},
{
"code": null,
"e": 3498,
"s": 3487,
"text": " Live Demo"
},
{
"code": null,
"e": 3584,
"s": 3498,
"text": "from time import *\nprint(eval('dir()', {'sleeptime': sleep, 'Localtime': localtime}))"
},
{
"code": null,
"e": 3639,
"s": 3584,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3682,
"s": 3639,
"text": "['Localtime', '__builtins__', 'sleeptime']"
},
{
"code": null,
"e": 3935,
"s": 3682,
"text": "We can also restrict the availability of function in both local and global scope by allowing none of the built ins and only a few from the locally imported libraries. In the below example we have made only the gmtime method available from time library."
},
{
"code": null,
"e": 3946,
"s": 3935,
"text": " Live Demo"
},
{
"code": null,
"e": 4057,
"s": 3946,
"text": "from time import *\na = 1445945763\nprint(eval('gmtime(a)', {'__builtins__': None}, {'a': a, 'gmtime': gmtime}))"
},
{
"code": null,
"e": 4112,
"s": 4057,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 4235,
"s": 4112,
"text": "time.struct_time(tm_year=2015, tm_mon=10, tm_mday=27, tm_hour=11, tm_min=36, tm_sec=3, tm_wday=1, tm_yday=300, tm_isdst=0)"
}
] |
Bottom Up Testing
|
Each component at lower hierarchy is tested individually and then the components that rely upon these components are tested.
The order of Integration by Bottom-down approach will be:
4,2
5,2
6,3
7,3
2,1
3,1
+ Firstly, Test 4,5,6,7 individually using drivers.
+ Test 2 such that it calls 4 and 5 separately. If an error occurs we know that the problem is in one of the modules.
+ Test 1 such that it calls 3 and If an error occurs we know that the problem is in 3 or in the interface between 1 and 3
Though Top level components are the most important, yet tested last using this strategy. In Bottom-up approach, the Components 2 and 3 are replaced by drivers while testing components 4,5,6,7. They are generally more complex than stubs.
|
[
{
"code": null,
"e": 6004,
"s": 5879,
"text": "Each component at lower hierarchy is tested individually and then the components that rely upon these components are tested."
},
{
"code": null,
"e": 6062,
"s": 6004,
"text": "The order of Integration by Bottom-down approach will be:"
},
{
"code": null,
"e": 6087,
"s": 6062,
"text": "4,2\n5,2\n6,3\n7,3\n2,1\n3,1\n"
},
{
"code": null,
"e": 6379,
"s": 6087,
"text": "+ Firstly, Test 4,5,6,7 individually using drivers.\n+ Test 2 such that it calls 4 and 5 separately. If an error occurs we know that the problem is in one of the modules.\n+ Test 1 such that it calls 3 and If an error occurs we know that the problem is in 3 or in the interface between 1 and 3"
}
] |
What does the if __name__ == "__main__": do in Python?
|
When the Python interpreter reads a source file, it executes all of the code found in it.
Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.
One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
For example, if you have 2 files one.py and two.py with the following code:
one.py:
def func():
print("func() in one.py")
print("Root of one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported")
Two.py:
import one
print("Root of two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported")
Now if you run,
$ python one.py
You will get the output:
Root of one.py
one.py is being run directly
But if you run,
$ python two.py
You will get the output:
Root of in one.py
one.py is being imported
Root of in two.py
func() in one.py
two.py is being run directly
|
[
{
"code": null,
"e": 1277,
"s": 1187,
"text": "When the Python interpreter reads a source file, it executes all of the code found in it."
},
{
"code": null,
"e": 1606,
"s": 1277,
"text": "Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value \"__main__\". If this file is being imported from another module, __name__ will be set to the module's name."
},
{
"code": null,
"e": 1996,
"s": 1606,
"text": "One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves."
},
{
"code": null,
"e": 2072,
"s": 1996,
"text": "For example, if you have 2 files one.py and two.py with the following code:"
},
{
"code": null,
"e": 2080,
"s": 2072,
"text": "one.py:"
},
{
"code": null,
"e": 2259,
"s": 2080,
"text": "def func():\n print(\"func() in one.py\")\nprint(\"Root of one.py\")\nif __name__ == \"__main__\":\n print(\"one.py is being run directly\")\nelse:\n print(\"one.py is being imported\")"
},
{
"code": null,
"e": 2267,
"s": 2259,
"text": "Two.py:"
},
{
"code": null,
"e": 2426,
"s": 2267,
"text": "import one\nprint(\"Root of two.py\")\none.func()\nif __name__ == \"__main__\":\n print(\"two.py is being run directly\")\nelse:\n print(\"two.py is being imported\")"
},
{
"code": null,
"e": 2442,
"s": 2426,
"text": "Now if you run,"
},
{
"code": null,
"e": 2458,
"s": 2442,
"text": "$ python one.py"
},
{
"code": null,
"e": 2483,
"s": 2458,
"text": "You will get the output:"
},
{
"code": null,
"e": 2527,
"s": 2483,
"text": "Root of one.py\none.py is being run directly"
},
{
"code": null,
"e": 2543,
"s": 2527,
"text": "But if you run,"
},
{
"code": null,
"e": 2559,
"s": 2543,
"text": "$ python two.py"
},
{
"code": null,
"e": 2584,
"s": 2559,
"text": "You will get the output:"
},
{
"code": null,
"e": 2691,
"s": 2584,
"text": "Root of in one.py\none.py is being imported\nRoot of in two.py\nfunc() in one.py\ntwo.py is being run directly"
}
] |
Rotate a Matrix by 180 degree
|
01 May, 2021
Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space.
Examples :
Input : 1 2 3
4 5 6
7 8 9
Output : 9 8 7
6 5 4
3 2 1
Input : 1 2 3 4
5 6 7 8
9 0 1 2
3 4 5 6
Output : 6 5 4 3
2 1 0 9
8 7 6 5
4 3 2 1
Method: 1 (Only prints rotated matrix) The solution of this problem is that to rotate a matrix by 180 degrees we can easily follow that step
Matrix = a00 a01 a02
a10 a11 a12
a20 a21 a22
when we rotate it by 90 degree
then matrix is
Matrix = a02 a12 a22
a01 a11 a21
a00 a10 a20
when we rotate it by again 90
degree then matrix is
Matrix = a22 a21 a20
a12 a11 a10
a02 a01 a00
From the above illustration, we get that simply to rotate the matrix by 180 degrees then we will have to print the given matrix in a reverse manner.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to rotate a matrix by 180 degrees#include <bits/stdc++.h>#define N 3using namespace std; // Function to Rotate the matrix by 180 degreevoid rotateMatrix(int mat[][N]){ // Simply print from last cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) printf("%d ", mat[i][j]); printf("\n"); }} // Driven codeint main(){ int mat[N][N] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); return 0;}
// Java program to rotate a// matrix by 180 degreesimport java.util.*; class GFG { static int N = 3; // Function to Rotate the // matrix by 180 degree static void rotateMatrix(int mat[][]) { // Simply print from last // cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) System.out.print(mat[i][j] + " "); System.out.println(); } } // Driver Code public static void main(String[] args) { int[][] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); }} // This code is contributed by ChitraNayal
# Python3 program to# rotate a matrix by# 180 degreesN = 3; # Function to Rotate# the matrix by 180 degreedef rotateMatrix(mat): # Simply print from # last cell to first cell. i = N - 1; while(i >= 0): j = N - 1; while(j >= 0): print(mat[i][j], end = " "); j = j - 1; print(); i = i - 1; # Driven codemat = [[1, 2, 3], [ 4, 5, 6 ], [ 7, 8, 9 ]];rotateMatrix(mat); # This code is contributed# by mits
// C# program to rotate a// matrix by 180 degreesusing System; class GFG { static int N = 3; // Function to Rotate the // matrix by 180 degree static void rotateMatrix(int[, ] mat) { // Simply print from last // cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) Console.Write(mat[i, j] + " "); Console.WriteLine(); } } // Driver Code static public void Main() { int[, ] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); }} // This code is contributed by aj_36
<?php// PHP program to rotate// a matrix by 180 degree$N = 3; // Function to Rotate the// matrix by 180 degreefunction rotateMatrix($mat){ global $N; // Simply print from // last cell to first cell. for ($i = $N - 1; $i >= 0; $i--) { for ($j = $N - 1; $j >= 0; $j--) echo $mat[$i][$j], " "; echo "\n"; }} // Driver Code$mat = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); rotateMatrix($mat); // This code is contributed by ajit?>
<script> // Javascript program to rotate a// matrix by 180 degreesN = 3; // Function to Rotate the// matrix by 180 degreefunction rotateMatrix(mat){ // Simply print from last // cell to first cell. for(var i = N - 1; i >= 0; i--) { for(var j = N - 1; j >= 0; j--) document.write(mat[i][j] + " "); document.write("<br>"); }} // Driver Codevar mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; rotateMatrix(mat); // This code is contributed by kirti </script>
Output :
9 8 7
6 5 4
3 2 1
Time complexity: O(N*N) Auxiliary Space: O(1)
Method : 2(In-place rotation) There are four steps : 1- Find transpose of a matrix. 2- Reverse columns of the transpose. 3- Find transpose of a matrix. 4- Reverse columns of the transpose
Let the given matrix be
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
First we find transpose.
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Then we reverse elements of every column.
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
then transpose again
4 3 2 1
8 7 6 5
12 11 10 9
16 15 14 13
Then we reverse elements of every column again
16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1
C++
Java
C#
Python3
PHP
Javascript
// C++ program for left rotation of matrix by 180#include <bits/stdc++.h>using namespace std; #define R 4#define C 4 // Function to rotate the matrix by 180 degreevoid reverseColumns(int arr[R][C]){ for (int i = 0; i < C; i++) for (int j = 0, k = C - 1; j < k; j++, k--) swap(arr[j][i], arr[k][i]);} // Function for transpose of matrixvoid transpose(int arr[R][C]){ for (int i = 0; i < R; i++) for (int j = i; j < C; j++) swap(arr[i][j], arr[j][i]);} // Function for display the matrixvoid printMatrix(int arr[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << arr[i][j] << " "; cout << '\n'; }} // Function to anticlockwise rotate matrix// by 180 degreevoid rotate180(int arr[R][C]){ transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr);} // Driven codeint main(){ int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); return 0;}
// Java program for left// rotation of matrix by 180import java.util.*; class GFG { static int R = 4, C = 4, t = 0; // Function to rotate the // matrix by 180 degree static void reverseColumns(int arr[][]) { for (int i = 0; i < C; i++) { for (int j = 0, k = C - 1; j < k; j++, k--) { t = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = t; } } } // Function for transpose of matrix static void transpose(int arr[][]) { for (int i = 0; i < R; i++) { for (int j = i; j < C; j++) { t = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = t; } } } // Function for display the matrix static void printMatrix(int arr[][]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } // Function to anticlockwise // rotate matrix by 180 degree static void rotate180(int arr[][]) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driver Code public static void main(String[] args) { int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); }} // This code is contributed by ChitraNayal
// C# program for left// rotation of matrix by 180using System; class GFG { static int R = 4, C = 4, t = 0; // Function to rotate the // matrix by 180 degree static void reverseColumns(int[, ] arr) { for (int i = 0; i < C; i++) { for (int j = 0, k = C - 1; j < k; j++, k--) { t = arr[j, i]; arr[j, i] = arr[k, i]; arr[k, i] = t; } } } // Function for transpose of matrix static void transpose(int[, ] arr) { for (int i = 0; i < R; i++) { for (int j = i; j < C; j++) { t = arr[i, j]; arr[i, j] = arr[j, i]; arr[j, i] = t; } } } // Function for display the matrix static void printMatrix(int[, ] arr) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) Console.Write(arr[i, j] + " "); Console.WriteLine(); } } // Function to anticlockwise // rotate matrix by 180 degree static void rotate180(int[, ] arr) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driver Code static public void Main() { int[, ] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); }} // This code is contributed by ajit
# Python3 program for left rotation of matrix by 180 R = 4C = 4 # Function to rotate the matrix by 180 degreedef reverseColumns(arr): for i in range(C): j = 0 k = C-1 while j < k: t = arr[j][i] arr[j][i] = arr[k][i] arr[k][i] = t j += 1 k -= 1 # Function for transpose of matrixdef transpose(arr): for i in range(R): for j in range(i, C): t = arr[i][j] arr[i][j] = arr[j][i] arr[j][i] = t # Function for display the matrixdef printMatrix(arr): for i in range(R): for j in range(C): print(arr[i][j], end = " "); print(); # Function to anticlockwise rotate matrix# by 180 degreedef rotate180(arr): transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); # Driven codearr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ];rotate180(arr);printMatrix(arr);
<?php// PHP program for left rotation of matrix by 180 $R = 4;$C = 4; // Function to rotate the matrix by 180 degreefunction reverseColumns(&$arr){ global $C; for ($i = 0; $i < $C; $i++) { for ($j = 0, $k = $C - 1; $j < $k; $j++, $k--) { $t = $arr[$j][$i]; $arr[$j][$i] = $arr[$k][$i]; $arr[$k][$i] = $t; } } } // Function for transpose of matrixfunction transpose(&$arr){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = $i; $j < $C; $j++) { $t = $arr[$i][$j]; $arr[$i][$j] = $arr[$j][$i]; $arr[$j][$i] = $t; } }} // Function for display the matrixfunction printMatrix(&$arr){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { echo $arr[$i][$j]." "; } echo "\n"; }} // Function to anticlockwise rotate matrix// by 180 degreefunction rotate180(&$arr){ transpose($arr); reverseColumns($arr); transpose($arr); reverseColumns($arr);} // Driven code $arr = array( array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ), array( 9, 10, 11, 12 ), array( 13, 14, 15, 16 ) );rotate180($arr);printMatrix($arr);return 0;?>
<script>// Javascript program for left// rotation of matrix by 180 let R = 4, C = 4, t = 0; // Function to rotate the // matrix by 180 degree function reverseColumns(arr) { for (let i = 0; i < C; i++) { for (let j = 0, k = C - 1; j < k; j++, k--) { t = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = t; } } } // Function for transpose of matrix function transpose(arr) { for (let i = 0; i < R; i++) { for (let j = i; j < C; j++) { t = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = t; } } } // Function for display the matrix function printMatrix(arr) { for (let i = 0; i < R; i++) { for (let j = 0; j < C; j++) document.write(arr[i][j] + " "); document.write("<br>"); } } // Function to anticlockwise // rotate matrix by 180 degree function rotate180(arr) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driver Code let arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ]; rotate180(arr); printMatrix(arr); //This code is contributed by avanitrachhadiya2155 </script>
Output :
16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1
Time complexity : O(R*C) Auxiliary Space : O(1)In the code above, the transpose of the matrix has to be found twice, and also, columns have to be reversed twice. So, we can have a better solution.
Method : 3 (Position swapping)Here, we swap the values in the respective positions.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */void reverseRow(vector<vector<int>>& data, int index){ int cols = data[index].size(); for(int i = 0; i < cols / 2; i++) { int temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; }} /** * Print Matrix data * @param data matrix */void printMatrix(vector<vector<int>>& data){ for(int i = 0; i < data.size(); i++) { for(int j = 0; j < data[i].size(); j++) { cout << data[i][j] << " "; } cout << endl; }} /** * Rotate Matrix by 180 degrees * @param data matrix */void rotateMatrix180(vector<vector<int>>& data){ int rows = data.size(); int cols = data[0].size(); if (rows % 2 != 0) { // If N is odd reverse the middle // row in the matrix reverseRow(data, data.size() / 2); } // Swap the value of matrix [i][j] with // [rows - i - 1][cols - j - 1] for half // the rows size. for(int i = 0; i <= (rows/2) - 1; i++) { for(int j = 0; j < cols; j++) { int temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } }} // Driver code int main(){ vector<vector<int>> data{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; // Rotate Matrix rotateMatrix180(data); // Print Matrix printMatrix(data); return 0;} // This code is contributed by divyeshrabadiya07
public class GFG { /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */ private static void reverseRow(int[][] data, int index) { int cols = data[index].length; for (int i = 0; i < cols / 2; i++) { int temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; } } /** * Print Matrix data * @param data matrix */ private static void printMatrix(int[][] data) { for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { System.out.print(data[i][j] + " "); } System.out.println(""); } } /** * Rotate Matrix by 180 degrees * @param data matrix */ private static void rotateMatrix180(int[][] data) { int rows = data.length; int cols = data[0].length; if (rows % 2 != 0) { //If N is odd reverse the middle row in the matrix reverseRow(data, data.length / 2); } //Swap the value of matrix [i][j] with [rows - i - 1][cols - j - 1] for half the rows size. for (int i = 0; i <= (rows/2) - 1; i++) { for (int j = 0; j < cols; j++) { int temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } } } public static void main(String[] args) { int[][] data = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }; //Rotate Matrix rotateMatrix180(data); //Print Matrix printMatrix(data); }}
# Reverse Row at specified index in the matrixdef reverseRow(data, index): cols = len(data[index]) for i in range(cols // 2): temp = data[index][i] data[index][i] = data[index][cols - i - 1] data[index][cols - i - 1] = temp return data # Print Matrix datadef printMatrix(data): for i in range(len(data)): for j in range(len(data[0])): print(data[i][j], end = ' ') print() # Rotate Matrix by 180 degreesdef rotateMatrix(data): rows = len(data) cols = len(data[0]) if (rows % 2): # If N is odd reverse the middle # row in the matrix data = reverseRow(data, len(data) // 2) # Swap the value of matrix [i][j] with # [rows - i - 1][cols - j - 1] for half # the rows size. for i in range(rows // 2): for j in range(cols): temp = data[i][j] data[i][j] = data[rows - i - 1][cols - j - 1] data[rows - i - 1][cols - j - 1] = temp return data # Driver Codedata = [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ], [ 11, 12, 13, 14, 15 ], [ 16, 17, 18, 19, 20 ], [ 21, 22, 23, 24, 25 ] ] # Rotate Matrixdata = rotateMatrix(data) # Print MatrixprintMatrix(data) # This code is contributed by rohitsingh07052
using System; class GFG{ /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */ private static void reverseRow(int[, ] data, int index) { int cols = data.GetLength(1); for (int i = 0; i < cols / 2; i++) { int temp = data[index, i]; data[index, i] = data[index, cols - i - 1]; data[index, cols - i - 1] = temp; } } /** * Print Matrix data * @param data matrix */ private static void printMatrix(int[, ] data) { for (int i = 0; i < data.GetLength(0); i++) { for (int j = 0; j < data.GetLength(1); j++) { Console.Write(data[i, j] + " "); } Console.WriteLine(); } } /** * Rotate Matrix by 180 degrees * @param data matrix */ private static void rotateMatrix180(int[, ] data) { int rows = data.GetLength(0); int cols = data.GetLength(1); if (rows % 2 != 0) { // If N is odd reverse the middle row in the // matrix reverseRow(data, data.GetLength(0) / 2); } // Swap the value of matrix [i][j] with [rows - i - // 1][cols - j - 1] for half the rows size. for (int i = 0; i <= (rows / 2) - 1; i++) { for (int j = 0; j < cols; j++) { int temp = data[i, j]; data[i, j] = data[rows - i - 1, cols - j - 1]; data[rows - i - 1, cols - j - 1] = temp; } } } // Driver code public static void Main() { int[, ] data = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; // Rotate Matrix rotateMatrix180(data); // Print Matrix printMatrix(data); }} // This code is contributed by subhammahato348
<script> // Reverse Row at specified index in the matrix// @param data matrix// @param index row indexfunction reverseRow(data,index){ let cols = data[index].length; for(let i = 0; i < cols / 2; i++) { let temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; }} /** * Print Matrix data * @param data matrix */function printMatrix(data){ for(let i = 0; i < data.length; i++) { for(let j = 0; j < data[i].length; j++) { document.write(data[i][j] + " "); } document.write("<br>"); }} /** * Rotate Matrix by 180 degrees * @param data matrix */function rotateMatrix180(data){ let rows = data.length; let cols = data[0].length; if (rows % 2 != 0) { // If N is odd reverse the middle // row in the matrix reverseRow(data, Math.floor(data.length / 2)); } // Swap the value of matrix [i][j] // with [rows - i - 1][cols - j - 1] // for half the rows size. for(let i = 0; i <= (rows/2) - 1; i++) { for(let j = 0; j < cols; j++) { let temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } }} // Driver codelet data = [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ], [ 11, 12, 13, 14, 15 ], [ 16, 17, 18, 19, 20 ], [ 21, 22, 23, 24, 25 ] ];// Rotate MatrixrotateMatrix180(data); // Print MatrixprintMatrix(data); // This code is contributed by rag2127 </script>
Output :
25 24 23 22 21
20 19 18 17 16
15 14 13 12 11
10 9 8 7 6
5 4 3 2 1
Time complexity : O(R*C) Auxiliary Space : O(1)
ukasp
jit_t
Mithun Kumar
rajatssb
Knv Srinivas
rohitsingh07052
subhammahato348
divyeshrabadiya07
Kirti_Mangal
avanitrachhadiya2155
rag2127
Nvidia
rotation
Mathematical
Matrix
Nvidia
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 May, 2021"
},
{
"code": null,
"e": 183,
"s": 54,
"text": "Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space. "
},
{
"code": null,
"e": 195,
"s": 183,
"text": "Examples : "
},
{
"code": null,
"e": 437,
"s": 195,
"text": "Input : 1 2 3\n 4 5 6\n 7 8 9\nOutput : 9 8 7 \n 6 5 4 \n 3 2 1\n\nInput : 1 2 3 4 \n 5 6 7 8 \n 9 0 1 2 \n 3 4 5 6 \nOutput : 6 5 4 3 \n 2 1 0 9 \n 8 7 6 5 \n 4 3 2 1"
},
{
"code": null,
"e": 579,
"s": 437,
"text": "Method: 1 (Only prints rotated matrix) The solution of this problem is that to rotate a matrix by 180 degrees we can easily follow that step "
},
{
"code": null,
"e": 876,
"s": 579,
"text": "Matrix = a00 a01 a02\n a10 a11 a12\n a20 a21 a22\n\nwhen we rotate it by 90 degree\nthen matrix is\nMatrix = a02 a12 a22\n a01 a11 a21\n a00 a10 a20\n \nwhen we rotate it by again 90 \ndegree then matrix is \nMatrix = a22 a21 a20\n a12 a11 a10\n a02 a01 a00 "
},
{
"code": null,
"e": 1025,
"s": 876,
"text": "From the above illustration, we get that simply to rotate the matrix by 180 degrees then we will have to print the given matrix in a reverse manner."
},
{
"code": null,
"e": 1029,
"s": 1025,
"text": "C++"
},
{
"code": null,
"e": 1034,
"s": 1029,
"text": "Java"
},
{
"code": null,
"e": 1042,
"s": 1034,
"text": "Python3"
},
{
"code": null,
"e": 1045,
"s": 1042,
"text": "C#"
},
{
"code": null,
"e": 1049,
"s": 1045,
"text": "PHP"
},
{
"code": null,
"e": 1060,
"s": 1049,
"text": "Javascript"
},
{
"code": "// C++ program to rotate a matrix by 180 degrees#include <bits/stdc++.h>#define N 3using namespace std; // Function to Rotate the matrix by 180 degreevoid rotateMatrix(int mat[][N]){ // Simply print from last cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) printf(\"%d \", mat[i][j]); printf(\"\\n\"); }} // Driven codeint main(){ int mat[N][N] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); return 0;}",
"e": 1584,
"s": 1060,
"text": null
},
{
"code": "// Java program to rotate a// matrix by 180 degreesimport java.util.*; class GFG { static int N = 3; // Function to Rotate the // matrix by 180 degree static void rotateMatrix(int mat[][]) { // Simply print from last // cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) System.out.print(mat[i][j] + \" \"); System.out.println(); } } // Driver Code public static void main(String[] args) { int[][] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); }} // This code is contributed by ChitraNayal",
"e": 2291,
"s": 1584,
"text": null
},
{
"code": "# Python3 program to# rotate a matrix by# 180 degreesN = 3; # Function to Rotate# the matrix by 180 degreedef rotateMatrix(mat): # Simply print from # last cell to first cell. i = N - 1; while(i >= 0): j = N - 1; while(j >= 0): print(mat[i][j], end = \" \"); j = j - 1; print(); i = i - 1; # Driven codemat = [[1, 2, 3], [ 4, 5, 6 ], [ 7, 8, 9 ]];rotateMatrix(mat); # This code is contributed# by mits",
"e": 2770,
"s": 2291,
"text": null
},
{
"code": "// C# program to rotate a// matrix by 180 degreesusing System; class GFG { static int N = 3; // Function to Rotate the // matrix by 180 degree static void rotateMatrix(int[, ] mat) { // Simply print from last // cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) Console.Write(mat[i, j] + \" \"); Console.WriteLine(); } } // Driver Code static public void Main() { int[, ] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); }} // This code is contributed by aj_36",
"e": 3445,
"s": 2770,
"text": null
},
{
"code": "<?php// PHP program to rotate// a matrix by 180 degree$N = 3; // Function to Rotate the// matrix by 180 degreefunction rotateMatrix($mat){ global $N; // Simply print from // last cell to first cell. for ($i = $N - 1; $i >= 0; $i--) { for ($j = $N - 1; $j >= 0; $j--) echo $mat[$i][$j], \" \"; echo \"\\n\"; }} // Driver Code$mat = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); rotateMatrix($mat); // This code is contributed by ajit?>",
"e": 3961,
"s": 3445,
"text": null
},
{
"code": "<script> // Javascript program to rotate a// matrix by 180 degreesN = 3; // Function to Rotate the// matrix by 180 degreefunction rotateMatrix(mat){ // Simply print from last // cell to first cell. for(var i = N - 1; i >= 0; i--) { for(var j = N - 1; j >= 0; j--) document.write(mat[i][j] + \" \"); document.write(\"<br>\"); }} // Driver Codevar mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; rotateMatrix(mat); // This code is contributed by kirti </script>",
"e": 4486,
"s": 3961,
"text": null
},
{
"code": null,
"e": 4496,
"s": 4486,
"text": "Output : "
},
{
"code": null,
"e": 4521,
"s": 4496,
"text": " 9 8 7 \n 6 5 4 \n 3 2 1 "
},
{
"code": null,
"e": 4567,
"s": 4521,
"text": "Time complexity: O(N*N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4755,
"s": 4567,
"text": "Method : 2(In-place rotation) There are four steps : 1- Find transpose of a matrix. 2- Reverse columns of the transpose. 3- Find transpose of a matrix. 4- Reverse columns of the transpose"
},
{
"code": null,
"e": 5128,
"s": 4755,
"text": "Let the given matrix be\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n\nFirst we find transpose.\n1 5 9 13\n2 6 10 14\n3 7 11 15\n4 8 12 16\n\nThen we reverse elements of every column.\n4 8 12 16\n3 7 11 15\n2 6 10 14\n1 5 9 13\n\nthen transpose again \n4 3 2 1 \n8 7 6 5 \n12 11 10 9\n16 15 14 13 \n\nThen we reverse elements of every column again\n16 15 14 13 \n12 11 10 9 \n8 7 6 5 \n4 3 2 1"
},
{
"code": null,
"e": 5132,
"s": 5128,
"text": "C++"
},
{
"code": null,
"e": 5137,
"s": 5132,
"text": "Java"
},
{
"code": null,
"e": 5140,
"s": 5137,
"text": "C#"
},
{
"code": null,
"e": 5148,
"s": 5140,
"text": "Python3"
},
{
"code": null,
"e": 5152,
"s": 5148,
"text": "PHP"
},
{
"code": null,
"e": 5163,
"s": 5152,
"text": "Javascript"
},
{
"code": "// C++ program for left rotation of matrix by 180#include <bits/stdc++.h>using namespace std; #define R 4#define C 4 // Function to rotate the matrix by 180 degreevoid reverseColumns(int arr[R][C]){ for (int i = 0; i < C; i++) for (int j = 0, k = C - 1; j < k; j++, k--) swap(arr[j][i], arr[k][i]);} // Function for transpose of matrixvoid transpose(int arr[R][C]){ for (int i = 0; i < R; i++) for (int j = i; j < C; j++) swap(arr[i][j], arr[j][i]);} // Function for display the matrixvoid printMatrix(int arr[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << arr[i][j] << \" \"; cout << '\\n'; }} // Function to anticlockwise rotate matrix// by 180 degreevoid rotate180(int arr[R][C]){ transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr);} // Driven codeint main(){ int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); return 0;}",
"e": 6268,
"s": 5163,
"text": null
},
{
"code": "// Java program for left// rotation of matrix by 180import java.util.*; class GFG { static int R = 4, C = 4, t = 0; // Function to rotate the // matrix by 180 degree static void reverseColumns(int arr[][]) { for (int i = 0; i < C; i++) { for (int j = 0, k = C - 1; j < k; j++, k--) { t = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = t; } } } // Function for transpose of matrix static void transpose(int arr[][]) { for (int i = 0; i < R; i++) { for (int j = i; j < C; j++) { t = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = t; } } } // Function for display the matrix static void printMatrix(int arr[][]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) System.out.print(arr[i][j] + \" \"); System.out.println(); } } // Function to anticlockwise // rotate matrix by 180 degree static void rotate180(int arr[][]) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driver Code public static void main(String[] args) { int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); }} // This code is contributed by ChitraNayal",
"e": 7800,
"s": 6268,
"text": null
},
{
"code": "// C# program for left// rotation of matrix by 180using System; class GFG { static int R = 4, C = 4, t = 0; // Function to rotate the // matrix by 180 degree static void reverseColumns(int[, ] arr) { for (int i = 0; i < C; i++) { for (int j = 0, k = C - 1; j < k; j++, k--) { t = arr[j, i]; arr[j, i] = arr[k, i]; arr[k, i] = t; } } } // Function for transpose of matrix static void transpose(int[, ] arr) { for (int i = 0; i < R; i++) { for (int j = i; j < C; j++) { t = arr[i, j]; arr[i, j] = arr[j, i]; arr[j, i] = t; } } } // Function for display the matrix static void printMatrix(int[, ] arr) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) Console.Write(arr[i, j] + \" \"); Console.WriteLine(); } } // Function to anticlockwise // rotate matrix by 180 degree static void rotate180(int[, ] arr) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driver Code static public void Main() { int[, ] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); }} // This code is contributed by ajit",
"e": 9316,
"s": 7800,
"text": null
},
{
"code": "# Python3 program for left rotation of matrix by 180 R = 4C = 4 # Function to rotate the matrix by 180 degreedef reverseColumns(arr): for i in range(C): j = 0 k = C-1 while j < k: t = arr[j][i] arr[j][i] = arr[k][i] arr[k][i] = t j += 1 k -= 1 # Function for transpose of matrixdef transpose(arr): for i in range(R): for j in range(i, C): t = arr[i][j] arr[i][j] = arr[j][i] arr[j][i] = t # Function for display the matrixdef printMatrix(arr): for i in range(R): for j in range(C): print(arr[i][j], end = \" \"); print(); # Function to anticlockwise rotate matrix# by 180 degreedef rotate180(arr): transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); # Driven codearr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ];rotate180(arr);printMatrix(arr);",
"e": 10310,
"s": 9316,
"text": null
},
{
"code": "<?php// PHP program for left rotation of matrix by 180 $R = 4;$C = 4; // Function to rotate the matrix by 180 degreefunction reverseColumns(&$arr){ global $C; for ($i = 0; $i < $C; $i++) { for ($j = 0, $k = $C - 1; $j < $k; $j++, $k--) { $t = $arr[$j][$i]; $arr[$j][$i] = $arr[$k][$i]; $arr[$k][$i] = $t; } } } // Function for transpose of matrixfunction transpose(&$arr){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = $i; $j < $C; $j++) { $t = $arr[$i][$j]; $arr[$i][$j] = $arr[$j][$i]; $arr[$j][$i] = $t; } }} // Function for display the matrixfunction printMatrix(&$arr){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { echo $arr[$i][$j].\" \"; } echo \"\\n\"; }} // Function to anticlockwise rotate matrix// by 180 degreefunction rotate180(&$arr){ transpose($arr); reverseColumns($arr); transpose($arr); reverseColumns($arr);} // Driven code $arr = array( array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ), array( 9, 10, 11, 12 ), array( 13, 14, 15, 16 ) );rotate180($arr);printMatrix($arr);return 0;?>",
"e": 11597,
"s": 10310,
"text": null
},
{
"code": "<script>// Javascript program for left// rotation of matrix by 180 let R = 4, C = 4, t = 0; // Function to rotate the // matrix by 180 degree function reverseColumns(arr) { for (let i = 0; i < C; i++) { for (let j = 0, k = C - 1; j < k; j++, k--) { t = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = t; } } } // Function for transpose of matrix function transpose(arr) { for (let i = 0; i < R; i++) { for (let j = i; j < C; j++) { t = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = t; } } } // Function for display the matrix function printMatrix(arr) { for (let i = 0; i < R; i++) { for (let j = 0; j < C; j++) document.write(arr[i][j] + \" \"); document.write(\"<br>\"); } } // Function to anticlockwise // rotate matrix by 180 degree function rotate180(arr) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driver Code let arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ]; rotate180(arr); printMatrix(arr); //This code is contributed by avanitrachhadiya2155 </script>",
"e": 12993,
"s": 11597,
"text": null
},
{
"code": null,
"e": 13003,
"s": 12993,
"text": "Output : "
},
{
"code": null,
"e": 13049,
"s": 13003,
"text": " 16 15 14 13 \n 12 11 10 9 \n 8 7 6 5 \n 4 3 2 1"
},
{
"code": null,
"e": 13246,
"s": 13049,
"text": "Time complexity : O(R*C) Auxiliary Space : O(1)In the code above, the transpose of the matrix has to be found twice, and also, columns have to be reversed twice. So, we can have a better solution."
},
{
"code": null,
"e": 13331,
"s": 13246,
"text": "Method : 3 (Position swapping)Here, we swap the values in the respective positions. "
},
{
"code": null,
"e": 13335,
"s": 13331,
"text": "C++"
},
{
"code": null,
"e": 13340,
"s": 13335,
"text": "Java"
},
{
"code": null,
"e": 13348,
"s": 13340,
"text": "Python3"
},
{
"code": null,
"e": 13351,
"s": 13348,
"text": "C#"
},
{
"code": null,
"e": 13362,
"s": 13351,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */void reverseRow(vector<vector<int>>& data, int index){ int cols = data[index].size(); for(int i = 0; i < cols / 2; i++) { int temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; }} /** * Print Matrix data * @param data matrix */void printMatrix(vector<vector<int>>& data){ for(int i = 0; i < data.size(); i++) { for(int j = 0; j < data[i].size(); j++) { cout << data[i][j] << \" \"; } cout << endl; }} /** * Rotate Matrix by 180 degrees * @param data matrix */void rotateMatrix180(vector<vector<int>>& data){ int rows = data.size(); int cols = data[0].size(); if (rows % 2 != 0) { // If N is odd reverse the middle // row in the matrix reverseRow(data, data.size() / 2); } // Swap the value of matrix [i][j] with // [rows - i - 1][cols - j - 1] for half // the rows size. for(int i = 0; i <= (rows/2) - 1; i++) { for(int j = 0; j < cols; j++) { int temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } }} // Driver code int main(){ vector<vector<int>> data{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; // Rotate Matrix rotateMatrix180(data); // Print Matrix printMatrix(data); return 0;} // This code is contributed by divyeshrabadiya07",
"e": 15177,
"s": 13362,
"text": null
},
{
"code": "public class GFG { /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */ private static void reverseRow(int[][] data, int index) { int cols = data[index].length; for (int i = 0; i < cols / 2; i++) { int temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; } } /** * Print Matrix data * @param data matrix */ private static void printMatrix(int[][] data) { for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { System.out.print(data[i][j] + \" \"); } System.out.println(\"\"); } } /** * Rotate Matrix by 180 degrees * @param data matrix */ private static void rotateMatrix180(int[][] data) { int rows = data.length; int cols = data[0].length; if (rows % 2 != 0) { //If N is odd reverse the middle row in the matrix reverseRow(data, data.length / 2); } //Swap the value of matrix [i][j] with [rows - i - 1][cols - j - 1] for half the rows size. for (int i = 0; i <= (rows/2) - 1; i++) { for (int j = 0; j < cols; j++) { int temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } } } public static void main(String[] args) { int[][] data = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }; //Rotate Matrix rotateMatrix180(data); //Print Matrix printMatrix(data); }}",
"e": 17022,
"s": 15177,
"text": null
},
{
"code": "# Reverse Row at specified index in the matrixdef reverseRow(data, index): cols = len(data[index]) for i in range(cols // 2): temp = data[index][i] data[index][i] = data[index][cols - i - 1] data[index][cols - i - 1] = temp return data # Print Matrix datadef printMatrix(data): for i in range(len(data)): for j in range(len(data[0])): print(data[i][j], end = ' ') print() # Rotate Matrix by 180 degreesdef rotateMatrix(data): rows = len(data) cols = len(data[0]) if (rows % 2): # If N is odd reverse the middle # row in the matrix data = reverseRow(data, len(data) // 2) # Swap the value of matrix [i][j] with # [rows - i - 1][cols - j - 1] for half # the rows size. for i in range(rows // 2): for j in range(cols): temp = data[i][j] data[i][j] = data[rows - i - 1][cols - j - 1] data[rows - i - 1][cols - j - 1] = temp return data # Driver Codedata = [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ], [ 11, 12, 13, 14, 15 ], [ 16, 17, 18, 19, 20 ], [ 21, 22, 23, 24, 25 ] ] # Rotate Matrixdata = rotateMatrix(data) # Print MatrixprintMatrix(data) # This code is contributed by rohitsingh07052",
"e": 18396,
"s": 17022,
"text": null
},
{
"code": "using System; class GFG{ /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */ private static void reverseRow(int[, ] data, int index) { int cols = data.GetLength(1); for (int i = 0; i < cols / 2; i++) { int temp = data[index, i]; data[index, i] = data[index, cols - i - 1]; data[index, cols - i - 1] = temp; } } /** * Print Matrix data * @param data matrix */ private static void printMatrix(int[, ] data) { for (int i = 0; i < data.GetLength(0); i++) { for (int j = 0; j < data.GetLength(1); j++) { Console.Write(data[i, j] + \" \"); } Console.WriteLine(); } } /** * Rotate Matrix by 180 degrees * @param data matrix */ private static void rotateMatrix180(int[, ] data) { int rows = data.GetLength(0); int cols = data.GetLength(1); if (rows % 2 != 0) { // If N is odd reverse the middle row in the // matrix reverseRow(data, data.GetLength(0) / 2); } // Swap the value of matrix [i][j] with [rows - i - // 1][cols - j - 1] for half the rows size. for (int i = 0; i <= (rows / 2) - 1; i++) { for (int j = 0; j < cols; j++) { int temp = data[i, j]; data[i, j] = data[rows - i - 1, cols - j - 1]; data[rows - i - 1, cols - j - 1] = temp; } } } // Driver code public static void Main() { int[, ] data = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; // Rotate Matrix rotateMatrix180(data); // Print Matrix printMatrix(data); }} // This code is contributed by subhammahato348",
"e": 20180,
"s": 18396,
"text": null
},
{
"code": "<script> // Reverse Row at specified index in the matrix// @param data matrix// @param index row indexfunction reverseRow(data,index){ let cols = data[index].length; for(let i = 0; i < cols / 2; i++) { let temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; }} /** * Print Matrix data * @param data matrix */function printMatrix(data){ for(let i = 0; i < data.length; i++) { for(let j = 0; j < data[i].length; j++) { document.write(data[i][j] + \" \"); } document.write(\"<br>\"); }} /** * Rotate Matrix by 180 degrees * @param data matrix */function rotateMatrix180(data){ let rows = data.length; let cols = data[0].length; if (rows % 2 != 0) { // If N is odd reverse the middle // row in the matrix reverseRow(data, Math.floor(data.length / 2)); } // Swap the value of matrix [i][j] // with [rows - i - 1][cols - j - 1] // for half the rows size. for(let i = 0; i <= (rows/2) - 1; i++) { for(let j = 0; j < cols; j++) { let temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } }} // Driver codelet data = [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ], [ 11, 12, 13, 14, 15 ], [ 16, 17, 18, 19, 20 ], [ 21, 22, 23, 24, 25 ] ];// Rotate MatrixrotateMatrix180(data); // Print MatrixprintMatrix(data); // This code is contributed by rag2127 </script>",
"e": 21775,
"s": 20180,
"text": null
},
{
"code": null,
"e": 21785,
"s": 21775,
"text": "Output : "
},
{
"code": null,
"e": 21856,
"s": 21785,
"text": "25 24 23 22 21 \n20 19 18 17 16 \n15 14 13 12 11 \n10 9 8 7 6 \n5 4 3 2 1 "
},
{
"code": null,
"e": 21905,
"s": 21856,
"text": "Time complexity : O(R*C) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 21911,
"s": 21905,
"text": "ukasp"
},
{
"code": null,
"e": 21917,
"s": 21911,
"text": "jit_t"
},
{
"code": null,
"e": 21930,
"s": 21917,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 21939,
"s": 21930,
"text": "rajatssb"
},
{
"code": null,
"e": 21952,
"s": 21939,
"text": "Knv Srinivas"
},
{
"code": null,
"e": 21968,
"s": 21952,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 21984,
"s": 21968,
"text": "subhammahato348"
},
{
"code": null,
"e": 22002,
"s": 21984,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 22015,
"s": 22002,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 22036,
"s": 22015,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 22044,
"s": 22036,
"text": "rag2127"
},
{
"code": null,
"e": 22051,
"s": 22044,
"text": "Nvidia"
},
{
"code": null,
"e": 22060,
"s": 22051,
"text": "rotation"
},
{
"code": null,
"e": 22073,
"s": 22060,
"text": "Mathematical"
},
{
"code": null,
"e": 22080,
"s": 22073,
"text": "Matrix"
},
{
"code": null,
"e": 22087,
"s": 22080,
"text": "Nvidia"
},
{
"code": null,
"e": 22100,
"s": 22087,
"text": "Mathematical"
},
{
"code": null,
"e": 22107,
"s": 22100,
"text": "Matrix"
},
{
"code": null,
"e": 22205,
"s": 22107,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22235,
"s": 22205,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 22278,
"s": 22235,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 22338,
"s": 22278,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 22353,
"s": 22338,
"text": "C++ Data Types"
},
{
"code": null,
"e": 22377,
"s": 22353,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 22412,
"s": 22377,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 22456,
"s": 22412,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 22487,
"s": 22456,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 22511,
"s": 22487,
"text": "Sudoku | Backtracking-7"
}
] |
Text Preprocessing in Python | Set 2
|
29 May, 2019
Prerequisite: Introduction to NLP, Text Preprocessing in Python | Set 1
In the previous post, we saw the basic preprocessing steps when working with textual data. In this article, we will look at some more advanced text preprocessing techniques. We can use these techniques to gain more insights into the data that we have.
Let’s import the necessary libraries.
# import the necessary librariesimport nltkimport stringimport re
The part of speech explains how a word is used in a sentence. In a sentence, a word can have different contexts and semantic meanings. The basic natural language processing models like bag-of-words fail to identify these relations between words. Hence, we use part of speech tagging to mark a word to its part of speech tag based on its context in the data. It is also used to extract relationships between words.
from nltk.tokenize import word_tokenizefrom nltk import pos_tag # convert text into word_tokens with their tagsdef pos_tagging(text): word_tokens = word_tokenize(text) return pos_tag(word_tokens) pos_tagging('You just gave me a scare')
Example:
Input: ‘You just gave me a scare’Output: [(‘You’, ‘PRP’), (‘just’, ‘RB’), (‘gave’, ‘VBD’), (‘me’, ‘PRP’),(‘a’, ‘DT’), (‘scare’, ‘NN’)]
In the given example, PRP stands for personal pronoun, RB for adverb, VBD for verb past tense, DT for determiner and NN for noun. We can get the details of all the part of speech tags using the Penn Treebank tagset.
# download the tagset nltk.download('tagsets') # extract information about the tagnltk.help.upenn_tagset('NN')
Example:
Input: ‘NN’Output: NN: noun, common, singular or masscommon-carrier cabbage knuckle-duster Casino afghan shed thermostatinvestment slide humour falloff slick wind hyena override subhumanitymachinist ...
Chunking is the process of extracting phrases from unstructured text and more structure to it. It is also known as shallow parsing. It is done on top of Part of Speech tagging. It groups word into “chunks”, mainly of noun phrases. Chunking is done using regular expressions.
from nltk.tokenize import word_tokenize from nltk import pos_tag # define chunking function with text and regular# expression representing grammar as parameterdef chunking(text, grammar): word_tokens = word_tokenize(text) # label words with part of speech word_pos = pos_tag(word_tokens) # create a chunk parser using grammar chunkParser = nltk.RegexpParser(grammar) # test it on the list of word tokens with tagged pos tree = chunkParser.parse(word_pos) for subtree in tree.subtrees(): print(subtree) tree.draw() sentence = 'the little yellow bird is flying in the sky'grammar = "NP: {<DT>?<JJ>*<NN>}"chunking(sentence, grammar)
In the given example, grammar, which is defined using a simple regular expression rule. This rule says that an NP (Noun Phrase) chunk should be formed whenever the chunker finds an optional determiner (DT) followed by any number of adjectives (JJ) and then a noun (NN).
Libraries like spaCy and Textblob are more suited for chunking.
Example:
Input: ‘the little yellow bird is flying in the sky’Output:(S(NP the/DT little/JJ yellow/JJ bird/NN)is/VBZflying/VBGin/IN(NP the/DT sky/NN))(NP the/DT little/JJ yellow/JJ bird/NN)(NP the/DT sky/NN)
Named Entity Recognition is used to extract information from unstructured text. It is used to classify entities present in a text into categories like a person, organization, event, places, etc. It gives us detailed knowledge about the text and the relationships between the different entities.
from nltk.tokenize import word_tokenizefrom nltk import pos_tag, ne_chunk def named_entity_recognition(text): # tokenize the text word_tokens = word_tokenize(text) # part of speech tagging of words word_pos = pos_tag(word_tokens) # tree of word entities print(ne_chunk(word_pos)) text = 'Bill works for GeeksforGeeks so he went to Delhi for a meetup.'named_entity_recognition(text)
Example:
Input: ‘Bill works for GeeksforGeeks so he went to Delhi for a meetup.’Output:(S(PERSON Bill/NNP)works/VBZfor/IN(ORGANIZATION GeeksforGeeks/NNP)so/RBhe/PRPwent/VBDto/TO(GPE Delhi/NNP)for/INa/DTmeetup/NN./.)
Natural-language-processing
Python-nltk
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 May, 2019"
},
{
"code": null,
"e": 100,
"s": 28,
"text": "Prerequisite: Introduction to NLP, Text Preprocessing in Python | Set 1"
},
{
"code": null,
"e": 352,
"s": 100,
"text": "In the previous post, we saw the basic preprocessing steps when working with textual data. In this article, we will look at some more advanced text preprocessing techniques. We can use these techniques to gain more insights into the data that we have."
},
{
"code": null,
"e": 390,
"s": 352,
"text": "Let’s import the necessary libraries."
},
{
"code": "# import the necessary librariesimport nltkimport stringimport re",
"e": 456,
"s": 390,
"text": null
},
{
"code": null,
"e": 870,
"s": 456,
"text": "The part of speech explains how a word is used in a sentence. In a sentence, a word can have different contexts and semantic meanings. The basic natural language processing models like bag-of-words fail to identify these relations between words. Hence, we use part of speech tagging to mark a word to its part of speech tag based on its context in the data. It is also used to extract relationships between words."
},
{
"code": "from nltk.tokenize import word_tokenizefrom nltk import pos_tag # convert text into word_tokens with their tagsdef pos_tagging(text): word_tokens = word_tokenize(text) return pos_tag(word_tokens) pos_tagging('You just gave me a scare')",
"e": 1114,
"s": 870,
"text": null
},
{
"code": null,
"e": 1123,
"s": 1114,
"text": "Example:"
},
{
"code": null,
"e": 1258,
"s": 1123,
"text": "Input: ‘You just gave me a scare’Output: [(‘You’, ‘PRP’), (‘just’, ‘RB’), (‘gave’, ‘VBD’), (‘me’, ‘PRP’),(‘a’, ‘DT’), (‘scare’, ‘NN’)]"
},
{
"code": null,
"e": 1474,
"s": 1258,
"text": "In the given example, PRP stands for personal pronoun, RB for adverb, VBD for verb past tense, DT for determiner and NN for noun. We can get the details of all the part of speech tags using the Penn Treebank tagset."
},
{
"code": "# download the tagset nltk.download('tagsets') # extract information about the tagnltk.help.upenn_tagset('NN')",
"e": 1586,
"s": 1474,
"text": null
},
{
"code": null,
"e": 1595,
"s": 1586,
"text": "Example:"
},
{
"code": null,
"e": 1798,
"s": 1595,
"text": "Input: ‘NN’Output: NN: noun, common, singular or masscommon-carrier cabbage knuckle-duster Casino afghan shed thermostatinvestment slide humour falloff slick wind hyena override subhumanitymachinist ..."
},
{
"code": null,
"e": 2073,
"s": 1798,
"text": "Chunking is the process of extracting phrases from unstructured text and more structure to it. It is also known as shallow parsing. It is done on top of Part of Speech tagging. It groups word into “chunks”, mainly of noun phrases. Chunking is done using regular expressions."
},
{
"code": "from nltk.tokenize import word_tokenize from nltk import pos_tag # define chunking function with text and regular# expression representing grammar as parameterdef chunking(text, grammar): word_tokens = word_tokenize(text) # label words with part of speech word_pos = pos_tag(word_tokens) # create a chunk parser using grammar chunkParser = nltk.RegexpParser(grammar) # test it on the list of word tokens with tagged pos tree = chunkParser.parse(word_pos) for subtree in tree.subtrees(): print(subtree) tree.draw() sentence = 'the little yellow bird is flying in the sky'grammar = \"NP: {<DT>?<JJ>*<NN>}\"chunking(sentence, grammar)",
"e": 2755,
"s": 2073,
"text": null
},
{
"code": null,
"e": 3025,
"s": 2755,
"text": "In the given example, grammar, which is defined using a simple regular expression rule. This rule says that an NP (Noun Phrase) chunk should be formed whenever the chunker finds an optional determiner (DT) followed by any number of adjectives (JJ) and then a noun (NN)."
},
{
"code": null,
"e": 3089,
"s": 3025,
"text": "Libraries like spaCy and Textblob are more suited for chunking."
},
{
"code": null,
"e": 3098,
"s": 3089,
"text": "Example:"
},
{
"code": null,
"e": 3296,
"s": 3098,
"text": "Input: ‘the little yellow bird is flying in the sky’Output:(S(NP the/DT little/JJ yellow/JJ bird/NN)is/VBZflying/VBGin/IN(NP the/DT sky/NN))(NP the/DT little/JJ yellow/JJ bird/NN)(NP the/DT sky/NN)"
},
{
"code": null,
"e": 3591,
"s": 3296,
"text": "Named Entity Recognition is used to extract information from unstructured text. It is used to classify entities present in a text into categories like a person, organization, event, places, etc. It gives us detailed knowledge about the text and the relationships between the different entities."
},
{
"code": "from nltk.tokenize import word_tokenizefrom nltk import pos_tag, ne_chunk def named_entity_recognition(text): # tokenize the text word_tokens = word_tokenize(text) # part of speech tagging of words word_pos = pos_tag(word_tokens) # tree of word entities print(ne_chunk(word_pos)) text = 'Bill works for GeeksforGeeks so he went to Delhi for a meetup.'named_entity_recognition(text)",
"e": 3997,
"s": 3591,
"text": null
},
{
"code": null,
"e": 4006,
"s": 3997,
"text": "Example:"
},
{
"code": null,
"e": 4213,
"s": 4006,
"text": "Input: ‘Bill works for GeeksforGeeks so he went to Delhi for a meetup.’Output:(S(PERSON Bill/NNP)works/VBZfor/IN(ORGANIZATION GeeksforGeeks/NNP)so/RBhe/PRPwent/VBDto/TO(GPE Delhi/NNP)for/INa/DTmeetup/NN./.)"
},
{
"code": null,
"e": 4241,
"s": 4213,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 4253,
"s": 4241,
"text": "Python-nltk"
},
{
"code": null,
"e": 4260,
"s": 4253,
"text": "Python"
}
] |
What is the purpose of the testng.xml file?
|
The testng.xml file has the numerous uses as listed below −
Test cases are executed in groups.
Test cases are executed in groups.
Test methods can be included or excluded in the execution.
Test methods can be included or excluded in the execution.
The execution of multiple test cases from multiple java class files can be
triggered.
The execution of multiple test cases from multiple java class files can be
triggered.
Comprises names of the folder, class, method.
Comprises names of the folder, class, method.
Capable of triggering parallel execution.
Capable of triggering parallel execution.
Test methods belonging to groups can be included or excluded in the
execution.
Test methods belonging to groups can be included or excluded in the
execution.
TestNG.xml file
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Cycle1">
<test name = "Tutorialspoint">
<classes>
<class name = "Test1" />
<methods>
<exclude name= “Login.*”/>
</methods>
</classes>
</test>
</suite>
Here as per the xml file, all the test methods with starting name Login will be
excluded from test execution.
@Test
public void VerifyPay(){
System.out.println("Verify payment is successful”);
}
@Test
public void LoginAdmin(){
System.out.println("Login is successful in admin”);
}
@Test
public void LoginSystem(){
System.out.println("Login is successful”);
}
Here as per the java class file, only VerifyPay() will be executed since all methods starting with name Login will be excluded from test execution.
|
[
{
"code": null,
"e": 1247,
"s": 1187,
"text": "The testng.xml file has the numerous uses as listed below −"
},
{
"code": null,
"e": 1282,
"s": 1247,
"text": "Test cases are executed in groups."
},
{
"code": null,
"e": 1317,
"s": 1282,
"text": "Test cases are executed in groups."
},
{
"code": null,
"e": 1376,
"s": 1317,
"text": "Test methods can be included or excluded in the execution."
},
{
"code": null,
"e": 1435,
"s": 1376,
"text": "Test methods can be included or excluded in the execution."
},
{
"code": null,
"e": 1521,
"s": 1435,
"text": "The execution of multiple test cases from multiple java class files can be\ntriggered."
},
{
"code": null,
"e": 1607,
"s": 1521,
"text": "The execution of multiple test cases from multiple java class files can be\ntriggered."
},
{
"code": null,
"e": 1653,
"s": 1607,
"text": "Comprises names of the folder, class, method."
},
{
"code": null,
"e": 1699,
"s": 1653,
"text": "Comprises names of the folder, class, method."
},
{
"code": null,
"e": 1741,
"s": 1699,
"text": "Capable of triggering parallel execution."
},
{
"code": null,
"e": 1783,
"s": 1741,
"text": "Capable of triggering parallel execution."
},
{
"code": null,
"e": 1862,
"s": 1783,
"text": "Test methods belonging to groups can be included or excluded in the\nexecution."
},
{
"code": null,
"e": 1941,
"s": 1862,
"text": "Test methods belonging to groups can be included or excluded in the\nexecution."
},
{
"code": null,
"e": 1957,
"s": 1941,
"text": "TestNG.xml file"
},
{
"code": null,
"e": 2277,
"s": 1957,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name = \"Cycle1\">\n <test name = \"Tutorialspoint\">\n <classes>\n <class name = \"Test1\" />\n <methods>\n <exclude name= “Login.*”/>\n </methods>\n </classes>\n </test>\n</suite>"
},
{
"code": null,
"e": 2387,
"s": 2277,
"text": "Here as per the xml file, all the test methods with starting name Login will be\nexcluded from test execution."
},
{
"code": null,
"e": 2645,
"s": 2387,
"text": "@Test\npublic void VerifyPay(){\n System.out.println(\"Verify payment is successful”);\n}\n@Test\npublic void LoginAdmin(){\n System.out.println(\"Login is successful in admin”);\n}\n@Test\npublic void LoginSystem(){\n System.out.println(\"Login is successful”);\n}"
},
{
"code": null,
"e": 2793,
"s": 2645,
"text": "Here as per the java class file, only VerifyPay() will be executed since all methods starting with name Login will be excluded from test execution."
}
] |
Remove last node of the linked list
|
24 Jun, 2022
Given a linked list, the task is to remove the last node of the linked list and update the head pointer of the linked list.
Examples:
Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output: 1 -> 2 -> 3 -> 4 -> NULL
Explanation: The last node of the linked list
is 5, so 5 is deleted.
Input: 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL
Output: 2 -> 4 -> 6 -> 8 -> 33 -> NULL
Explanation: The last node of the linked list
is 67, so 67 is deleted.
Approach: To delete the last node of a linked list, find the second last node and make the next pointer of that node null.
Algorithm:
1. If the first node is null or there is only one node, then they return null.
if headNode == null then return null
if headNode.nextNode == null then free
head and return null
2. Create an extra space secondLast, and traverse the linked list till the second last node.
while secondLast.nextNode.nextNode != null
secondLast = secondLast.nextNode
3. delete the last node, i.e. the next node of the second last node delete(secondLast.nextNode), and set the value of the next second-last node to null.
Implementation:
C++
Java
Python3
C#
Javascript
// CPP program to remove last node of// linked list.#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Function to remove the last node of the linked list */Node* removeLastNode(struct Node* head){ if (head == NULL) return NULL; if (head->next == NULL) { delete head; return NULL; } // Find the second last node Node* second_last = head; while (second_last->next->next != NULL) second_last = second_last->next; // Delete last node delete (second_last->next); // Change next of second last second_last->next = NULL; return head;} // Function to push node at headvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ /* Start with the empty list */ Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); head = removeLastNode(head); for (Node* temp = head; temp != NULL; temp = temp->next) cout << temp->data << " "; return 0;}
// Java program to remove last node of// linked list.class GFG { // Link list node / static class Node { int data; Node next; }; // Function to remove the last node // of the linked list / static Node removeLastNode(Node head) { if (head == null) return null; if (head.next == null) { return null; } // Find the second last node Node second_last = head; while (second_last.next.next != null) second_last = second_last.next; // Change next of second last second_last.next = null; return head; } // Function to push node at head static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void main(String args[]) { // Start with the empty list / Node head = null; // Use push() function to construct // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeLastNode(head); for (Node temp = head; temp != null; temp = temp.next) System.out.print(temp.data + " "); }} // This code is contributed by Arnab Kundu
# Python3 program to remove the last node of # linked list.import sysimport math # Link list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to push node at head def push(head, data): if not head: return Node(data) temp = Node(data) temp.next = head head = temp return head # Function to remove the last node # of the linked listdef removeLastNode(head): if head == None: return None if head.next == None: head = None return None second_last = head while(second_last.next.next): second_last = second_last.next second_last.next = None return head # Driver codeif __name__=='__main__': # Start with the empty list head = None # Use push() function to construct # the below list 8 . 23 . 11 . 29 . 12 head = push(head, 12) head = push(head, 29) head = push(head, 11) head = push(head, 23) head = push(head, 8) head = removeLastNode(head) while(head): print("{} ".format(head.data), end ="") head = head.next # This code is contributed by Vikash kumar 37
// C# program to remove last node of// linked list.using System; class GFG { // Link list node / public class Node { public int data; public Node next; }; // Function to remove the last node // of the linked list / static Node removeLastNode(Node head) { if (head == null) return null; if (head.next == null) { return null; } // Find the second last node Node second_last = head; while (second_last.next.next != null) second_last = second_last.next; // Change next of second last second_last.next = null; return head; } // Function to push node at head static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void Main(String[] args) { // Start with the empty list / Node head = null; // Use push() function to construct // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeLastNode(head); for (Node temp = head; temp != null; temp = temp.next) Console.Write(temp.data + " "); }} /* This code contributed by PrinciRaj1992 */
<script>// javascript program to remove last node of// linked list. // Link list node / class Node { constructor() { this.data = 0; this.next = null; } } // Function to remove the last node // of the linked list / function removeLastNode(head) { if (head == null) return null; if (head.next == null) { return null; } // Find the second last node var second_last = head; while (second_last.next.next != null) second_last = second_last.next; // Change next of second last second_last.next = null; return head; } // Function to push node at head function push(head_ref , new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code // Start with the empty list / var head = null; // Use push() function to construct // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeLastNode(head); for (temp = head; temp != null; temp = temp.next) document.write(temp.data + " "); // This code contributed by Rajput-Ji</script>
8 23 11 29
Complexity Analysis:
Time Complexity: O(n). The algorithm involves traversal of the linked list till its end, so the time complexity required is O(n).
Space Complexity: O(1). No extra space is required, so the space complexity is constant.
VishalBachchas
andrew1234
Vikash Kumar 37
princiraj1992
Rajput-Ji
surinderdawra388
Technical Scripter 2018
Data Structures
Linked List
Technical Scripter
Data Structures
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 176,
"s": 52,
"text": "Given a linked list, the task is to remove the last node of the linked list and update the head pointer of the linked list."
},
{
"code": null,
"e": 188,
"s": 176,
"text": "Examples: "
},
{
"code": null,
"e": 485,
"s": 188,
"text": "Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL\nOutput: 1 -> 2 -> 3 -> 4 -> NULL\n\nExplanation: The last node of the linked list\nis 5, so 5 is deleted.\n\nInput: 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL\nOutput: 2 -> 4 -> 6 -> 8 -> 33 -> NULL\n\nExplanation: The last node of the linked list\nis 67, so 67 is deleted. "
},
{
"code": null,
"e": 610,
"s": 485,
"text": "Approach: To delete the last node of a linked list, find the second last node and make the next pointer of that node null. "
},
{
"code": null,
"e": 623,
"s": 610,
"text": "Algorithm: "
},
{
"code": null,
"e": 703,
"s": 623,
"text": "1. If the first node is null or there is only one node, then they return null. "
},
{
"code": null,
"e": 801,
"s": 703,
"text": "if headNode == null then return null\nif headNode.nextNode == null then free \nhead and return null"
},
{
"code": null,
"e": 895,
"s": 801,
"text": "2. Create an extra space secondLast, and traverse the linked list till the second last node. "
},
{
"code": null,
"e": 979,
"s": 895,
"text": "while secondLast.nextNode.nextNode != null \n secondLast = secondLast.nextNode "
},
{
"code": null,
"e": 1132,
"s": 979,
"text": "3. delete the last node, i.e. the next node of the second last node delete(secondLast.nextNode), and set the value of the next second-last node to null."
},
{
"code": null,
"e": 1150,
"s": 1132,
"text": "Implementation: "
},
{
"code": null,
"e": 1154,
"s": 1150,
"text": "C++"
},
{
"code": null,
"e": 1159,
"s": 1154,
"text": "Java"
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "Python3"
},
{
"code": null,
"e": 1170,
"s": 1167,
"text": "C#"
},
{
"code": null,
"e": 1181,
"s": 1170,
"text": "Javascript"
},
{
"code": "// CPP program to remove last node of// linked list.#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Function to remove the last node of the linked list */Node* removeLastNode(struct Node* head){ if (head == NULL) return NULL; if (head->next == NULL) { delete head; return NULL; } // Find the second last node Node* second_last = head; while (second_last->next->next != NULL) second_last = second_last->next; // Delete last node delete (second_last->next); // Change next of second last second_last->next = NULL; return head;} // Function to push node at headvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ /* Start with the empty list */ Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); head = removeLastNode(head); for (Node* temp = head; temp != NULL; temp = temp->next) cout << temp->data << \" \"; return 0;}",
"e": 2481,
"s": 1181,
"text": null
},
{
"code": "// Java program to remove last node of// linked list.class GFG { // Link list node / static class Node { int data; Node next; }; // Function to remove the last node // of the linked list / static Node removeLastNode(Node head) { if (head == null) return null; if (head.next == null) { return null; } // Find the second last node Node second_last = head; while (second_last.next.next != null) second_last = second_last.next; // Change next of second last second_last.next = null; return head; } // Function to push node at head static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void main(String args[]) { // Start with the empty list / Node head = null; // Use push() function to construct // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeLastNode(head); for (Node temp = head; temp != null; temp = temp.next) System.out.print(temp.data + \" \"); }} // This code is contributed by Arnab Kundu",
"e": 3944,
"s": 2481,
"text": null
},
{
"code": "# Python3 program to remove the last node of # linked list.import sysimport math # Link list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to push node at head def push(head, data): if not head: return Node(data) temp = Node(data) temp.next = head head = temp return head # Function to remove the last node # of the linked listdef removeLastNode(head): if head == None: return None if head.next == None: head = None return None second_last = head while(second_last.next.next): second_last = second_last.next second_last.next = None return head # Driver codeif __name__=='__main__': # Start with the empty list head = None # Use push() function to construct # the below list 8 . 23 . 11 . 29 . 12 head = push(head, 12) head = push(head, 29) head = push(head, 11) head = push(head, 23) head = push(head, 8) head = removeLastNode(head) while(head): print(\"{} \".format(head.data), end =\"\") head = head.next # This code is contributed by Vikash kumar 37",
"e": 5077,
"s": 3944,
"text": null
},
{
"code": "// C# program to remove last node of// linked list.using System; class GFG { // Link list node / public class Node { public int data; public Node next; }; // Function to remove the last node // of the linked list / static Node removeLastNode(Node head) { if (head == null) return null; if (head.next == null) { return null; } // Find the second last node Node second_last = head; while (second_last.next.next != null) second_last = second_last.next; // Change next of second last second_last.next = null; return head; } // Function to push node at head static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void Main(String[] args) { // Start with the empty list / Node head = null; // Use push() function to construct // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeLastNode(head); for (Node temp = head; temp != null; temp = temp.next) Console.Write(temp.data + \" \"); }} /* This code contributed by PrinciRaj1992 */",
"e": 6566,
"s": 5077,
"text": null
},
{
"code": "<script>// javascript program to remove last node of// linked list. // Link list node / class Node { constructor() { this.data = 0; this.next = null; } } // Function to remove the last node // of the linked list / function removeLastNode(head) { if (head == null) return null; if (head.next == null) { return null; } // Find the second last node var second_last = head; while (second_last.next.next != null) second_last = second_last.next; // Change next of second last second_last.next = null; return head; } // Function to push node at head function push(head_ref , new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code // Start with the empty list / var head = null; // Use push() function to construct // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeLastNode(head); for (temp = head; temp != null; temp = temp.next) document.write(temp.data + \" \"); // This code contributed by Rajput-Ji</script>",
"e": 8005,
"s": 6566,
"text": null
},
{
"code": null,
"e": 8016,
"s": 8005,
"text": "8 23 11 29"
},
{
"code": null,
"e": 8041,
"s": 8018,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 8171,
"s": 8041,
"text": "Time Complexity: O(n). The algorithm involves traversal of the linked list till its end, so the time complexity required is O(n)."
},
{
"code": null,
"e": 8260,
"s": 8171,
"text": "Space Complexity: O(1). No extra space is required, so the space complexity is constant."
},
{
"code": null,
"e": 8277,
"s": 8262,
"text": "VishalBachchas"
},
{
"code": null,
"e": 8288,
"s": 8277,
"text": "andrew1234"
},
{
"code": null,
"e": 8304,
"s": 8288,
"text": "Vikash Kumar 37"
},
{
"code": null,
"e": 8318,
"s": 8304,
"text": "princiraj1992"
},
{
"code": null,
"e": 8328,
"s": 8318,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8345,
"s": 8328,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8369,
"s": 8345,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 8385,
"s": 8369,
"text": "Data Structures"
},
{
"code": null,
"e": 8397,
"s": 8385,
"text": "Linked List"
},
{
"code": null,
"e": 8416,
"s": 8397,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8432,
"s": 8416,
"text": "Data Structures"
},
{
"code": null,
"e": 8444,
"s": 8432,
"text": "Linked List"
}
] |
Number of handshakes such that a person shakes hands only once
|
02 May, 2022
There is N number of people at a party. Find the total number of handshakes such that a person can handshake only once.
Examples:
Input : 5
Output : 10
Input : 9
Output : 36
We can see a recursive nature in the problem.
// n-th person has (n-1) choices and after
// n-th person chooses a person, problem
// recurs for n-1.
handshake(n) = (n-1) + handshake(n-1)
// Base case
handshake(0) = 0
Below is the implementation of the above recursive formula.
C++
C
Java
Python3
C#
PHP
Javascript
// Recursive C++ program to count total number of handshakes// when a person can shake hand with only one.#include <bits/stdc++.h>using namespace std; // Function to find all possible handshakesint handshake(int n){ // When n becomes 0 that means all the persons have done // handshake with other if (n == 0) return 0; else return (n - 1) + handshake(n - 1);} // Driver codeint main(){ int n = 9; cout << " " << handshake(n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Recursive C program to count total number of handshakes// when a person can shake hand with only one.#include <stdio.h> // function to find all possible handshakesint handshake(int n){ // when n becomes 0 that means all the persons have done // handshake with other if (n == 0) return 0; else return (n - 1) + handshake(n - 1);} int main(){ int n = 9; printf("%d", handshake(n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Recursive Java program to count total number of// handshakes when a person can shake hand with only one.import java.io.*; class GFG { // function to find all possible handshakes static int handshake(int n) { // when n becomes 0 that means all the persons have // done handshake with other if (n == 0) return 0; else return (n - 1) + handshake(n - 1); } // Driver Code public static void main(String[] args) { int n = 9; System.out.print(handshake(n)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Recursive Python program# to count total number of# handshakes when a person# can shake hand with only one. # function to find all# possible handshakesdef handshake(n): # when n becomes 0 that means # all the persons have done # handshake with other if (n == 0): return 0 else: return (n - 1) + handshake(n - 1) # Driver Coden = 9print(handshake(n)) # This code is contributed# by Shivi_Aggarwal
// Recursive C# program to// count total number of// handshakes when a person// can shake hand with only one.using System; class GFG{ // function to find all// possible handshakesstatic int handshake(int n){ // when n becomes 0 that // means all the persons // have done handshake // with other if (n == 0) return 0; else return (n - 1) + handshake(n - 1);} // Driver Codepublic static void Main (String []args){ int n = 9; Console.WriteLine(handshake(n));}} // This code is contributed// by Arnab Kundu
<?php// Recursive PHP program to // count total number of// handshakes when a person// can shake hand with only one. // function to find all// possible handshakesfunction handshake($n){ // when n becomes 0 that means // all the persons have done // handshake with other if ($n == 0) return 0; else return ($n - 1) + handshake($n - 1);} // Driver Code$n = 9;echo(handshake($n)); // This code is contributed// by Shivi_Aggarwal?>
<script> // Recursive JavaScript program to // count total number of // handshakes when a person // can shake hand with only one. // function to find all // possible handshakes function handshake(n) { // when n becomes 0 that // means all the persons // have done handshake // with other if (n === 0) return 0; else return n - 1 + handshake(n - 1); } // Driver Code var n = 9; document.write(handshake(n));</script>
36
We can come up with a direct formula by expanding the recursion.
handshake(n) = (n-1) + handshake(n-1)
= (n-1) + (n-2) + handshake(n-2)
= (n-1) + (n-2) + .... 1 + 0
= n * (n - 1)/2
C++
C
Java
Python3
C#
PHP
Javascript
// Recursive CPP program to count total number of handshakes// when a person can shake hand with only one.#include <bits/stdc++.h>using namespace std; // function to find all possible handshakesint handshake(int n) { return n * (n - 1) / 2; } int main(){ int n = 9; cout << handshake(n) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Recursive CPP program to count total number of handshakes// when a person can shake hand with only one.#include <stdio.h> // function to find all possible handshakesint handshake(int n) { return n * (n - 1) / 2; } int main(){ int n = 9; printf("%d", handshake(n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Recursive Java program to count total number of// handshakes when a person can shake hand with only one.class GFG { // function to find all possible handshakes static int handshake(int n) { return n * (n - 1) / 2; } // Driver code public static void main(String args[]) { int n = 9; System.out.println(handshake(n)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Recursive Python program# to count total number of# handshakes when a person# can shake hand with only one. # function to find all# possible handshakesdef handshake(n): return int(n * (n - 1) / 2) # Driver Coden = 9print(handshake(n)) # This code is contributed# by Shivi_Aggarwal
// Recursive C# program to// count total number of// handshakes when a person// can shake hand with only one.using System; class GFG{ // function to find all// possible handshakesstatic int handshake(int n){ return n * (n - 1) / 2;} // Driver codestatic public void Main (){ int n = 9; Console.WriteLine(handshake(n));}} // This code is contributed by Sachin
<?php// Recursive PHP program to// count total number of// handshakes when a person// can shake hand with only one. // function to find all// possible handshakesfunction handshake($n){ return $n * ($n - 1) / 2;} // Driver Code$n = 9;echo(handshake($n)); // This code is contributed// by Shivi_Aggarwal?>
<script> // Recursive Javascript program to// count total number of// handshakes when a person// can shake hand with only one. // Function to find all// possible handshakesfunction handshake(n){ return n * parseInt((n - 1) / 2, 10);} // Driver codelet n = 9; document.write(handshake(n)); // This code is contributed by rameshtravel07 </script>
36
Chandan_Kumar
andrew1234
Shivi_Aggarwal
Sach_Code
rdtank
rameshtravel07
shivanisinghss2110
adityakumar129
Combinatorial
Recursion
School Programming
Recursion
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 May, 2022"
},
{
"code": null,
"e": 172,
"s": 52,
"text": "There is N number of people at a party. Find the total number of handshakes such that a person can handshake only once."
},
{
"code": null,
"e": 183,
"s": 172,
"text": "Examples: "
},
{
"code": null,
"e": 229,
"s": 183,
"text": "Input : 5\nOutput : 10\n\nInput : 9\nOutput : 36 "
},
{
"code": null,
"e": 276,
"s": 229,
"text": "We can see a recursive nature in the problem. "
},
{
"code": null,
"e": 449,
"s": 276,
"text": "// n-th person has (n-1) choices and after\n// n-th person chooses a person, problem\n// recurs for n-1.\nhandshake(n) = (n-1) + handshake(n-1)\n\n// Base case\nhandshake(0) = 0 "
},
{
"code": null,
"e": 510,
"s": 449,
"text": "Below is the implementation of the above recursive formula. "
},
{
"code": null,
"e": 514,
"s": 510,
"text": "C++"
},
{
"code": null,
"e": 516,
"s": 514,
"text": "C"
},
{
"code": null,
"e": 521,
"s": 516,
"text": "Java"
},
{
"code": null,
"e": 529,
"s": 521,
"text": "Python3"
},
{
"code": null,
"e": 532,
"s": 529,
"text": "C#"
},
{
"code": null,
"e": 536,
"s": 532,
"text": "PHP"
},
{
"code": null,
"e": 547,
"s": 536,
"text": "Javascript"
},
{
"code": "// Recursive C++ program to count total number of handshakes// when a person can shake hand with only one.#include <bits/stdc++.h>using namespace std; // Function to find all possible handshakesint handshake(int n){ // When n becomes 0 that means all the persons have done // handshake with other if (n == 0) return 0; else return (n - 1) + handshake(n - 1);} // Driver codeint main(){ int n = 9; cout << \" \" << handshake(n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1081,
"s": 547,
"text": null
},
{
"code": "// Recursive C program to count total number of handshakes// when a person can shake hand with only one.#include <stdio.h> // function to find all possible handshakesint handshake(int n){ // when n becomes 0 that means all the persons have done // handshake with other if (n == 0) return 0; else return (n - 1) + handshake(n - 1);} int main(){ int n = 9; printf(\"%d\", handshake(n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1572,
"s": 1081,
"text": null
},
{
"code": "// Recursive Java program to count total number of// handshakes when a person can shake hand with only one.import java.io.*; class GFG { // function to find all possible handshakes static int handshake(int n) { // when n becomes 0 that means all the persons have // done handshake with other if (n == 0) return 0; else return (n - 1) + handshake(n - 1); } // Driver Code public static void main(String[] args) { int n = 9; System.out.print(handshake(n)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 2181,
"s": 1572,
"text": null
},
{
"code": "# Recursive Python program# to count total number of# handshakes when a person# can shake hand with only one. # function to find all# possible handshakesdef handshake(n): # when n becomes 0 that means # all the persons have done # handshake with other if (n == 0): return 0 else: return (n - 1) + handshake(n - 1) # Driver Coden = 9print(handshake(n)) # This code is contributed# by Shivi_Aggarwal",
"e": 2609,
"s": 2181,
"text": null
},
{
"code": "// Recursive C# program to// count total number of// handshakes when a person// can shake hand with only one.using System; class GFG{ // function to find all// possible handshakesstatic int handshake(int n){ // when n becomes 0 that // means all the persons // have done handshake // with other if (n == 0) return 0; else return (n - 1) + handshake(n - 1);} // Driver Codepublic static void Main (String []args){ int n = 9; Console.WriteLine(handshake(n));}} // This code is contributed// by Arnab Kundu",
"e": 3151,
"s": 2609,
"text": null
},
{
"code": "<?php// Recursive PHP program to // count total number of// handshakes when a person// can shake hand with only one. // function to find all// possible handshakesfunction handshake($n){ // when n becomes 0 that means // all the persons have done // handshake with other if ($n == 0) return 0; else return ($n - 1) + handshake($n - 1);} // Driver Code$n = 9;echo(handshake($n)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 3608,
"s": 3151,
"text": null
},
{
"code": "<script> // Recursive JavaScript program to // count total number of // handshakes when a person // can shake hand with only one. // function to find all // possible handshakes function handshake(n) { // when n becomes 0 that // means all the persons // have done handshake // with other if (n === 0) return 0; else return n - 1 + handshake(n - 1); } // Driver Code var n = 9; document.write(handshake(n));</script>",
"e": 4140,
"s": 3608,
"text": null
},
{
"code": null,
"e": 4143,
"s": 4140,
"text": "36"
},
{
"code": null,
"e": 4211,
"s": 4145,
"text": "We can come up with a direct formula by expanding the recursion. "
},
{
"code": null,
"e": 4368,
"s": 4211,
"text": "handshake(n) = (n-1) + handshake(n-1)\n = (n-1) + (n-2) + handshake(n-2)\n = (n-1) + (n-2) + .... 1 + 0\n = n * (n - 1)/2 "
},
{
"code": null,
"e": 4372,
"s": 4368,
"text": "C++"
},
{
"code": null,
"e": 4374,
"s": 4372,
"text": "C"
},
{
"code": null,
"e": 4379,
"s": 4374,
"text": "Java"
},
{
"code": null,
"e": 4387,
"s": 4379,
"text": "Python3"
},
{
"code": null,
"e": 4390,
"s": 4387,
"text": "C#"
},
{
"code": null,
"e": 4394,
"s": 4390,
"text": "PHP"
},
{
"code": null,
"e": 4405,
"s": 4394,
"text": "Javascript"
},
{
"code": "// Recursive CPP program to count total number of handshakes// when a person can shake hand with only one.#include <bits/stdc++.h>using namespace std; // function to find all possible handshakesint handshake(int n) { return n * (n - 1) / 2; } int main(){ int n = 9; cout << handshake(n) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 4782,
"s": 4405,
"text": null
},
{
"code": "// Recursive CPP program to count total number of handshakes// when a person can shake hand with only one.#include <stdio.h> // function to find all possible handshakesint handshake(int n) { return n * (n - 1) / 2; } int main(){ int n = 9; printf(\"%d\", handshake(n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 5131,
"s": 4782,
"text": null
},
{
"code": "// Recursive Java program to count total number of// handshakes when a person can shake hand with only one.class GFG { // function to find all possible handshakes static int handshake(int n) { return n * (n - 1) / 2; } // Driver code public static void main(String args[]) { int n = 9; System.out.println(handshake(n)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 5549,
"s": 5131,
"text": null
},
{
"code": "# Recursive Python program# to count total number of# handshakes when a person# can shake hand with only one. # function to find all# possible handshakesdef handshake(n): return int(n * (n - 1) / 2) # Driver Coden = 9print(handshake(n)) # This code is contributed# by Shivi_Aggarwal",
"e": 5844,
"s": 5549,
"text": null
},
{
"code": "// Recursive C# program to// count total number of// handshakes when a person// can shake hand with only one.using System; class GFG{ // function to find all// possible handshakesstatic int handshake(int n){ return n * (n - 1) / 2;} // Driver codestatic public void Main (){ int n = 9; Console.WriteLine(handshake(n));}} // This code is contributed by Sachin",
"e": 6216,
"s": 5844,
"text": null
},
{
"code": "<?php// Recursive PHP program to// count total number of// handshakes when a person// can shake hand with only one. // function to find all// possible handshakesfunction handshake($n){ return $n * ($n - 1) / 2;} // Driver Code$n = 9;echo(handshake($n)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 6523,
"s": 6216,
"text": null
},
{
"code": "<script> // Recursive Javascript program to// count total number of// handshakes when a person// can shake hand with only one. // Function to find all// possible handshakesfunction handshake(n){ return n * parseInt((n - 1) / 2, 10);} // Driver codelet n = 9; document.write(handshake(n)); // This code is contributed by rameshtravel07 </script>",
"e": 6871,
"s": 6523,
"text": null
},
{
"code": null,
"e": 6874,
"s": 6871,
"text": "36"
},
{
"code": null,
"e": 6890,
"s": 6876,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 6901,
"s": 6890,
"text": "andrew1234"
},
{
"code": null,
"e": 6916,
"s": 6901,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 6926,
"s": 6916,
"text": "Sach_Code"
},
{
"code": null,
"e": 6933,
"s": 6926,
"text": "rdtank"
},
{
"code": null,
"e": 6948,
"s": 6933,
"text": "rameshtravel07"
},
{
"code": null,
"e": 6967,
"s": 6948,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 6982,
"s": 6967,
"text": "adityakumar129"
},
{
"code": null,
"e": 6996,
"s": 6982,
"text": "Combinatorial"
},
{
"code": null,
"e": 7006,
"s": 6996,
"text": "Recursion"
},
{
"code": null,
"e": 7025,
"s": 7006,
"text": "School Programming"
},
{
"code": null,
"e": 7035,
"s": 7025,
"text": "Recursion"
},
{
"code": null,
"e": 7049,
"s": 7035,
"text": "Combinatorial"
}
] |
Python MongoDB - Create Database
|
Unlike other databases, MongoDB does not provide separate command to create a database.
In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created.
Therefore, you can create a database in MongoDB using the Use command.
Basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME
Following command creates a database named in mydb.
>use mydb
switched to db mydb
You can verify your creation by using the db command, this displays the current database.
>db
mydb
To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion.
Following example creates a database in MangoDB.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
print("Database created........")
#Verification
print("List of databases after creating new one")
print(client.list_database_names())
Database created........
List of databases after creating new one:
['admin', 'config', 'local', 'mydb']
You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
print("Database created........")
Database created........
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3293,
"s": 3205,
"text": "Unlike other databases, MongoDB does not provide separate command to create a database."
},
{
"code": null,
"e": 3565,
"s": 3293,
"text": "In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created."
},
{
"code": null,
"e": 3636,
"s": 3565,
"text": "Therefore, you can create a database in MongoDB using the Use command."
},
{
"code": null,
"e": 3691,
"s": 3636,
"text": "Basic syntax of use DATABASE statement is as follows −"
},
{
"code": null,
"e": 3710,
"s": 3691,
"text": "use DATABASE_NAME\n"
},
{
"code": null,
"e": 3762,
"s": 3710,
"text": "Following command creates a database named in mydb."
},
{
"code": null,
"e": 3793,
"s": 3762,
"text": ">use mydb\nswitched to db mydb\n"
},
{
"code": null,
"e": 3883,
"s": 3793,
"text": "You can verify your creation by using the db command, this displays the current database."
},
{
"code": null,
"e": 3893,
"s": 3883,
"text": ">db\nmydb\n"
},
{
"code": null,
"e": 4058,
"s": 3893,
"text": "To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion."
},
{
"code": null,
"e": 4107,
"s": 4058,
"text": "Following example creates a database in MangoDB."
},
{
"code": null,
"e": 4395,
"s": 4107,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\nprint(\"Database created........\")\n\n#Verification\nprint(\"List of databases after creating new one\")\nprint(client.list_database_names())"
},
{
"code": null,
"e": 4500,
"s": 4395,
"text": "Database created........\nList of databases after creating new one:\n['admin', 'config', 'local', 'mydb']\n"
},
{
"code": null,
"e": 4624,
"s": 4500,
"text": "You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style."
},
{
"code": null,
"e": 4811,
"s": 4624,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\nprint(\"Database created........\")"
},
{
"code": null,
"e": 4837,
"s": 4811,
"text": "Database created........\n"
},
{
"code": null,
"e": 4874,
"s": 4837,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4890,
"s": 4874,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4923,
"s": 4890,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4942,
"s": 4923,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4977,
"s": 4942,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4999,
"s": 4977,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5033,
"s": 4999,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5061,
"s": 5033,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5096,
"s": 5061,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5110,
"s": 5096,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5143,
"s": 5110,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5160,
"s": 5143,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5167,
"s": 5160,
"text": " Print"
},
{
"code": null,
"e": 5178,
"s": 5167,
"text": " Add Notes"
}
] |
Exploratory Data Analysis with Python in B2B Marketing | by Mai Nguyen | Towards Data Science
|
This project focuses on conducting Exploratory Data Analysis (EDA) for B2B Marketing using Python. We will use data from Olist, an e-commerce platform that connects small and medium business with top Marketplaces in Brazil, as an example. Besides providing the method and the code, I also want to discuss the fundamentals in B2B Marketing and how these insights from EDA can help Olist to make a better marketing decision. All the Python code is provided on my GitHub.
Olist is a platform that connects small and medium business with the marketplaces in Brazil (Extra, Shoptime, Walmart, Submarino, .etc) and helps the merchants to sell at these marketplaces. Unlike in some countries, the fast-growing e-commerce sector in Brazil is dominated by a number of large-size marketplaces rather than by a few marketplaces (Ex: Amazon and Ebay in the U.S.). Therefore, a merchant has the incentive to operate in multiple marketplaces to maximize their revenue. With the limitation in human resources as the main pain point, the merchant would want to use Olist to manage its sales channel in different marketplaces and streamline the stock management and the order fulfillment process.
With this B2B2C model, Olist’s marketing team have 2 main objectives:
From the seller side, they want to increase the number of merchants using Olist platform.
From the buyer side, they want to maximize the e-commerce sales of the merchants on these marketplaces.
The scope of this analysis focuses more on the seller side (B2B) of Olist. With a given dataset, I will conduct the exploratory data analysis (EDA) that can bring some helpful insights into Olist’s B2B marketing team.
Marketing & Sales process for B2B:
The datasets were obtained from Kaggle. You can download it here.
The first dataset has 4 variables with 8000 data points. The variables are MQL_id (marketing qualified leads), its first contact date, the landing page that captured the leads, and the lead origin (the channel that brings the leads to the landing pages).
The second dataset contains 842 observations with 14 variables. Each observation is a won deal of Olist which consists of the mql_id of the merchant, seller_id (used in Olist platform), sdr_id and sr_id(the sales development representative and sales representative that were in charge of the deal), won_date, business segment, lead_type, lead_behaviour_profile, business_type, declared_monthly_revenue. Among these, 5 variables have too many Null values that they cannot bring value to the analysis.
Third dataset: Via Kaggle, Olist also donated their dataset about the demand side. We will use this to inform Olist marketers about the performance of the sellers, thus help them to improve the B2B marketing process.
The number of MQL: The MQL data is provided from 07/2017 to 06/2018, while the won MQL data is provided from 01/2018 to 12/2018. In 2017, MQLs that Olist marketing team generated is around 400 MQLs/month. In 2018, they boost the number to 1000–1400 leads per month. Regarding the won MQL, its peak was at 05/2018 with 200 won opportunities.
#Figure 1num_mql = mql.set_index(pd.to_datetime(mql[‘first_contact_date’]))num_mql = num_mql.groupby(pd.Grouper(freq = “M”)).count().drop(axis =1, columns = [‘first_contact_date’,“landing_page_id”, “origin”])num_won = close.set_index(pd.to_datetime(close[“won_date”]))num_won = num_won.groupby(pd.Grouper(freq = “M”)).count().drop(axis = 1, columns = [“seller_id”, “sdr_id”, “sr_id”,“business_segment”, “lead_type”, “lead_behaviour_profile”, “has_company”, “has_gtin”, “average_stock”, “business_type”,“declared_product_catalog_size”, “declared_monthly_revenue”, “won_date”])plt.figure(figsize = (8,6))plt.plot(num_mql.index, num_mql, "-", label = "number of MQL")plt.plot(num_won.index, num_won, "-", label = "number of won MQL")plt.legend()plt.title("Number of MQL", size = 15)plt.savefig("NumMQL.png")
Channels: The majority of MQLs come from organic_search channel, followed by direct traffic and social. Other, other_publicities, referral and display are the sources that bring the least MQLs to Olist. The organic_search MQL is significantly increased in 2018–02 and declined after that. This can be the result of a big event/PR campaign.
#Figure 2mql_origin = mql.groupby(‘origin’).agg({‘mql_id’:”count”});print(mql_origin)origin = list(mql_origin.index)plt.figure(figsize = (10,8))fancy_plot = plt.subplot()for i in origin: channel = mql[mql[‘origin’] == i] channel = channel.set_index(pd.to_datetime(channel[‘first_contact_date’])) channel_agg = channel.groupby(pd.Grouper(freq = “M”)).count().drop(axis = 1, columns =[“first_contact_date”, “landing_page_id”, “origin”]) fancy_plot.plot(channel_agg.index, channel_agg, “-o”, label = i)fancy_plot.legend()plt.title(‘Number of MQL by channels overtime’, size = 15)plt.savefig(“channel-mql.png”)
The conversion rates for these channels are varied. Organic_search, paid_search and direct traffic are the sources that enjoy the highest conversion rates (12.5%, 11.5%, and 11% respectively). Email, other_publicities and social have the lowest conversion rates (3%, 5%, 5.5% respectively). This means that SEO and Google Adwords are the most effective marketing channels for Olist. This result seems to be relevant to a couple of surveys illustrating the most effective marketing channel for B2B companies.
www.bizible.com
#Figure 3origin_lost = data.groupby([‘origin’, ‘lost’]).count().drop(axis = 1, columns =[‘first_contact_date’,’landing_page_id’, “seller_id”, “sdr_id”, “sr_id”, “won_date”, “business_segment”, “lead_type”, “lead_behaviour_profile”, “has_company”, “has_gtin”, “average_stock”, “business_type”, “declared_product_catalog_size”, “declared_monthly_revenue”])percentage = []for i in origin: pct = origin_lost.loc[i].loc[False][0]/(origin_lost.loc[i].loc[True][0]+origin_lost.loc[i].loc[False][0]) percentage.append(pct)plt.figure(figsize = (6,4))plt.bar(origin, percentage)plt.xticks(rotation = 90)plt.ylabel(‘won rate’)plt.savefig(“won-rate.png”)
Olist used 495 landing pages to capture MQLs. Even though the sales team is responsible for converting an MQL into a won opportunity, the marketing team can affect this likelihood from the top of the funnel by providing relevant messaging and benefits on the landing pages. From figure 4 above, there are 2 landing pages that have a very high number of MQLs (~800 MQLs) as well as very high won rate (~20%), meaning that 20% of the MQLs captured from these landing pages become Olist’s sellers.
#Figure 4mql_lp = mql.groupby(‘landing_page_id’).agg({‘mql_id’:”count”})mql_lp = mql_lp[mql_lp[‘mql_id’] > 30]data_lp = pd.merge(data, mql_lp, how = “inner”, left_on = “landing_page_id”, right_index = True)lp_lost = data_lp.groupby([‘landing_page_id’, ‘lost’]).agg({‘mql_id_x’:”count”})landing_page = list(mql_lp.index)percentage_lp = []landing_page_2 = []Num_mql = []for i in landing_page: if mql_lp.loc[i][0] == lp_lost.loc[i].loc[True][0]: lp_lost.drop([i]) else: pct = lp_lost.loc[i].loc[False][0]/(lp_lost.loc[i].loc[True][0]+lp_lost.loc[i].loc[False][0]) percentage_lp.append(pct) landing_page_2.append(i) Num_mql.append(mql_lp.loc[i][0])fig = plt.figure(figsize = (10,4))ax = fig.add_subplot(111)ax2 = ax.twinx()ax.bar(landing_page_2, percentage_lp)ax2.plot(landing_page_2, Num_mql, color = “red”)ax.set_ylabel(‘won rate’)ax2.set_ylabel(‘number of MQL’)for tick in ax.get_xticklabels(): tick.set_rotation(90)plt.savefig(“landing-page.png”)
Learning from these landing pages can help Olist to replicate the success to other landing pages.
Targeting is very important in B2B marketing. There’re segments that will be very interested in Olist and vice versa. The following graph shows that by using the sales cycle (how long the sales process is) as the indication:
#Figure 5data2 = pd.merge(mql, close, how = “right”, on = “mql_id”)data2[‘first_contact_date’] = pd.to_datetime(data2[‘first_contact_date’])data2[‘won_date’] = pd.to_datetime(data2[‘won_date’])data2[‘sales cycle’] = data2[‘won_date’] — data2[‘first_contact_date’]data2[‘sales cycle’] = data2[‘sales cycle’].dt.dayssegment_time = data2.groupby([‘business_segment’]).agg({“mql_id”:”count”, “sales cycle”:”mean”})fig = plt.figure(figsize = (10,4))ax = fig.add_subplot(111)ax2 = ax.twinx()ax.bar(segment_time.index, segment_time[‘sales cycle’])ax2.plot(segment_time.index, segment_time[‘mql_id’], color = “red”)ax.set_ylabel(‘Sales cycle’)ax2.set_ylabel(‘number of MQL’)for tick in ax.get_xticklabels(): tick.set_rotation(90)
Business segments such as Home_decor, health_beauty, household_utilities, construction tool for house and garden, car accessories and electronics are the majorities of the sellers with the sales cycle typically around 50 days. Some segments that have a long sales cycle than others are perfume and watches. However, since these 2 segments only have a small number of MQLs (7 & 10) so Olist should probably wait for more MQLs to have a more accurate observation.
Regarding the Lead_type variable, Online_medium is the most popular type among Olist MQLs. There is no significant difference between the sales cycle of these business types.
#Figure 7fig = plt.figure(figsize = (10,4))ax = fig.add_subplot(111)ax2 = ax.twinx()ax.bar(lead_time.index, lead_time[‘sales cycle’])ax2.plot(lead_time.index, lead_time[‘mql_id’], color = “red”)ax.set_ylabel(‘Sales cycle’)ax2.set_ylabel(‘number of MQL’)for tick in ax.get_xticklabels(): tick.set_rotation(90)
Olist can also base on the sales cycle to evaluate the performance of a Sales Rep. From Figure 7, It seems that the number of leads an SR has, the shorter the sales cycle. This can be explained that an experienced sales rep (more MQLs) will perform better (shorter sales length) than a new sales rep.
The table below is the description of each behavior profile, based on DiSC, a behavior assessment tool developed from DiSC theory of psychologist William Moulton Marston.
#Figure 8segment = pd.DataFrame(index = ['cat','eagle', 'wolf', 'shark'])for i in segment_time.index: lead_profile = close[close['business_segment'] == i] segment = lead_profile.groupby('lead_behaviour_profile').agg({'mql_id':"count"}).rename(columns = {'mql_id':i}).merge(segment, how = "right", left_index = True, right_index = True) segment = segment.fillna(0)plt.figure(figsize = (14,4))snb.heatmap(segment, annot = True)plt.title("Heatmap of Lead Behaviour Profile and Business Segment", size = 15)
48.3% of lead behavior profiles are cat — steadiness, meaning that this person places emphasis on cooperation, sincerity, and dependability. Understand the characteristics of the leads can help Olist team to create relevant personas, making it easier for them to craft contents, messaging and stories to the targeted audience.
Business Type
#Figure 9segment2 = pd.DataFrame(index = ['reseller', 'manufacturer', 'other'])for i in segment_time.index: lead_profile = close[close['business_segment'] == i] segment2 = lead_profile.groupby('business_type').agg({'mql_id':"count"}).rename(columns = {'mql_id':i}).merge(segment2, how = "right", left_index = True, right_index = True)segment2 = segment2.fillna(0)plt.figure(figsize = (14,4))snb.heatmap(segment2, annot = True)
There are 2 business types: reseller and manufacturer. Reseller accounts for 69.7% of total MQLs. Therefore, there is no surprise when reseller appears the most among the business segments. However, in the home_decor segment, 56% are manufacturers.
Time for first orders
#Figure 10seller = pd.merge(order_item, orders[['order_id','order_approved_at']], how = "left", left_on = "order_id",right_on = "order_id")seller['order_approved_at'] = pd.to_datetime(seller['order_approved_at'])seller_first_order = seller.groupby('seller_id').agg({"order_approved_at":"min"})diff = pd.merge(close, seller_first_order, how = "inner", left_on = "seller_id", right_index = True)diff['first_order_time'] = diff['order_approved_at'] - pd.to_datetime(diff['won_date'])diff['first_order_time'] = diff["first_order_time"].dt.days#Histogramplt.figure()plt.hist(diff["first_order_time"], bins = 15, rwidth = 0.9)plt.title("Histogram of time for first order",size = 15)plt.xlabel("Days")plt.show()
Most sellers have to wait less than 50 days to have the first order from Olist since the day they agree to join Olist platform (figure 10).
Main business segments such as heath_beauty, home_decor, household_utilities, audio_video_electronics,...typically wait for 50–60 days to have the first order since won date. We also see some other segments such as food_drink, handcrafted and fashion_accessories have significantly longer time before its first order.
#Figure 11first_order_segment = diff.groupby("business_segment").agg({"first_order_time":"mean", "mql_id":"count"})fig = plt.figure(figsize = (10,4))ax = fig.add_subplot(111)ax2 = ax.twinx()ax.bar(first_order_segment.index, first_order_segment['first_order_time'])ax2.plot(first_order_segment.index, first_order_segment['mql_id'], color = "red")ax.set_ylabel('Days')ax2.set_ylabel('number of MQL')for tick in ax.get_xticklabels(): tick.set_rotation(90)plt.title("First order time by segments", size = 15)
Sales per segments:
#Figure 12product = pd.merge(product[["product_id", "product_category_name"]], category, how = "left", left_on = "product_category_name", right_on = "product_category_name")product_by_value = pd.merge(seller, product, how = "left", left_on = "product_id", right_on = "product_id")category_sales = product_by_value.groupby("product_category_name_english").agg({"price":"sum"})category_sales = category_sales.sort_values(by = ["price"], ascending = False)top10 = category_sales.iloc[:10]top10_category = top10.indexplt.figure(figsize = (10,6)) fancy_plot_2 = plt.subplot() for i in top10_category: order_category = product_by_value[product_by_value['product_category_name_english'] == i] order_category = order_category.set_index(pd.to_datetime(order_category['order_approved_at'])) order_category_agg = order_category.groupby(pd.Grouper(freq = "M")).agg({"price":"sum"}) fancy_plot_2.plot(order_category_agg.index, order_category_agg,'-x', label = i) fancy_plot_2.legend() plt.title("Sales by segment overtime", size =15)
Figure 12 is the top 10 product categories that have the highest sales from Olist. Since health_beauty, computer_accessories, furniture_devor, housewares, auto, and garden_tools are also the main business segments among MQLs, the sales values from these segments also on top. The only thing that surprises me is Watches. Though only have a small number of sellers from Watches segment, revenue from watches is really high in comparison with other segments.
Conclusion & Recommendation
We look at Olist seller side marketing from different angles: channels, messages (landing pages), targeting (business segment, lead behavior, business type,..), sales process (sales cycle, sales rep), closed deal performance to indicate the platform usage. Each angle can add value to how the team can optimize marketing campaigns.
Here are some detail recommendations:
Continue to work on SEO/Events to increase organic traffic
Learn from successful landing pages to create hypotheses for A/B testing. The goal is to replicate the successes in other landing pages
Sport leisure and watches segment can be developed more because Olist can capture high revenue from them
Leads are steadiness type. Olist can build customer persona around these type of people and crafting messaging/content to target these people.
Investigate in Home_decor segment why it attracts a lot of manufacturers. Can it be replicated in other segments?
About the author: I’m an MBA student at the University of California, Davis. I have a passion for Marketing Analytics, Modeling, Machine Learning, and Data Science. If you have any comment, feedback or questions, feel free to reach me at mapnguyen@ucdavis.edu or connect me on LinkedIn. Happy modeling!
|
[
{
"code": null,
"e": 641,
"s": 172,
"text": "This project focuses on conducting Exploratory Data Analysis (EDA) for B2B Marketing using Python. We will use data from Olist, an e-commerce platform that connects small and medium business with top Marketplaces in Brazil, as an example. Besides providing the method and the code, I also want to discuss the fundamentals in B2B Marketing and how these insights from EDA can help Olist to make a better marketing decision. All the Python code is provided on my GitHub."
},
{
"code": null,
"e": 1352,
"s": 641,
"text": "Olist is a platform that connects small and medium business with the marketplaces in Brazil (Extra, Shoptime, Walmart, Submarino, .etc) and helps the merchants to sell at these marketplaces. Unlike in some countries, the fast-growing e-commerce sector in Brazil is dominated by a number of large-size marketplaces rather than by a few marketplaces (Ex: Amazon and Ebay in the U.S.). Therefore, a merchant has the incentive to operate in multiple marketplaces to maximize their revenue. With the limitation in human resources as the main pain point, the merchant would want to use Olist to manage its sales channel in different marketplaces and streamline the stock management and the order fulfillment process."
},
{
"code": null,
"e": 1422,
"s": 1352,
"text": "With this B2B2C model, Olist’s marketing team have 2 main objectives:"
},
{
"code": null,
"e": 1512,
"s": 1422,
"text": "From the seller side, they want to increase the number of merchants using Olist platform."
},
{
"code": null,
"e": 1616,
"s": 1512,
"text": "From the buyer side, they want to maximize the e-commerce sales of the merchants on these marketplaces."
},
{
"code": null,
"e": 1834,
"s": 1616,
"text": "The scope of this analysis focuses more on the seller side (B2B) of Olist. With a given dataset, I will conduct the exploratory data analysis (EDA) that can bring some helpful insights into Olist’s B2B marketing team."
},
{
"code": null,
"e": 1869,
"s": 1834,
"text": "Marketing & Sales process for B2B:"
},
{
"code": null,
"e": 1935,
"s": 1869,
"text": "The datasets were obtained from Kaggle. You can download it here."
},
{
"code": null,
"e": 2190,
"s": 1935,
"text": "The first dataset has 4 variables with 8000 data points. The variables are MQL_id (marketing qualified leads), its first contact date, the landing page that captured the leads, and the lead origin (the channel that brings the leads to the landing pages)."
},
{
"code": null,
"e": 2690,
"s": 2190,
"text": "The second dataset contains 842 observations with 14 variables. Each observation is a won deal of Olist which consists of the mql_id of the merchant, seller_id (used in Olist platform), sdr_id and sr_id(the sales development representative and sales representative that were in charge of the deal), won_date, business segment, lead_type, lead_behaviour_profile, business_type, declared_monthly_revenue. Among these, 5 variables have too many Null values that they cannot bring value to the analysis."
},
{
"code": null,
"e": 2907,
"s": 2690,
"text": "Third dataset: Via Kaggle, Olist also donated their dataset about the demand side. We will use this to inform Olist marketers about the performance of the sellers, thus help them to improve the B2B marketing process."
},
{
"code": null,
"e": 3248,
"s": 2907,
"text": "The number of MQL: The MQL data is provided from 07/2017 to 06/2018, while the won MQL data is provided from 01/2018 to 12/2018. In 2017, MQLs that Olist marketing team generated is around 400 MQLs/month. In 2018, they boost the number to 1000–1400 leads per month. Regarding the won MQL, its peak was at 05/2018 with 200 won opportunities."
},
{
"code": null,
"e": 4053,
"s": 3248,
"text": "#Figure 1num_mql = mql.set_index(pd.to_datetime(mql[‘first_contact_date’]))num_mql = num_mql.groupby(pd.Grouper(freq = “M”)).count().drop(axis =1, columns = [‘first_contact_date’,“landing_page_id”, “origin”])num_won = close.set_index(pd.to_datetime(close[“won_date”]))num_won = num_won.groupby(pd.Grouper(freq = “M”)).count().drop(axis = 1, columns = [“seller_id”, “sdr_id”, “sr_id”,“business_segment”, “lead_type”, “lead_behaviour_profile”, “has_company”, “has_gtin”, “average_stock”, “business_type”,“declared_product_catalog_size”, “declared_monthly_revenue”, “won_date”])plt.figure(figsize = (8,6))plt.plot(num_mql.index, num_mql, \"-\", label = \"number of MQL\")plt.plot(num_won.index, num_won, \"-\", label = \"number of won MQL\")plt.legend()plt.title(\"Number of MQL\", size = 15)plt.savefig(\"NumMQL.png\")"
},
{
"code": null,
"e": 4393,
"s": 4053,
"text": "Channels: The majority of MQLs come from organic_search channel, followed by direct traffic and social. Other, other_publicities, referral and display are the sources that bring the least MQLs to Olist. The organic_search MQL is significantly increased in 2018–02 and declined after that. This can be the result of a big event/PR campaign."
},
{
"code": null,
"e": 5005,
"s": 4393,
"text": "#Figure 2mql_origin = mql.groupby(‘origin’).agg({‘mql_id’:”count”});print(mql_origin)origin = list(mql_origin.index)plt.figure(figsize = (10,8))fancy_plot = plt.subplot()for i in origin: channel = mql[mql[‘origin’] == i] channel = channel.set_index(pd.to_datetime(channel[‘first_contact_date’])) channel_agg = channel.groupby(pd.Grouper(freq = “M”)).count().drop(axis = 1, columns =[“first_contact_date”, “landing_page_id”, “origin”]) fancy_plot.plot(channel_agg.index, channel_agg, “-o”, label = i)fancy_plot.legend()plt.title(‘Number of MQL by channels overtime’, size = 15)plt.savefig(“channel-mql.png”)"
},
{
"code": null,
"e": 5513,
"s": 5005,
"text": "The conversion rates for these channels are varied. Organic_search, paid_search and direct traffic are the sources that enjoy the highest conversion rates (12.5%, 11.5%, and 11% respectively). Email, other_publicities and social have the lowest conversion rates (3%, 5%, 5.5% respectively). This means that SEO and Google Adwords are the most effective marketing channels for Olist. This result seems to be relevant to a couple of surveys illustrating the most effective marketing channel for B2B companies."
},
{
"code": null,
"e": 5529,
"s": 5513,
"text": "www.bizible.com"
},
{
"code": null,
"e": 6172,
"s": 5529,
"text": "#Figure 3origin_lost = data.groupby([‘origin’, ‘lost’]).count().drop(axis = 1, columns =[‘first_contact_date’,’landing_page_id’, “seller_id”, “sdr_id”, “sr_id”, “won_date”, “business_segment”, “lead_type”, “lead_behaviour_profile”, “has_company”, “has_gtin”, “average_stock”, “business_type”, “declared_product_catalog_size”, “declared_monthly_revenue”])percentage = []for i in origin: pct = origin_lost.loc[i].loc[False][0]/(origin_lost.loc[i].loc[True][0]+origin_lost.loc[i].loc[False][0]) percentage.append(pct)plt.figure(figsize = (6,4))plt.bar(origin, percentage)plt.xticks(rotation = 90)plt.ylabel(‘won rate’)plt.savefig(“won-rate.png”)"
},
{
"code": null,
"e": 6667,
"s": 6172,
"text": "Olist used 495 landing pages to capture MQLs. Even though the sales team is responsible for converting an MQL into a won opportunity, the marketing team can affect this likelihood from the top of the funnel by providing relevant messaging and benefits on the landing pages. From figure 4 above, there are 2 landing pages that have a very high number of MQLs (~800 MQLs) as well as very high won rate (~20%), meaning that 20% of the MQLs captured from these landing pages become Olist’s sellers."
},
{
"code": null,
"e": 7614,
"s": 6667,
"text": "#Figure 4mql_lp = mql.groupby(‘landing_page_id’).agg({‘mql_id’:”count”})mql_lp = mql_lp[mql_lp[‘mql_id’] > 30]data_lp = pd.merge(data, mql_lp, how = “inner”, left_on = “landing_page_id”, right_index = True)lp_lost = data_lp.groupby([‘landing_page_id’, ‘lost’]).agg({‘mql_id_x’:”count”})landing_page = list(mql_lp.index)percentage_lp = []landing_page_2 = []Num_mql = []for i in landing_page: if mql_lp.loc[i][0] == lp_lost.loc[i].loc[True][0]: lp_lost.drop([i]) else: pct = lp_lost.loc[i].loc[False][0]/(lp_lost.loc[i].loc[True][0]+lp_lost.loc[i].loc[False][0]) percentage_lp.append(pct) landing_page_2.append(i) Num_mql.append(mql_lp.loc[i][0])fig = plt.figure(figsize = (10,4))ax = fig.add_subplot(111)ax2 = ax.twinx()ax.bar(landing_page_2, percentage_lp)ax2.plot(landing_page_2, Num_mql, color = “red”)ax.set_ylabel(‘won rate’)ax2.set_ylabel(‘number of MQL’)for tick in ax.get_xticklabels(): tick.set_rotation(90)plt.savefig(“landing-page.png”)"
},
{
"code": null,
"e": 7712,
"s": 7614,
"text": "Learning from these landing pages can help Olist to replicate the success to other landing pages."
},
{
"code": null,
"e": 7937,
"s": 7712,
"text": "Targeting is very important in B2B marketing. There’re segments that will be very interested in Olist and vice versa. The following graph shows that by using the sales cycle (how long the sales process is) as the indication:"
},
{
"code": null,
"e": 8659,
"s": 7937,
"text": "#Figure 5data2 = pd.merge(mql, close, how = “right”, on = “mql_id”)data2[‘first_contact_date’] = pd.to_datetime(data2[‘first_contact_date’])data2[‘won_date’] = pd.to_datetime(data2[‘won_date’])data2[‘sales cycle’] = data2[‘won_date’] — data2[‘first_contact_date’]data2[‘sales cycle’] = data2[‘sales cycle’].dt.dayssegment_time = data2.groupby([‘business_segment’]).agg({“mql_id”:”count”, “sales cycle”:”mean”})fig = plt.figure(figsize = (10,4))ax = fig.add_subplot(111)ax2 = ax.twinx()ax.bar(segment_time.index, segment_time[‘sales cycle’])ax2.plot(segment_time.index, segment_time[‘mql_id’], color = “red”)ax.set_ylabel(‘Sales cycle’)ax2.set_ylabel(‘number of MQL’)for tick in ax.get_xticklabels(): tick.set_rotation(90)"
},
{
"code": null,
"e": 9121,
"s": 8659,
"text": "Business segments such as Home_decor, health_beauty, household_utilities, construction tool for house and garden, car accessories and electronics are the majorities of the sellers with the sales cycle typically around 50 days. Some segments that have a long sales cycle than others are perfume and watches. However, since these 2 segments only have a small number of MQLs (7 & 10) so Olist should probably wait for more MQLs to have a more accurate observation."
},
{
"code": null,
"e": 9296,
"s": 9121,
"text": "Regarding the Lead_type variable, Online_medium is the most popular type among Olist MQLs. There is no significant difference between the sales cycle of these business types."
},
{
"code": null,
"e": 9605,
"s": 9296,
"text": "#Figure 7fig = plt.figure(figsize = (10,4))ax = fig.add_subplot(111)ax2 = ax.twinx()ax.bar(lead_time.index, lead_time[‘sales cycle’])ax2.plot(lead_time.index, lead_time[‘mql_id’], color = “red”)ax.set_ylabel(‘Sales cycle’)ax2.set_ylabel(‘number of MQL’)for tick in ax.get_xticklabels(): tick.set_rotation(90)"
},
{
"code": null,
"e": 9906,
"s": 9605,
"text": "Olist can also base on the sales cycle to evaluate the performance of a Sales Rep. From Figure 7, It seems that the number of leads an SR has, the shorter the sales cycle. This can be explained that an experienced sales rep (more MQLs) will perform better (shorter sales length) than a new sales rep."
},
{
"code": null,
"e": 10077,
"s": 9906,
"text": "The table below is the description of each behavior profile, based on DiSC, a behavior assessment tool developed from DiSC theory of psychologist William Moulton Marston."
},
{
"code": null,
"e": 10686,
"s": 10077,
"text": "#Figure 8segment = pd.DataFrame(index = ['cat','eagle', 'wolf', 'shark'])for i in segment_time.index: lead_profile = close[close['business_segment'] == i] segment = lead_profile.groupby('lead_behaviour_profile').agg({'mql_id':\"count\"}).rename(columns = {'mql_id':i}).merge(segment, how = \"right\", left_index = True, right_index = True) segment = segment.fillna(0)plt.figure(figsize = (14,4))snb.heatmap(segment, annot = True)plt.title(\"Heatmap of Lead Behaviour Profile and Business Segment\", size = 15)"
},
{
"code": null,
"e": 11013,
"s": 10686,
"text": "48.3% of lead behavior profiles are cat — steadiness, meaning that this person places emphasis on cooperation, sincerity, and dependability. Understand the characteristics of the leads can help Olist team to create relevant personas, making it easier for them to craft contents, messaging and stories to the targeted audience."
},
{
"code": null,
"e": 11027,
"s": 11013,
"text": "Business Type"
},
{
"code": null,
"e": 11460,
"s": 11027,
"text": "#Figure 9segment2 = pd.DataFrame(index = ['reseller', 'manufacturer', 'other'])for i in segment_time.index: lead_profile = close[close['business_segment'] == i] segment2 = lead_profile.groupby('business_type').agg({'mql_id':\"count\"}).rename(columns = {'mql_id':i}).merge(segment2, how = \"right\", left_index = True, right_index = True)segment2 = segment2.fillna(0)plt.figure(figsize = (14,4))snb.heatmap(segment2, annot = True)"
},
{
"code": null,
"e": 11709,
"s": 11460,
"text": "There are 2 business types: reseller and manufacturer. Reseller accounts for 69.7% of total MQLs. Therefore, there is no surprise when reseller appears the most among the business segments. However, in the home_decor segment, 56% are manufacturers."
},
{
"code": null,
"e": 11731,
"s": 11709,
"text": "Time for first orders"
},
{
"code": null,
"e": 12436,
"s": 11731,
"text": "#Figure 10seller = pd.merge(order_item, orders[['order_id','order_approved_at']], how = \"left\", left_on = \"order_id\",right_on = \"order_id\")seller['order_approved_at'] = pd.to_datetime(seller['order_approved_at'])seller_first_order = seller.groupby('seller_id').agg({\"order_approved_at\":\"min\"})diff = pd.merge(close, seller_first_order, how = \"inner\", left_on = \"seller_id\", right_index = True)diff['first_order_time'] = diff['order_approved_at'] - pd.to_datetime(diff['won_date'])diff['first_order_time'] = diff[\"first_order_time\"].dt.days#Histogramplt.figure()plt.hist(diff[\"first_order_time\"], bins = 15, rwidth = 0.9)plt.title(\"Histogram of time for first order\",size = 15)plt.xlabel(\"Days\")plt.show()"
},
{
"code": null,
"e": 12576,
"s": 12436,
"text": "Most sellers have to wait less than 50 days to have the first order from Olist since the day they agree to join Olist platform (figure 10)."
},
{
"code": null,
"e": 12894,
"s": 12576,
"text": "Main business segments such as heath_beauty, home_decor, household_utilities, audio_video_electronics,...typically wait for 50–60 days to have the first order since won date. We also see some other segments such as food_drink, handcrafted and fashion_accessories have significantly longer time before its first order."
},
{
"code": null,
"e": 13402,
"s": 12894,
"text": "#Figure 11first_order_segment = diff.groupby(\"business_segment\").agg({\"first_order_time\":\"mean\", \"mql_id\":\"count\"})fig = plt.figure(figsize = (10,4))ax = fig.add_subplot(111)ax2 = ax.twinx()ax.bar(first_order_segment.index, first_order_segment['first_order_time'])ax2.plot(first_order_segment.index, first_order_segment['mql_id'], color = \"red\")ax.set_ylabel('Days')ax2.set_ylabel('number of MQL')for tick in ax.get_xticklabels(): tick.set_rotation(90)plt.title(\"First order time by segments\", size = 15)"
},
{
"code": null,
"e": 13422,
"s": 13402,
"text": "Sales per segments:"
},
{
"code": null,
"e": 14478,
"s": 13422,
"text": "#Figure 12product = pd.merge(product[[\"product_id\", \"product_category_name\"]], category, how = \"left\", left_on = \"product_category_name\", right_on = \"product_category_name\")product_by_value = pd.merge(seller, product, how = \"left\", left_on = \"product_id\", right_on = \"product_id\")category_sales = product_by_value.groupby(\"product_category_name_english\").agg({\"price\":\"sum\"})category_sales = category_sales.sort_values(by = [\"price\"], ascending = False)top10 = category_sales.iloc[:10]top10_category = top10.indexplt.figure(figsize = (10,6)) fancy_plot_2 = plt.subplot() for i in top10_category: order_category = product_by_value[product_by_value['product_category_name_english'] == i] order_category = order_category.set_index(pd.to_datetime(order_category['order_approved_at'])) order_category_agg = order_category.groupby(pd.Grouper(freq = \"M\")).agg({\"price\":\"sum\"}) fancy_plot_2.plot(order_category_agg.index, order_category_agg,'-x', label = i) fancy_plot_2.legend() plt.title(\"Sales by segment overtime\", size =15)"
},
{
"code": null,
"e": 14935,
"s": 14478,
"text": "Figure 12 is the top 10 product categories that have the highest sales from Olist. Since health_beauty, computer_accessories, furniture_devor, housewares, auto, and garden_tools are also the main business segments among MQLs, the sales values from these segments also on top. The only thing that surprises me is Watches. Though only have a small number of sellers from Watches segment, revenue from watches is really high in comparison with other segments."
},
{
"code": null,
"e": 14963,
"s": 14935,
"text": "Conclusion & Recommendation"
},
{
"code": null,
"e": 15295,
"s": 14963,
"text": "We look at Olist seller side marketing from different angles: channels, messages (landing pages), targeting (business segment, lead behavior, business type,..), sales process (sales cycle, sales rep), closed deal performance to indicate the platform usage. Each angle can add value to how the team can optimize marketing campaigns."
},
{
"code": null,
"e": 15333,
"s": 15295,
"text": "Here are some detail recommendations:"
},
{
"code": null,
"e": 15392,
"s": 15333,
"text": "Continue to work on SEO/Events to increase organic traffic"
},
{
"code": null,
"e": 15528,
"s": 15392,
"text": "Learn from successful landing pages to create hypotheses for A/B testing. The goal is to replicate the successes in other landing pages"
},
{
"code": null,
"e": 15633,
"s": 15528,
"text": "Sport leisure and watches segment can be developed more because Olist can capture high revenue from them"
},
{
"code": null,
"e": 15776,
"s": 15633,
"text": "Leads are steadiness type. Olist can build customer persona around these type of people and crafting messaging/content to target these people."
},
{
"code": null,
"e": 15890,
"s": 15776,
"text": "Investigate in Home_decor segment why it attracts a lot of manufacturers. Can it be replicated in other segments?"
}
] |
How do I remove a particular element from an array in JavaScript
|
To remove an element from an array, use the splice() method. JavaScript array splice() method changes the content of an array, adding new elements while removing old elements.
The following are the parameters −
index − Index at which to start changing the array.
index − Index at which to start changing the array.
howMany − An integer indicating the number of old array elements to remove. If howMany is a 0, then no elements are removed.
howMany − An integer indicating the number of old array elements to remove. If howMany is a 0, then no elements are removed.
element1, ..., elementN − The elements adds to the array. If you don't specify any elements, splice simply removes the elements from the array.
element1, ..., elementN − The elements adds to the array. If you don't specify any elements, splice simply removes the elements from the array.
You can try to run the following code to learn how to add and remove individual elements in a JavaScript array −
<html>
<head>
<title>JavaScript Array splice Method</title>
</head>
<body>
<script>
var arr = ["orange", "mango", "banana", "sugar", "tea"];
var removed = arr.splice(2, 0, "water");
document.write("After adding 1: " + arr );
document.write("<br />removed is: " + removed);
removed = arr.splice(3, 1);
document.write("<br />After adding 1: " + arr );
document.write("<br />removed is: " + removed);
</script>
</body>
</html>
After adding 1: orange,mango,water,banana,sugar,tea
removed is:
After adding 1: orange,mango,water,sugar,tea
removed is: banana
|
[
{
"code": null,
"e": 1238,
"s": 1062,
"text": "To remove an element from an array, use the splice() method. JavaScript array splice() method changes the content of an array, adding new elements while removing old elements."
},
{
"code": null,
"e": 1273,
"s": 1238,
"text": "The following are the parameters −"
},
{
"code": null,
"e": 1325,
"s": 1273,
"text": "index − Index at which to start changing the array."
},
{
"code": null,
"e": 1377,
"s": 1325,
"text": "index − Index at which to start changing the array."
},
{
"code": null,
"e": 1502,
"s": 1377,
"text": "howMany − An integer indicating the number of old array elements to remove. If howMany is a 0, then no elements are removed."
},
{
"code": null,
"e": 1627,
"s": 1502,
"text": "howMany − An integer indicating the number of old array elements to remove. If howMany is a 0, then no elements are removed."
},
{
"code": null,
"e": 1771,
"s": 1627,
"text": "element1, ..., elementN − The elements adds to the array. If you don't specify any elements, splice simply removes the elements from the array."
},
{
"code": null,
"e": 1915,
"s": 1771,
"text": "element1, ..., elementN − The elements adds to the array. If you don't specify any elements, splice simply removes the elements from the array."
},
{
"code": null,
"e": 2028,
"s": 1915,
"text": "You can try to run the following code to learn how to add and remove individual elements in a JavaScript array −"
},
{
"code": null,
"e": 2555,
"s": 2028,
"text": "<html>\n <head>\n <title>JavaScript Array splice Method</title>\n </head>\n \n <body>\n <script>\n var arr = [\"orange\", \"mango\", \"banana\", \"sugar\", \"tea\"];\n\n var removed = arr.splice(2, 0, \"water\");\n document.write(\"After adding 1: \" + arr );\n document.write(\"<br />removed is: \" + removed);\n\n removed = arr.splice(3, 1);\n document.write(\"<br />After adding 1: \" + arr );\n document.write(\"<br />removed is: \" + removed);\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 2685,
"s": 2555,
"text": "After adding 1: orange,mango,water,banana,sugar,tea\nremoved is: \nAfter adding 1: orange,mango,water,sugar,tea\nremoved is: banana\n"
}
] |
Describe about net income approach in capital structure.
|
Capital structure plays an important role in value of a company. Different companies have different
capital structures like some have capital based on debt, some have based on equity and some have a
mixed or combination of both in their financial mix.
Durand proposed net income approach and he states that change in cost of capital and valuation of
company will change, if there a change in financial leverage. Capital structure is relevant to valuation of a firm. Increase in financial leverage leads to increase in weighted average cost of capital (WACC) and value of firm will increase.
Market value of equity shares depends on amount available after paying interest on debt. This approach prepositions that market value depends on the amount available for equity shareholders. Net income and cost of capital depends on use of Debt in capital structure, which had an impact on equity shares and market value.
NI = NOI – I
Where, NI = net income, NOI = net operating income and I = interest on debt.
Assumptions related to net income are as follows −
No taxes
No taxes
Cost of equity > cost of debt.
Cost of equity > cost of debt.
Both debt and equity capitalisations are constant.
Both debt and equity capitalisations are constant.
Debt proportion is independent of investors risk.
Debt proportion is independent of investors risk.
Dividend pay-out ratio is 1.
Dividend pay-out ratio is 1.
V = E + D
Where, V = market value (firm), E = market value (Equity) + Market value (Debt)
E = equity shareholder’s income/ cost of equity
D = interest rate on debt/ cost of Debt
Cost of capital = NOI/V
Degree of financial leverage = D/V
Where, NOI = Net operating income.
Disadvantages of net income are as follows −
Corporate taxes are not considered.
Corporate taxes are not considered.
It has constant cost of debt (interest rate depends on fund providers).
It has constant cost of debt (interest rate depends on fund providers).
Financial risk increases with increase debt.
Financial risk increases with increase debt.
Financial leverage increases with increase in equity capitalisation.
Financial leverage increases with increase in equity capitalisation.
|
[
{
"code": null,
"e": 1314,
"s": 1062,
"text": "Capital structure plays an important role in value of a company. Different companies have different\ncapital structures like some have capital based on debt, some have based on equity and some have a\nmixed or combination of both in their financial mix."
},
{
"code": null,
"e": 1653,
"s": 1314,
"text": "Durand proposed net income approach and he states that change in cost of capital and valuation of\ncompany will change, if there a change in financial leverage. Capital structure is relevant to valuation of a firm. Increase in financial leverage leads to increase in weighted average cost of capital (WACC) and value of firm will increase."
},
{
"code": null,
"e": 1975,
"s": 1653,
"text": "Market value of equity shares depends on amount available after paying interest on debt. This approach prepositions that market value depends on the amount available for equity shareholders. Net income and cost of capital depends on use of Debt in capital structure, which had an impact on equity shares and market value."
},
{
"code": null,
"e": 1988,
"s": 1975,
"text": "NI = NOI – I"
},
{
"code": null,
"e": 2065,
"s": 1988,
"text": "Where, NI = net income, NOI = net operating income and I = interest on debt."
},
{
"code": null,
"e": 2116,
"s": 2065,
"text": "Assumptions related to net income are as follows −"
},
{
"code": null,
"e": 2125,
"s": 2116,
"text": "No taxes"
},
{
"code": null,
"e": 2134,
"s": 2125,
"text": "No taxes"
},
{
"code": null,
"e": 2165,
"s": 2134,
"text": "Cost of equity > cost of debt."
},
{
"code": null,
"e": 2196,
"s": 2165,
"text": "Cost of equity > cost of debt."
},
{
"code": null,
"e": 2247,
"s": 2196,
"text": "Both debt and equity capitalisations are constant."
},
{
"code": null,
"e": 2298,
"s": 2247,
"text": "Both debt and equity capitalisations are constant."
},
{
"code": null,
"e": 2348,
"s": 2298,
"text": "Debt proportion is independent of investors risk."
},
{
"code": null,
"e": 2398,
"s": 2348,
"text": "Debt proportion is independent of investors risk."
},
{
"code": null,
"e": 2427,
"s": 2398,
"text": "Dividend pay-out ratio is 1."
},
{
"code": null,
"e": 2456,
"s": 2427,
"text": "Dividend pay-out ratio is 1."
},
{
"code": null,
"e": 2466,
"s": 2456,
"text": "V = E + D"
},
{
"code": null,
"e": 2546,
"s": 2466,
"text": "Where, V = market value (firm), E = market value (Equity) + Market value (Debt)"
},
{
"code": null,
"e": 2594,
"s": 2546,
"text": "E = equity shareholder’s income/ cost of equity"
},
{
"code": null,
"e": 2634,
"s": 2594,
"text": "D = interest rate on debt/ cost of Debt"
},
{
"code": null,
"e": 2693,
"s": 2634,
"text": "Cost of capital = NOI/V\nDegree of financial leverage = D/V"
},
{
"code": null,
"e": 2728,
"s": 2693,
"text": "Where, NOI = Net operating income."
},
{
"code": null,
"e": 2773,
"s": 2728,
"text": "Disadvantages of net income are as follows −"
},
{
"code": null,
"e": 2809,
"s": 2773,
"text": "Corporate taxes are not considered."
},
{
"code": null,
"e": 2845,
"s": 2809,
"text": "Corporate taxes are not considered."
},
{
"code": null,
"e": 2917,
"s": 2845,
"text": "It has constant cost of debt (interest rate depends on fund providers)."
},
{
"code": null,
"e": 2989,
"s": 2917,
"text": "It has constant cost of debt (interest rate depends on fund providers)."
},
{
"code": null,
"e": 3034,
"s": 2989,
"text": "Financial risk increases with increase debt."
},
{
"code": null,
"e": 3079,
"s": 3034,
"text": "Financial risk increases with increase debt."
},
{
"code": null,
"e": 3148,
"s": 3079,
"text": "Financial leverage increases with increase in equity capitalisation."
},
{
"code": null,
"e": 3217,
"s": 3148,
"text": "Financial leverage increases with increase in equity capitalisation."
}
] |
Batch Script - TYPE
|
This batch command prints the content of a file or files to the output.
TYPE [filename]
Where filename is the file whose contents need to be displayed.
@echo off
TYPE C:\tp\lists.txt
The contents of the file lists.txt will be displayed to the command prompt.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2241,
"s": 2169,
"text": "This batch command prints the content of a file or files to the output."
},
{
"code": null,
"e": 2258,
"s": 2241,
"text": "TYPE [filename]\n"
},
{
"code": null,
"e": 2322,
"s": 2258,
"text": "Where filename is the file whose contents need to be displayed."
},
{
"code": null,
"e": 2354,
"s": 2322,
"text": "@echo off \nTYPE C:\\tp\\lists.txt"
},
{
"code": null,
"e": 2430,
"s": 2354,
"text": "The contents of the file lists.txt will be displayed to the command prompt."
},
{
"code": null,
"e": 2437,
"s": 2430,
"text": " Print"
},
{
"code": null,
"e": 2448,
"s": 2437,
"text": " Add Notes"
}
] |
Batch Script - Arrays
|
Arrays are not specifically defined as a type in Batch Script but can be implemented. The following things need to be noted when arrays are implemented in Batch Script.
Each element of the array needs to be defined with the set command.
The ‘for’ loop would be required to iterate through the values of the array.
An array is created by using the following set command.
set a[0]=1
Where 0 is the index of the array and 1 is the value assigned to the first element of the array.
Another way to implement arrays is to define a list of values and iterate through the list of values. The following example show how this can be implemented.
@echo off
set list=1 2 3 4
(for %%a in (%list%) do (
echo %%a
))
The above command produces the following output.
1
2
3
4
You can retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array.
@echo off
set a[0]=1
echo %a[0]%
In this example, the index starts from 0 which means the first element can be accessed using index as 0, the second element can be accessed using index as 1 and so on. Let's check the following example to create, initialize and access arrays −
@echo off
set a[0]=1
set a[1]=2
set a[2]=3
echo The first element of the array is %a[0]%
echo The second element of the array is %a[1]%
echo The third element of the array is %a[2]%
The above command produces the following output.
The first element of the array is 1
The second element of the array is 2
The third element of the array is 3
To add an element to the end of the array, you can use the set element along with the last index of the array element.
@echo off
set a[0]=1
set a[1]=2
set a[2]=3
Rem Adding an element at the end of an array
Set a[3]=4
echo The last element of the array is %a[3]%
The above command produces the following output.
The last element of the array is 4
You can modify an existing element of an Array by assigning a new value at a given index as shown in the following example −
@echo off
set a[0]=1
set a[1]=2
set a[2]=3
Rem Setting the new value for the second element of the array
Set a[1]=5
echo The new value of the second element of the array is %a[1]%
The above command produces the following output.
The new value of the second element of the array is 5
Iterating over an array is achieved by using the ‘for’ loop and going through each element of the array. The following example shows a simple way that an array can be implemented.
@echo off
setlocal enabledelayedexpansion
set topic[0]=comments
set topic[1]=variables
set topic[2]=Arrays
set topic[3]=Decision making
set topic[4]=Time and date
set topic[5]=Operators
for /l %%n in (0,1,5) do (
echo !topic[%%n]!
)
Following things need to be noted about the above program −
Each element of the array needs to be specifically defined using the set command.
Each element of the array needs to be specifically defined using the set command.
The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array.
The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array.
The above command produces the following output.
Comments
variables
Arrays
Decision making
Time and date
Operators
The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array.
@echo off
set Arr[0]=1
set Arr[1]=2
set Arr[2]=3
set Arr[3]=4
set "x = 0"
:SymLoop
if defined Arr[%x%] (
call echo %%Arr[%x%]%%
set /a "x+=1"
GOTO :SymLoop
)
echo "The length of the array is" %x%
Output The above command produces the following output.
1
2
3
4
"The length of the array is" 4
Structures can also be implemented in batch files using a little bit of an extra coding for implementation. The following example shows how this can be achieved.
@echo off
set obj[0].Name=Joe
set obj[0].ID=1
set obj[1].Name=Mark
set obj[1].ID=2
set obj[2].Name=Mohan
set obj[2].ID=3
FOR /L %%i IN (0 1 2) DO (
call echo Name = %%obj[%%i].Name%%
call echo Value = %%obj[%%i].ID%%
)
The following key things need to be noted about the above code.
Each variable defined using the set command has 2 values associated with each index of the array.
Each variable defined using the set command has 2 values associated with each index of the array.
The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3.
The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3.
We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code.
We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code.
We are able to access each element of the structure using the obj[%i%] notation.
We are able to access each element of the structure using the obj[%i%] notation.
The above command produces the following output.
Name=Joe
Value=1
Name=Mark
Value=2
Name=Mohan
Value=3
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2338,
"s": 2169,
"text": "Arrays are not specifically defined as a type in Batch Script but can be implemented. The following things need to be noted when arrays are implemented in Batch Script."
},
{
"code": null,
"e": 2406,
"s": 2338,
"text": "Each element of the array needs to be defined with the set command."
},
{
"code": null,
"e": 2483,
"s": 2406,
"text": "The ‘for’ loop would be required to iterate through the values of the array."
},
{
"code": null,
"e": 2539,
"s": 2483,
"text": "An array is created by using the following set command."
},
{
"code": null,
"e": 2551,
"s": 2539,
"text": "set a[0]=1\n"
},
{
"code": null,
"e": 2648,
"s": 2551,
"text": "Where 0 is the index of the array and 1 is the value assigned to the first element of the array."
},
{
"code": null,
"e": 2806,
"s": 2648,
"text": "Another way to implement arrays is to define a list of values and iterate through the list of values. The following example show how this can be implemented."
},
{
"code": null,
"e": 2878,
"s": 2806,
"text": "@echo off \nset list=1 2 3 4 \n(for %%a in (%list%) do ( \n echo %%a \n))"
},
{
"code": null,
"e": 2927,
"s": 2878,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2936,
"s": 2927,
"text": "1\n2\n3\n4\n"
},
{
"code": null,
"e": 3119,
"s": 2936,
"text": "You can retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array."
},
{
"code": null,
"e": 3154,
"s": 3119,
"text": "@echo off \nset a[0]=1 \necho %a[0]%"
},
{
"code": null,
"e": 3398,
"s": 3154,
"text": "In this example, the index starts from 0 which means the first element can be accessed using index as 0, the second element can be accessed using index as 1 and so on. Let's check the following example to create, initialize and access arrays −"
},
{
"code": null,
"e": 3585,
"s": 3398,
"text": "@echo off\nset a[0]=1 \nset a[1]=2 \nset a[2]=3 \necho The first element of the array is %a[0]% \necho The second element of the array is %a[1]% \necho The third element of the array is %a[2]%"
},
{
"code": null,
"e": 3634,
"s": 3585,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 3746,
"s": 3634,
"text": "The first element of the array is 1 \nThe second element of the array is 2 \nThe third element of the array is 3\n"
},
{
"code": null,
"e": 3865,
"s": 3746,
"text": "To add an element to the end of the array, you can use the set element along with the last index of the array element."
},
{
"code": null,
"e": 4017,
"s": 3865,
"text": "@echo off \nset a[0]=1 \nset a[1]=2 \nset a[2]=3 \nRem Adding an element at the end of an array \nSet a[3]=4 \necho The last element of the array is %a[3]%"
},
{
"code": null,
"e": 4066,
"s": 4017,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 4102,
"s": 4066,
"text": "The last element of the array is 4\n"
},
{
"code": null,
"e": 4227,
"s": 4102,
"text": "You can modify an existing element of an Array by assigning a new value at a given index as shown in the following example −"
},
{
"code": null,
"e": 4414,
"s": 4227,
"text": "@echo off \nset a[0]=1 \nset a[1]=2 \nset a[2]=3 \nRem Setting the new value for the second element of the array \nSet a[1]=5 \necho The new value of the second element of the array is %a[1]%"
},
{
"code": null,
"e": 4463,
"s": 4414,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 4518,
"s": 4463,
"text": "The new value of the second element of the array is 5\n"
},
{
"code": null,
"e": 4698,
"s": 4518,
"text": "Iterating over an array is achieved by using the ‘for’ loop and going through each element of the array. The following example shows a simple way that an array can be implemented."
},
{
"code": null,
"e": 4945,
"s": 4698,
"text": "@echo off \nsetlocal enabledelayedexpansion \nset topic[0]=comments \nset topic[1]=variables \nset topic[2]=Arrays \nset topic[3]=Decision making \nset topic[4]=Time and date \nset topic[5]=Operators \n\nfor /l %%n in (0,1,5) do ( \n echo !topic[%%n]! \n)"
},
{
"code": null,
"e": 5005,
"s": 4945,
"text": "Following things need to be noted about the above program −"
},
{
"code": null,
"e": 5087,
"s": 5005,
"text": "Each element of the array needs to be specifically defined using the set command."
},
{
"code": null,
"e": 5169,
"s": 5087,
"text": "Each element of the array needs to be specifically defined using the set command."
},
{
"code": null,
"e": 5270,
"s": 5169,
"text": "The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array."
},
{
"code": null,
"e": 5371,
"s": 5270,
"text": "The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array."
},
{
"code": null,
"e": 5420,
"s": 5371,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 5492,
"s": 5420,
"text": "Comments \nvariables \nArrays \nDecision making \nTime and date \nOperators\n"
},
{
"code": null,
"e": 5656,
"s": 5492,
"text": "The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array."
},
{
"code": null,
"e": 5872,
"s": 5656,
"text": "@echo off \nset Arr[0]=1 \nset Arr[1]=2 \nset Arr[2]=3 \nset Arr[3]=4 \nset \"x = 0\" \n:SymLoop \n\nif defined Arr[%x%] ( \n call echo %%Arr[%x%]%% \n set /a \"x+=1\"\n GOTO :SymLoop \n)\necho \"The length of the array is\" %x%"
},
{
"code": null,
"e": 5928,
"s": 5872,
"text": "Output The above command produces the following output."
},
{
"code": null,
"e": 5968,
"s": 5928,
"text": "1\n2\n3\n4\n\"The length of the array is\" 4\n"
},
{
"code": null,
"e": 6130,
"s": 5968,
"text": "Structures can also be implemented in batch files using a little bit of an extra coding for implementation. The following example shows how this can be achieved."
},
{
"code": null,
"e": 6363,
"s": 6130,
"text": "@echo off \nset obj[0].Name=Joe \nset obj[0].ID=1 \nset obj[1].Name=Mark \nset obj[1].ID=2 \nset obj[2].Name=Mohan \nset obj[2].ID=3 \nFOR /L %%i IN (0 1 2) DO (\n call echo Name = %%obj[%%i].Name%%\n call echo Value = %%obj[%%i].ID%%\n)"
},
{
"code": null,
"e": 6427,
"s": 6363,
"text": "The following key things need to be noted about the above code."
},
{
"code": null,
"e": 6525,
"s": 6427,
"text": "Each variable defined using the set command has 2 values associated with each index of the array."
},
{
"code": null,
"e": 6623,
"s": 6525,
"text": "Each variable defined using the set command has 2 values associated with each index of the array."
},
{
"code": null,
"e": 6733,
"s": 6623,
"text": "The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3."
},
{
"code": null,
"e": 6843,
"s": 6733,
"text": "The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3."
},
{
"code": null,
"e": 6970,
"s": 6843,
"text": "We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code."
},
{
"code": null,
"e": 7097,
"s": 6970,
"text": "We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code."
},
{
"code": null,
"e": 7178,
"s": 7097,
"text": "We are able to access each element of the structure using the obj[%i%] notation."
},
{
"code": null,
"e": 7259,
"s": 7178,
"text": "We are able to access each element of the structure using the obj[%i%] notation."
},
{
"code": null,
"e": 7308,
"s": 7259,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 7368,
"s": 7308,
"text": "Name=Joe \nValue=1 \nName=Mark \nValue=2 \nName=Mohan \nValue=3\n"
},
{
"code": null,
"e": 7375,
"s": 7368,
"text": " Print"
},
{
"code": null,
"e": 7386,
"s": 7375,
"text": " Add Notes"
}
] |
Google AMP - Form
|
This chapter explains how to work with form in Google AMP.
Note that forms tag remains the same as in standard HTML. AMP has added special restriction on the use of forms due to which we need to add the amp-form JavaScript file to work with forms.
<script async custom-element = "amp-form"
src = "https://cdn.ampproject.org/v0/ampform-0.1.js"></script>
To use forms in a AMP page, we need to include the above script in the .html file. The amp-form JavaScript file supports http and xmlhttprequest for form submission. Using HTTP request the page is reloaded and with xmlhttprequest it does not reload the page acts like ajax request.
For xmlhttprequest :
<form method = "post" class = "p2" action-xhr = "submitform.php" target = "_top">
//Input fields here
</form>
For http :
<form method = "post" class = "p2" action = "submitform.php" target = "_top">
//Input fields here
</form>
Amp-form provides special attributes i.e, submit-error and submit-success to handle error and success when form is submitted.
Example
An example for amp-form is shown below −
<!doctype html>
<html amp lang = "en">
<head>
<meta charset = "utf-8">
<script async src = "https://cdn.ampproject.org/v0.js"></script>
<title>Google AMP - Form</title>
<link rel = "canonical" href = "ampform.html">
<meta name = "viewport" conten t = "width = device-width,
minimum-scale = 1,initialscale = 1">
<style amp-boilerplate>
body{
-webkit-animation:
-amp-start 8s steps(1,end) 0s1 normal both;-moz-animation:
-amp-start 8s steps(1,end) 0s 1 normal both;-msanimation:
-amp-start 8s steps(1,end) 0s 1 normal both;animation:
-amp-start 8s steps(1,end) 0s 1 normal both
}
@-webkit-keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}@-o-keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}@keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}
</style>
<noscript>
<style amp-boilerplate>
body{
-webkit-animation:none;
-moz-animation:none;
-msanimation:none;
animation:none
}
</style>
</noscript>
<script async custom-element = "amp-form"
src = "https://cdn.ampproject.org/v0/amp-form-0.1.js">
</script>
<script async custom-template = "amp-mustache"
src = "https://cdn.ampproject.org/v0/amp-mustache-0.2.js">
</script>
<style amp-custom>
form.amp-form-submit-success [submit-success],
form.amp-form-submit-error [submit-error]{
margin-top: 16px;
}
form.amp-form-submit-success [submit-success] {
color: white;
background-color:gray;
}
form.amp-form-submit-error [submit-error] {
color: red;
}
form.amp-form-submit-success.hide-inputs > input {
display: none;
}
</style>
</head>
<body>
<h3>Google AMP - Form</h3>
<form method = "post"
class = "p2"
action-xhr = "submitform.php"
target = "_top">
<p>AMP - Form Example</p>
<div>
<input type = "text" name = "name" placeholder = "Enter
Name" required><br/><br/>
<input type = "email" name = "email"
placeholder = "Enter Email" required>
<br/>
<br/>
</div>
<input type = "submit" value = "Submit">
<div submit-success>
<template type = "amp-mustache">
Form Submitted! Thanks {{name}}.
</template>
</div>
<div submit-error>
<template type = "amp-mustache">
Error! {{name}}, please try again.
</template>
</div>
</form>
</body>
</html>
Output
When you executed the code shown above, you will find the result as shown below −
Now, enter the details and click the Submit button. The output screen displayed is as follows −
Observe that we have used amp-mustache for data-binding. The form is using action-xhr ie xmlhttprequest to submit form. We have used submitform.php file which returns the data in json format.
<form method = "post" class = "p2" action-xhr = "submitform.php"
target = "_top">
</form>
submitform.php
<?php
if(!empty($_POST)){
$domain_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
header("Content-type: application/json");
header("AMP-Access-Control-Allow-Source-Origin: " . $domain_url);
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
$myJSON = json_encode($_POST);
echo $myJSON;
}
?>
For the form to work using xmlhttprequest, we need to add headers as per the CORS specification. Details of response headers added to submitform.php are shown below −
For the form to work, we need to add headers such as access-control-expose-headers with value AMP-Access-Control-Allow-Source-Origin and amp-access-controlallow- source-origin −http://localhost:8080.
Note that we are using a php file and apache server. In php file, we have added the required headers as shown below −
<?php
if(!empty($_POST)){
$domain_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
header("Content-type: application/json");
header("AMP-Access-Control-Allow-Source-Origin: " . $domain_url);
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
$myJSON = json_encode($_POST);
echo $myJSON;
}
?
?>
In case we use a normal http request the page will get reloaded as shown below −
For http request we have used form as follows −
<form method = "GET" class = "p2" action = "submitform.php"
target = "_top">
</form>
Example
Observe the following code for a better understanding −
<!doctype html>
<html amp lang = "en">
<head>
<meta charset = "utf-8">
<script async src = "https://cdn.ampproject.org/v0.js"></script>
<title>Google AMP - Form</title>
<link rel = "canonical" href = "ampform.html">
<meta name = "viewport" content = "width = device-width,minimum-scale = 1,initialscale = 1">
<style amp-boilerplate>
body{
-webkit-animation:
-amp-start 8s steps(1,end) 0s1 normal both;-moz-animation:
-amp-start 8s steps(1,end) 0s 1 normal both;-msanimation:
-amp-start 8s steps(1,end) 0s 1 normal both;animation:
-amp-start 8s steps(1,end) 0s 1 normal both
}
@-webkit-keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}@-o-keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}@keyframes
-ampstart{from{visibility:hidden}to{visibility:visible}}
</style>
<noscript>
<style amp-boilerplate>
body {
-webkit-animation:none;
-moz-animation:none;
-msanimation:none;
animation:none}
>/style>
</noscript>
<script async custom-element = "amp-form"
src = "https://cdn.ampproject.org/v0/amp-form-0.1.js">
</script>
<script async custom-template = "amp-mustache"
src = "https://cdn.ampproject.org/v0/amp-mustache-0.2.js">
</script>
<style amp-custom>
form.amp-form-submit-success [submit-success],
form.amp-form-submit-error [submit-error]{
margin-top: 16px;
}
form.amp-form-submit-success [submit-success] {
color: white;
background-color:gray;
}
form.amp-form-submit-error [submit-error] {
color: red;
}
form.amp-form-submit-success.hide-inputs >
input {
display: none;
}
</style>
</head>
<body>
<h3>Google AMP - Form</h3>
<form method = "GET" class = "p2" action = "submitform.php" target = "_top">
<p>AMP - Form Example</p>
<div>
<input type = "text" name = "name" placeholder = "Enter Name" required>
<br/>
<br/>
<input type = "email" name = "email" placeholder = "Enter Email" required>
<br/>
<br/>
<div>
<input type = "submit" value = "Submit">
<div submit-success>
<template type = "amp-mustache">
Form Submitted! Thanks {{name}}.
</template>
</div>
<div submit-error>
<template type = "amp-mustache">
Error! {{name}}, please try again.
</template>
</div>
</form>
</body>
</html>
Output
When you executed the code shown above, you will find the result as shown below −
20 Lectures
2.5 hours
Asif Hussain
7 Lectures
1 hours
Aditya Kulkarni
33 Lectures
2.5 hours
Sasha Miller
22 Lectures
1.5 hours
Zach Miller
16 Lectures
1.5 hours
Sasha Miller
23 Lectures
2.5 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2479,
"s": 2420,
"text": "This chapter explains how to work with form in Google AMP."
},
{
"code": null,
"e": 2668,
"s": 2479,
"text": "Note that forms tag remains the same as in standard HTML. AMP has added special restriction on the use of forms due to which we need to add the amp-form JavaScript file to work with forms."
},
{
"code": null,
"e": 2778,
"s": 2668,
"text": "<script async custom-element = \"amp-form\" \n src = \"https://cdn.ampproject.org/v0/ampform-0.1.js\"></script>\n"
},
{
"code": null,
"e": 3060,
"s": 2778,
"text": "To use forms in a AMP page, we need to include the above script in the .html file. The amp-form JavaScript file supports http and xmlhttprequest for form submission. Using HTTP request the page is reloaded and with xmlhttprequest it does not reload the page acts like ajax request."
},
{
"code": null,
"e": 3316,
"s": 3060,
"text": "For xmlhttprequest :\n<form method = \"post\" class = \"p2\" action-xhr = \"submitform.php\" target = \"_top\">\n //Input fields here\n</form>\n\nFor http :\n<form method = \"post\" class = \"p2\" action = \"submitform.php\" target = \"_top\">\n //Input fields here\n</form>\n"
},
{
"code": null,
"e": 3442,
"s": 3316,
"text": "Amp-form provides special attributes i.e, submit-error and submit-success to handle error and success when form is submitted."
},
{
"code": null,
"e": 3450,
"s": 3442,
"text": "Example"
},
{
"code": null,
"e": 3491,
"s": 3450,
"text": "An example for amp-form is shown below −"
},
{
"code": null,
"e": 6603,
"s": 3491,
"text": "<!doctype html>\n<html amp lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <script async src = \"https://cdn.ampproject.org/v0.js\"></script>\n <title>Google AMP - Form</title>\n <link rel = \"canonical\" href = \"ampform.html\">\n <meta name = \"viewport\" conten t = \"width = device-width,\n minimum-scale = 1,initialscale = 1\">\n \n <style amp-boilerplate>\n body{\n -webkit-animation:\n -amp-start 8s steps(1,end) 0s1 normal both;-moz-animation:\n -amp-start 8s steps(1,end) 0s 1 normal both;-msanimation:\n -amp-start 8s steps(1,end) 0s 1 normal both;animation:\n -amp-start 8s steps(1,end) 0s 1 normal both\n }\n @-webkit-keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}}@-o-keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}}@keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}} \n </style>\n <noscript>\n <style amp-boilerplate>\n body{\n -webkit-animation:none;\n -moz-animation:none;\n -msanimation:none;\n animation:none\n }\n </style>\n </noscript>\n <script async custom-element = \"amp-form\"\n src = \"https://cdn.ampproject.org/v0/amp-form-0.1.js\">\n </script>\n <script async custom-template = \"amp-mustache\"\n src = \"https://cdn.ampproject.org/v0/amp-mustache-0.2.js\">\n </script>\n <style amp-custom>\n form.amp-form-submit-success [submit-success],\n form.amp-form-submit-error [submit-error]{\n margin-top: 16px;\n }\n form.amp-form-submit-success [submit-success] {\n color: white;\n background-color:gray;\n }\n form.amp-form-submit-error [submit-error] {\n color: red;\n }\n form.amp-form-submit-success.hide-inputs > input {\n display: none;\n }\n </style>\n </head>\n <body>\n <h3>Google AMP - Form</h3>\n <form method = \"post\" \n class = \"p2\" \n action-xhr = \"submitform.php\" \n target = \"_top\">\n <p>AMP - Form Example</p>\n <div>\n <input type = \"text\" name = \"name\" placeholder = \"Enter \n Name\" required><br/><br/>\n <input type = \"email\" name = \"email\" \n placeholder = \"Enter Email\" required>\n <br/>\n <br/>\n </div>\n \n <input type = \"submit\" value = \"Submit\">\n <div submit-success>\n <template type = \"amp-mustache\">\n Form Submitted! Thanks {{name}}.\n </template>\n </div>\n \n <div submit-error>\n <template type = \"amp-mustache\">\n Error! {{name}}, please try again.\n </template>\n </div>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 6610,
"s": 6603,
"text": "Output"
},
{
"code": null,
"e": 6692,
"s": 6610,
"text": "When you executed the code shown above, you will find the result as shown below −"
},
{
"code": null,
"e": 6788,
"s": 6692,
"text": "Now, enter the details and click the Submit button. The output screen displayed is as follows −"
},
{
"code": null,
"e": 6980,
"s": 6788,
"text": "Observe that we have used amp-mustache for data-binding. The form is using action-xhr ie xmlhttprequest to submit form. We have used submitform.php file which returns the data in json format."
},
{
"code": null,
"e": 7075,
"s": 6980,
"text": "<form method = \"post\" class = \"p2\" action-xhr = \"submitform.php\" \n target = \"_top\">\n</form>\n"
},
{
"code": null,
"e": 7090,
"s": 7075,
"text": "submitform.php"
},
{
"code": null,
"e": 7491,
"s": 7090,
"text": "<?php\n if(!empty($_POST)){\n $domain_url = (isset($_SERVER['HTTPS']) ? \"https\" : \"http\") . \"://$_SERVER[HTTP_HOST]\";\n header(\"Content-type: application/json\");\n header(\"AMP-Access-Control-Allow-Source-Origin: \" . $domain_url);\n header(\"Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin\");\n $myJSON = json_encode($_POST);\n echo $myJSON;\n }\n?>\n"
},
{
"code": null,
"e": 7658,
"s": 7491,
"text": "For the form to work using xmlhttprequest, we need to add headers as per the CORS specification. Details of response headers added to submitform.php are shown below −"
},
{
"code": null,
"e": 7858,
"s": 7658,
"text": "For the form to work, we need to add headers such as access-control-expose-headers with value AMP-Access-Control-Allow-Source-Origin and amp-access-controlallow- source-origin −http://localhost:8080."
},
{
"code": null,
"e": 7976,
"s": 7858,
"text": "Note that we are using a php file and apache server. In php file, we have added the required headers as shown below −"
},
{
"code": null,
"e": 8378,
"s": 7976,
"text": "<?php\n\n if(!empty($_POST)){\n $domain_url = (isset($_SERVER['HTTPS']) ? \"https\" : \"http\") . \"://$_SERVER[HTTP_HOST]\";\n header(\"Content-type: application/json\");\n header(\"AMP-Access-Control-Allow-Source-Origin: \" . $domain_url);\n header(\"Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin\");\n $myJSON = json_encode($_POST);\n echo $myJSON;\n }\n ?\n?>"
},
{
"code": null,
"e": 8459,
"s": 8378,
"text": "In case we use a normal http request the page will get reloaded as shown below −"
},
{
"code": null,
"e": 8507,
"s": 8459,
"text": "For http request we have used form as follows −"
},
{
"code": null,
"e": 8597,
"s": 8507,
"text": "<form method = \"GET\" class = \"p2\" action = \"submitform.php\" \n target = \"_top\">\n</form>\n"
},
{
"code": null,
"e": 8605,
"s": 8597,
"text": "Example"
},
{
"code": null,
"e": 8661,
"s": 8605,
"text": "Observe the following code for a better understanding −"
},
{
"code": null,
"e": 11696,
"s": 8661,
"text": "<!doctype html>\n<html amp lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <script async src = \"https://cdn.ampproject.org/v0.js\"></script>\n <title>Google AMP - Form</title>\n <link rel = \"canonical\" href = \"ampform.html\">\n <meta name = \"viewport\" content = \"width = device-width,minimum-scale = 1,initialscale = 1\">\n \n <style amp-boilerplate>\n body{\n -webkit-animation:\n -amp-start 8s steps(1,end) 0s1 normal both;-moz-animation:\n -amp-start 8s steps(1,end) 0s 1 normal both;-msanimation:\n -amp-start 8s steps(1,end) 0s 1 normal both;animation:\n -amp-start 8s steps(1,end) 0s 1 normal both\n }\n @-webkit-keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}}@-o-keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}}@keyframes \n -ampstart{from{visibility:hidden}to{visibility:visible}}\n </style>\n <noscript>\n <style amp-boilerplate>\n body {\n -webkit-animation:none;\n -moz-animation:none;\n -msanimation:none;\n animation:none}\n >/style>\n </noscript>\n \n <script async custom-element = \"amp-form\"\n src = \"https://cdn.ampproject.org/v0/amp-form-0.1.js\">\n </script>\n <script async custom-template = \"amp-mustache\"\n src = \"https://cdn.ampproject.org/v0/amp-mustache-0.2.js\">\n </script>\n \n <style amp-custom>\n form.amp-form-submit-success [submit-success],\n form.amp-form-submit-error [submit-error]{\n margin-top: 16px;\n }\n form.amp-form-submit-success [submit-success] {\n color: white;\n background-color:gray;\n }\n form.amp-form-submit-error [submit-error] {\n color: red;\n }\n form.amp-form-submit-success.hide-inputs > \n input {\n display: none;\n }\n </style>\n </head>\n <body>\n <h3>Google AMP - Form</h3>\n <form method = \"GET\" class = \"p2\" action = \"submitform.php\" target = \"_top\">\n <p>AMP - Form Example</p>\n <div>\n <input type = \"text\" name = \"name\" placeholder = \"Enter Name\" required>\n <br/>\n <br/>\n <input type = \"email\" name = \"email\" placeholder = \"Enter Email\" required>\n <br/>\n <br/>\n <div>\n \n <input type = \"submit\" value = \"Submit\">\n <div submit-success>\n <template type = \"amp-mustache\">\n Form Submitted! Thanks {{name}}.\n </template>\n </div>\n <div submit-error>\n <template type = \"amp-mustache\">\n Error! {{name}}, please try again.\n </template>\n </div>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 11703,
"s": 11696,
"text": "Output"
},
{
"code": null,
"e": 11785,
"s": 11703,
"text": "When you executed the code shown above, you will find the result as shown below −"
},
{
"code": null,
"e": 11820,
"s": 11785,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11834,
"s": 11820,
"text": " Asif Hussain"
},
{
"code": null,
"e": 11866,
"s": 11834,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11883,
"s": 11866,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 11918,
"s": 11883,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11932,
"s": 11918,
"text": " Sasha Miller"
},
{
"code": null,
"e": 11967,
"s": 11932,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11980,
"s": 11967,
"text": " Zach Miller"
},
{
"code": null,
"e": 12015,
"s": 11980,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12029,
"s": 12015,
"text": " Sasha Miller"
},
{
"code": null,
"e": 12064,
"s": 12029,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12078,
"s": 12064,
"text": " Sasha Miller"
},
{
"code": null,
"e": 12085,
"s": 12078,
"text": " Print"
},
{
"code": null,
"e": 12096,
"s": 12085,
"text": " Add Notes"
}
] |
How to convert date YYYYMMDD to YY-MM-DD in MySQL query?
|
To convert date YYYYMMDD to YY-MM-DD in MySQL, use the below syntax −
select date_format(str_to_date(yourColumnName, '%Y%m%d'),'%Y-%m-%d') from yourTableName;
Let us first create a table −
mysql> create table DemoTable
(
ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
ClientProjectDeadline varchar(200)
);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command. We have inserted dates in the YYYYMMDD format −
mysql> insert into DemoTable(ClientProjectDeadline) values('20121221');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(ClientProjectDeadline) values('20190416');
Query OK, 1 row affected (0.53 sec)
mysql> insert into DemoTable(ClientProjectDeadline) values('20160624');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(ClientProjectDeadline) values('20170131');
Query OK, 1 row affected (0.20 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+-----------------------+
| ClientId | ClientProjectDeadline |
+----------+-----------------------+
| 1 | 20121221 |
| 2 | 20190416 |
| 3 | 20160624 |
| 4 | 20170131 |
+----------+-----------------------+
4 rows in set (0.00 sec)
Following is the query to convert date YYYYMMDD to YY-MM-DD in MySQL −
mysql> select date_format(str_to_date(ClientProjectDeadline, '%Y%m%d'),'%Y-%m-%d') from DemoTable;
This will produce the following output −
+----------------------------------------------------------------------+
| date_format(str_to_date(ClientProjectDeadline, '%Y%m%d'),'%Y-%m-%d') |
+----------------------------------------------------------------------+
| 2012-12-21 |
| 2019-04-16 |
| 2016-06-24 |
| 2017-01-31 |
+----------------------------------------------------------------------+
4 rows in set (0.05 sec)
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "To convert date YYYYMMDD to YY-MM-DD in MySQL, use the below syntax −"
},
{
"code": null,
"e": 1221,
"s": 1132,
"text": "select date_format(str_to_date(yourColumnName, '%Y%m%d'),'%Y-%m-%d') from yourTableName;"
},
{
"code": null,
"e": 1251,
"s": 1221,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1414,
"s": 1251,
"text": "mysql> create table DemoTable\n(\n ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ClientProjectDeadline varchar(200)\n);\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 1517,
"s": 1414,
"text": "Insert some records in the table using insert command. We have inserted dates in the YYYYMMDD format −"
},
{
"code": null,
"e": 1949,
"s": 1517,
"text": "mysql> insert into DemoTable(ClientProjectDeadline) values('20121221');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable(ClientProjectDeadline) values('20190416');\nQuery OK, 1 row affected (0.53 sec)\nmysql> insert into DemoTable(ClientProjectDeadline) values('20160624');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable(ClientProjectDeadline) values('20170131');\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 2035,
"s": 1949,
"text": "Following is the query to display all records from the table using select statement −"
},
{
"code": null,
"e": 2066,
"s": 2035,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2107,
"s": 2066,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2428,
"s": 2107,
"text": "+----------+-----------------------+\n| ClientId | ClientProjectDeadline |\n+----------+-----------------------+\n| 1 | 20121221 |\n| 2 | 20190416 |\n| 3 | 20160624 |\n| 4 | 20170131 |\n+----------+-----------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2499,
"s": 2428,
"text": "Following is the query to convert date YYYYMMDD to YY-MM-DD in MySQL −"
},
{
"code": null,
"e": 2598,
"s": 2499,
"text": "mysql> select date_format(str_to_date(ClientProjectDeadline, '%Y%m%d'),'%Y-%m-%d') from DemoTable;"
},
{
"code": null,
"e": 2639,
"s": 2598,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3248,
"s": 2639,
"text": "+----------------------------------------------------------------------+\n| date_format(str_to_date(ClientProjectDeadline, '%Y%m%d'),'%Y-%m-%d') |\n+----------------------------------------------------------------------+\n| 2012-12-21 |\n| 2019-04-16 |\n| 2016-06-24 |\n| 2017-01-31 |\n+----------------------------------------------------------------------+\n4 rows in set (0.05 sec)"
}
] |
Deep Learning for NLP: Creating a Chatbot with Keras! | by z_ai | Towards Data Science
|
In the previous post, we learned what Artificial Neural Networks and Deep Learning are. Also, some neural network structures for exploiting sequential data like text or audio were introduced. If you haven’t read that post, you should sit back, grab a coffee, and slowly enjoy it. It can be found here.
This new post will cover how to use Keras, a very popular library for neural networks to build a Chatbot. The main concepts of this library will be explained, and then we will go through a step-by-step guide on how to use it to create a yes/no answering bot in Python. We will use the easy going nature of Keras to implement a RNN structure from the paper “End to End Memory Networks” by Sukhbaatar et al (which you can find here).
This is interesting because having defined a task or application (creating a yes/no chatbot to answer specific questions), we will learn how to translate the insights from a research work onto an actual model that we can then use to reach our application goals.
Don’t be scared if this is your first time implementing an NLP model; I will go through every step, and put a link to the code at the end. For the best learning experience, I suggest you first read the post, and then go through the code while glancing at the sections of the post that go along with it.
Lastly, before we start, here you have some additional resources to skyrocket your Machine Learning career:
Awesome Machine Learning Resources:- For learning resources go to How to Learn Machine Learning! - For professional resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers.
Lets get to it then!
Keras is an open source, high level library for developing neural network models. It was developed by François Chollet, a Deep Learning researcher from Google. It’s core principle is to make the process of building a neural network, training it, and then using it to make predictions, easy and accessible for anyone with a basic programming knowledge, while still allowing developers to fully customise the parameters of the ANN.
Basically, Keras is actually just an interface that can run on top of different Deep Learning frameworks like CNTK, Tensorflow, or Theano for example. It works the same, independently of the back-end that is used.
As we mentioned in the previous post, in a Neural Network each node in a specific layer takes the weighted sum of the outputs from the previous layer, applies a mathematical function to them, and then passes that result to the next layer.
With Keras we can create a block representing each layer, where these mathematical operations and the number of nodes in the layer can be easily defined. These different layers can be created by typing an intuitive and single line of code.
The steps for creating a Keras model are the following:
Step 1: First we must define a network model, which most of the time will be the Sequential model: the network will be defined as a sequence of layers, each with its own customisable size and activation function. In these models the first layer will be the input layer, which requires us to define the size of the input that we will be feeding to the network. After this more and more layers can be added and customised until we reach the final output layer.
#Define Sequential Modelmodel = Sequential() #Create input layermodel.add(Dense(32, input_dim=784))#Create hidden layer model.add(Activation('relu')) #Create Output layermodel.add(Activation('sigmoid'))
Step 2: After creating the structure of the network in this manner we have to compile it, which transforms the simple sequence of layers that we have previously defined, into a complex group of matrix operations that dictate how the network behaves. Here we must define the optimisation algorithm that will be used to train the network, and also choose the loss function that will be minimised.
#Compiling the model with a mean squared error loss and RMSProp #optimizermodel.compile(optimizer='rmsprop',loss='mse')
Step 3: Once this is done, we can train or fit the network, which is done using the back-propagation algorithm mentioned in the previous post.
# Train the model, iterating on the data in batches of 32 samples model.fit(data, labels, epochs=10, batch_size=32)
Step 4: Hurray! Our network is trained. Now we can use it to make predictions on new data.
As you can see, it is fairly easy to build a network using Keras, so lets get to it and use it to create our chatbot! The blocks of code used above are not representative of an actual concrete neural network model, they are just examples of each of the steps to help illustrate how straightforward it is to build a Neural Network using the Keras API.
You can find all the documentation about Keras and how to install it in its official web page.
Now we know what all these different types of neural networks are, lets use them to build a chat-bot that can answer some questions for us!
Most of the time, neural network structures are more complex than just the standard input-hidden layer-output. Sometimes we might want to invent a neural network ourselfs and play around with the different node or layer combinations. Also, in some occasions we might want to implement a model we have seen somewhere, like in a scientific paper.
In this post we will go through an example of this second case, and construct the neural model from the paper “End to End Memory Networks” by Sukhbaatar et al (which you can find here).
Also we will see how to save the trained model, so that we don’t have to train the network every time we want to make predictions using the model we have built. Lets go then!
As mentioned earlier, the RNN used in this post, has been taken from the paper “End to End Memory Networks” , so I recommend you take a look at it before proceeding, although I will explain the most relevant parts in the following lines.
This paper implements an RNN like structure that uses an attention model to compensate for the long term memory issue about RNNs that we discussed in the previous post.
Don’t know what an attention model is? Do not worry, I will explain it in simple terms to you. Attention models gathered a lot of interest because of their very good results in tasks like machine translation. They address the issue of long sequences and short term memory of RNNs that was mentioned previously.
To gather an intuition of what attention does, think of how a human would translate a long sentence from one language to another. Instead of taking the whoooooole sentence and then translating it in one go, you would split the sentence into smaller chunks and translate these smaller pieces one by one. We work part by part with the sentence because it is really difficult to memorise it entirely and then translate it at once.
An attention mechanism does just this. In each time step, the model gives a higher weight in the output to those parts of the input sentence that are more relevant towards the task that we are trying to complete. This is where the name comes from: it plays attention to what is more important. The example above illustrates this very well; to translate the first part of the sentence, it makes little sense to be looking at the entire sentence or to the last part of the sentence.
The following figure shows the performance of RNN vs Attention models as we increase the length of the input sentence. When faced with a very long sentence, and ask to perform a specific task, the RNN, after processing all the sentence will have probably forgotten about the first inputs it had.
Okay, now that we know what an attention model is, lets take a closer look at the structure of the model we will be using. This model takes an input xi (a sentence), a query q about such sentence, and outputs a yes/ no answer a.
On the left part of the previous image we can see a representation of a single layer of this model. Two different embeddings are calculated for each sentence, A and C. Also, the query or question q is embedded, using the B embedding.
The A embeddings mi, are then computed using an inner product with the question embedding u (this is the part where the attention is taking place, as by computing the inner product between these embeddings what we are doing is looking for matches of words from the query and the sentence, to then give more importance to these matches using a Softmax function on the resulting terms of the dot product).
Lastly, we compute the output vector o using the embeddings from C (ci), and the weights or probabilities pi obtained from the dot product. With this output vector o, the weight matrix W, and the embedding of the question u, we can finally calculate the predicted answer a hat.
To build the entire network, we just repeat these procedure on the different layers, using the predicted output from one of them as the input for the next one. This is shown on the right part of the previous image.
Don’t worry if all these came too quick at you, hopefully you will get a better and complete understanding as we go through the different steps to implement this model in Python.
In 2015, Facebook came up with a bAbI data-set and 20 tasks for testing text understanding and reasoning in the bAbI project. The tasks are described in detail in the paper here.
The goal of each task is to challenge a unique aspect of machine-text related activities, testing different capabilities of learning models. In this post we will face one of these tasks, specifically the “QA with single supporting fact”.
The block bellow shows an example of the expected behaviour from this kind of QA bot:
FACT: Sandra went back to the hallway. Sandra moved to the office. QUESTION: Is Sandra in the office?ANSWER: yes
The data-set comes already separated into training data (10k instances) and test data (1k instances), where each instance has a fact, a question, and a yes/no answer to that question.
Now that we have seen the structure of our data, we need to build a vocabulary out of it. On a Natural Language Processing model a vocabulary is basically a set of words that the model knows and therefore can understand. If after building a vocabulary the model sees inside a sentence a word that is not in the vocabulary, it will either give it a 0 value on its sentence vectors, or represent it as unknown.
VOCABULARY:'.', '?', 'Daniel', 'Is', 'John', 'Mary', 'Sandra', 'apple','back','bathroom', 'bedroom', 'discarded', 'down','dropped','football', 'garden', 'got', 'grabbed', 'hallway','in', 'journeyed', 'kitchen', 'left', 'milk', 'moved','no', 'office', 'picked', 'put', 'the', 'there', 'to','took', 'travelled', 'up', 'went', 'yes'
As our training data is not very varied (most questions use the same verbs and nouns but with different combinations), our vocabulary is not very big, but in moderately sized NLP projects the vocabulary can be very large.
Take into account that to build a vocabulary we should only use the training data most of the time; the test data should be separated from the training data at the very beginning of a Machine Learning project and not touched until it is time to asses the performance on the model that has been chosen and tuned.
After building the vocabulary we need to vectorize our data. As we are using normal words as the inputs to our models and computers can only deal with numbers under the hood, we need a way to represent our sentences, which are groups of words, as vectors of numbers. Vectorizing does just this.
There are many ways of vectorizing our sentences, like Bag of Words models, or Tf-Idf, however, for simplicity, we are going to just use an indexing vectorizing technique, in which we give each of the words in the vocabulary a unique index from 1 to the length of the vocabulary.
VECTORIZATION INDEX:'the': 1, 'bedroom': 2, 'bathroom': 3, 'took': 4, 'no': 5, 'hallway': 6, '.': 7, 'went': 8, 'is': 9, 'picked': 10, 'yes': 11, 'journeyed': 12, 'back': 13, 'down': 14, 'discarded': 15, 'office': 16, 'football': 17, 'daniel': 18, 'travelled': 19, 'mary': 20, 'sandra': 21, 'up': 22, 'dropped': 23, 'to': 24, '?': 25, 'milk': 26, 'got': 27, 'in': 28, 'there': 29, 'moved': 30, 'garden': 31, 'apple': 32, 'grabbed': 33, 'kitchen': 34, 'put': 35, 'left': 36, 'john': 37}
Take into account that this vectorization is done using a random seed to start, so even tough you are using the same data as me, you might get different indexes for each word. Don’t worry; this will not affect the results of the project. Also, the words in our vocabulary were in upper and lowercase; when doing this vectorization all the words get lowercased for uniformity.
After this, because of the way Keras works, we need to pad the sentences. What does this mean? It means that we need to search for the length of the longest sentence, convert every sentence to a vector of that length, and fill the gap between the number of words of each sentence, and the number of words of the longest sentences with zeros.
After doing this, a random sentence of the dataset should look like:
FIRST TRAINING SENTENCE VECTORIZED AND PADDED:array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 30, 24, 1, 3, 7, 21, 12, 24, 1, 2, 7])
As we can see, it has zeros everywhere except in the end (this sentence was a lot shorter than the longest sentence), where it has some numbers. What are these numbers? Well, they are the indexes representing the different words of the sentence: 20 is the index representing the word Mary, 30 is moved, 24 is to, 1 is the, 3 represents bathroom and so on. The actual sentence is:
FIRST TRAINING SENTENCE: "Mary moved to the bathroom . Sandra journeyed to the bedroom ."
Okay, now that we have prepared the data, we are ready to build our Neural Network!
The first step to creating the network is to create what in Keras is known as placeholders for the inputs, which in our case are the stories and the questions. In an easy manner, these placeholders are containers where batches of our training data will be placed before being fed to the model.
#Example of a Placeholderquestion = Input((max_question_len,batch_size))
They have to have the same dimension as the data that will be fed, and can also have a batch size defined, although we can leave it blank if we dont know it at the time of creating the placeholders.
Now we have to create the embeddings mentioned in the paper, A, C and B. An embedding turns an integer number (in this case the index of a word) into a d dimensional vector, where context is taken into account. Word embeddings are widely used in NLP and is one of the techniques that has made the field progress so much in the recent years.
#Create input encoder A:input_encoder_m = Sequential()input_encoder_m.add(Embedding(input_dim=vocab_len,output_dim = 64)) input_encoder_m.add(Dropout(0.3))#Outputs: (Samples, story_maxlen,embedding_dim) -- Gives a list of #the lenght of the samples where each item has the#lenght of the max story lenght and every word is embedded in the embbeding dimension
The code above is an example of one of the embeddings done in the paper (A embedding). Like always in Keras, we first define the model (Sequential), and then add the embedding layer and a dropout layer, which reduces the chance of the model over-fitting by triggering off nodes of the network.
Once we have created the two embeddings for the input sentences, and the embeddings for the questions, we can start defining the operations that take place in our model. As mentioned previously, we compute the attention by doing the dot product between the embedding of the questions and one of the embeddings of the stories, and then doing a softmax. The following block shows how this is done:
match = dot([input_encoded_m,question_encoded], axes = (2,2))match = Activation('softmax')(match)
After this, we need to calculate the output o adding the match matrix with the second input vector sequence, and then calculate the response using this output and the encoded question.
response = add([match,input_encoded_c])response = Permute((2,1))(response)answer = concatenate([response, question_encoded])
Lastly, once this is done we add the rest of the layers of the model, adding an LSTM layer (instead of an RNN like in the paper), a dropout layer and a final softmax to compute the output.
answer = LSTM(32)(answer)answer = Dropout(0.5)(answer)#Output layer:answer = Dense(vocab_len)(answer) #Output shape: (Samples, Vocab_size) #Yes or no and all 0sanswer = Activation('softmax')(answer)
Notice here that the output is a vector of the size of the vocabulary (that is, the length of the number of words known by the model), where all the positions should be zero except the ones at the indexes of ‘yes’ and ‘no’.
Now we are ready to compile the model, and train it!
model = Model([input_sequence,question], answer)model.compile(optimizer='rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy'])
With these two lines we build the final model, and compile it, that is, define all the maths that will be going on in the background by specifying an optimiser, a loss function and a metric to optimise.
Now its time to train the model, here we need to define the inputs to the training, (the input stories, questions and answers), the batch size that we will be feeding the model with (that is, how many inputs at once), and the number of epochs that we will train the model for (that is, how many times the model will go through the training data in order to update the weights). I used 1000 epochs and obtained an accuracy of 98%, but even with 100 to 200 epochs you should get some pretty good results.
Note that depending on your hardware, this training might take a while. Just relax, sit back, keep reading Medium and wait until its done.
After its completed the training you might be left wondering “am I going to have to wait this long every time I want to use the model?” the obvious answer my friend is, NO. Keras allows developers to save a certain model it has trained, with the weights and all the configurations. The following block of code shows how this is done.
filename = 'medium_chatbot_1000_epochs.h5'model.save(filename)
Now, when we want to use the model is as easy as loading it like so:
model.load_weights('medium_chatbot_1000_epochs.h5')
Cool cool. Now that we have trained our model, lets see how it performs on new data, and play a little bit with it!
Lets see how our model performs on the test data!
pred_results = model.predict(([inputs_test,questions_test]))
These results are an array, as mentioned earlier that contain in every position the probabilities of each of the words in the vocabulary being the answer to the question. If we look at the first element of this array, we will see a vector of the size of the vocabulary, where all the times are close to 0 except the ones corresponding to yes or no.
Out of these, if we pick the index of the highest value of the array and then see to which word it corresponds to, we should find out if the answer is affirmative or negative.
One fun thing that we can do now, is create our own stories and questions, and feed them to the bot to see what he says!
my_story = 'Sandra picked up the milk . Mary travelled left . 'my_story.split()my_question = 'Sandra got the milk ?'my_question.split()
I created a story and a question somehow similar to what our little bot has seen before, and after adapting it to the format that the neural network wants the bot answered ‘YES’ (in lowercase tough, he is not as enthusiastic as I am).
Lets try with something different:
my_story = 'Medium is cool . Jaime really likes it. 'my_story.split()my_question = 'Does Jaime like Medium ?'my_question.split()
The answer this time was: ‘Of course, who doesn’t?’
Just kidding, I didn’t try that story/question combination, as many of the words included are not inside the vocabulary of our little answering machine. Also, he only knows how to say ‘yes’ and ‘no’, and does not usually give out any other answers. However, with more training data and some workarounds this could be easily achieved.
That is it for today! I hope you guys enjoyed reading the post as much as I enjoyed writing it. Have a good day, take care, and enjoy AI!
You can find the code and the data on my Github page.
If you want to go deeper into attention models, or understand some word vectorizing techniques that I mentioned, check out these additional resources I’ve put together for you. Enjoy!
A Beginner’s Guide to Attention Mechanisms and Memory Networks
Andrew’s Ng video with the intuition to attention models.
A Begginner’s Guide to Tf-Idf and Bag of Words.
Keras guide to building this same model.
Have a good read!
For further resources on Machine Learning and Data Science check out the following repository: How to Learn Machine Learning! For career resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers.
Lastly, check out my other articles on Deep Learning for NLP:
towardsdatascience.com
towardsdatascience.com
Enjoy!
Also, for more resources to learn Machine Learning and Artificial Intelligence, check out the following repo:
|
[
{
"code": null,
"e": 474,
"s": 172,
"text": "In the previous post, we learned what Artificial Neural Networks and Deep Learning are. Also, some neural network structures for exploiting sequential data like text or audio were introduced. If you haven’t read that post, you should sit back, grab a coffee, and slowly enjoy it. It can be found here."
},
{
"code": null,
"e": 906,
"s": 474,
"text": "This new post will cover how to use Keras, a very popular library for neural networks to build a Chatbot. The main concepts of this library will be explained, and then we will go through a step-by-step guide on how to use it to create a yes/no answering bot in Python. We will use the easy going nature of Keras to implement a RNN structure from the paper “End to End Memory Networks” by Sukhbaatar et al (which you can find here)."
},
{
"code": null,
"e": 1168,
"s": 906,
"text": "This is interesting because having defined a task or application (creating a yes/no chatbot to answer specific questions), we will learn how to translate the insights from a research work onto an actual model that we can then use to reach our application goals."
},
{
"code": null,
"e": 1471,
"s": 1168,
"text": "Don’t be scared if this is your first time implementing an NLP model; I will go through every step, and put a link to the code at the end. For the best learning experience, I suggest you first read the post, and then go through the code while glancing at the sections of the post that go along with it."
},
{
"code": null,
"e": 1579,
"s": 1471,
"text": "Lastly, before we start, here you have some additional resources to skyrocket your Machine Learning career:"
},
{
"code": null,
"e": 1821,
"s": 1579,
"text": "Awesome Machine Learning Resources:- For learning resources go to How to Learn Machine Learning! - For professional resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers."
},
{
"code": null,
"e": 1842,
"s": 1821,
"text": "Lets get to it then!"
},
{
"code": null,
"e": 2273,
"s": 1842,
"text": "Keras is an open source, high level library for developing neural network models. It was developed by François Chollet, a Deep Learning researcher from Google. It’s core principle is to make the process of building a neural network, training it, and then using it to make predictions, easy and accessible for anyone with a basic programming knowledge, while still allowing developers to fully customise the parameters of the ANN."
},
{
"code": null,
"e": 2487,
"s": 2273,
"text": "Basically, Keras is actually just an interface that can run on top of different Deep Learning frameworks like CNTK, Tensorflow, or Theano for example. It works the same, independently of the back-end that is used."
},
{
"code": null,
"e": 2726,
"s": 2487,
"text": "As we mentioned in the previous post, in a Neural Network each node in a specific layer takes the weighted sum of the outputs from the previous layer, applies a mathematical function to them, and then passes that result to the next layer."
},
{
"code": null,
"e": 2966,
"s": 2726,
"text": "With Keras we can create a block representing each layer, where these mathematical operations and the number of nodes in the layer can be easily defined. These different layers can be created by typing an intuitive and single line of code."
},
{
"code": null,
"e": 3022,
"s": 2966,
"text": "The steps for creating a Keras model are the following:"
},
{
"code": null,
"e": 3481,
"s": 3022,
"text": "Step 1: First we must define a network model, which most of the time will be the Sequential model: the network will be defined as a sequence of layers, each with its own customisable size and activation function. In these models the first layer will be the input layer, which requires us to define the size of the input that we will be feeding to the network. After this more and more layers can be added and customised until we reach the final output layer."
},
{
"code": null,
"e": 3686,
"s": 3481,
"text": "#Define Sequential Modelmodel = Sequential() #Create input layermodel.add(Dense(32, input_dim=784))#Create hidden layer model.add(Activation('relu')) #Create Output layermodel.add(Activation('sigmoid')) "
},
{
"code": null,
"e": 4081,
"s": 3686,
"text": "Step 2: After creating the structure of the network in this manner we have to compile it, which transforms the simple sequence of layers that we have previously defined, into a complex group of matrix operations that dictate how the network behaves. Here we must define the optimisation algorithm that will be used to train the network, and also choose the loss function that will be minimised."
},
{
"code": null,
"e": 4201,
"s": 4081,
"text": "#Compiling the model with a mean squared error loss and RMSProp #optimizermodel.compile(optimizer='rmsprop',loss='mse')"
},
{
"code": null,
"e": 4344,
"s": 4201,
"text": "Step 3: Once this is done, we can train or fit the network, which is done using the back-propagation algorithm mentioned in the previous post."
},
{
"code": null,
"e": 4460,
"s": 4344,
"text": "# Train the model, iterating on the data in batches of 32 samples model.fit(data, labels, epochs=10, batch_size=32)"
},
{
"code": null,
"e": 4551,
"s": 4460,
"text": "Step 4: Hurray! Our network is trained. Now we can use it to make predictions on new data."
},
{
"code": null,
"e": 4902,
"s": 4551,
"text": "As you can see, it is fairly easy to build a network using Keras, so lets get to it and use it to create our chatbot! The blocks of code used above are not representative of an actual concrete neural network model, they are just examples of each of the steps to help illustrate how straightforward it is to build a Neural Network using the Keras API."
},
{
"code": null,
"e": 4997,
"s": 4902,
"text": "You can find all the documentation about Keras and how to install it in its official web page."
},
{
"code": null,
"e": 5137,
"s": 4997,
"text": "Now we know what all these different types of neural networks are, lets use them to build a chat-bot that can answer some questions for us!"
},
{
"code": null,
"e": 5482,
"s": 5137,
"text": "Most of the time, neural network structures are more complex than just the standard input-hidden layer-output. Sometimes we might want to invent a neural network ourselfs and play around with the different node or layer combinations. Also, in some occasions we might want to implement a model we have seen somewhere, like in a scientific paper."
},
{
"code": null,
"e": 5668,
"s": 5482,
"text": "In this post we will go through an example of this second case, and construct the neural model from the paper “End to End Memory Networks” by Sukhbaatar et al (which you can find here)."
},
{
"code": null,
"e": 5843,
"s": 5668,
"text": "Also we will see how to save the trained model, so that we don’t have to train the network every time we want to make predictions using the model we have built. Lets go then!"
},
{
"code": null,
"e": 6081,
"s": 5843,
"text": "As mentioned earlier, the RNN used in this post, has been taken from the paper “End to End Memory Networks” , so I recommend you take a look at it before proceeding, although I will explain the most relevant parts in the following lines."
},
{
"code": null,
"e": 6250,
"s": 6081,
"text": "This paper implements an RNN like structure that uses an attention model to compensate for the long term memory issue about RNNs that we discussed in the previous post."
},
{
"code": null,
"e": 6561,
"s": 6250,
"text": "Don’t know what an attention model is? Do not worry, I will explain it in simple terms to you. Attention models gathered a lot of interest because of their very good results in tasks like machine translation. They address the issue of long sequences and short term memory of RNNs that was mentioned previously."
},
{
"code": null,
"e": 6989,
"s": 6561,
"text": "To gather an intuition of what attention does, think of how a human would translate a long sentence from one language to another. Instead of taking the whoooooole sentence and then translating it in one go, you would split the sentence into smaller chunks and translate these smaller pieces one by one. We work part by part with the sentence because it is really difficult to memorise it entirely and then translate it at once."
},
{
"code": null,
"e": 7470,
"s": 6989,
"text": "An attention mechanism does just this. In each time step, the model gives a higher weight in the output to those parts of the input sentence that are more relevant towards the task that we are trying to complete. This is where the name comes from: it plays attention to what is more important. The example above illustrates this very well; to translate the first part of the sentence, it makes little sense to be looking at the entire sentence or to the last part of the sentence."
},
{
"code": null,
"e": 7766,
"s": 7470,
"text": "The following figure shows the performance of RNN vs Attention models as we increase the length of the input sentence. When faced with a very long sentence, and ask to perform a specific task, the RNN, after processing all the sentence will have probably forgotten about the first inputs it had."
},
{
"code": null,
"e": 7995,
"s": 7766,
"text": "Okay, now that we know what an attention model is, lets take a closer look at the structure of the model we will be using. This model takes an input xi (a sentence), a query q about such sentence, and outputs a yes/ no answer a."
},
{
"code": null,
"e": 8229,
"s": 7995,
"text": "On the left part of the previous image we can see a representation of a single layer of this model. Two different embeddings are calculated for each sentence, A and C. Also, the query or question q is embedded, using the B embedding."
},
{
"code": null,
"e": 8633,
"s": 8229,
"text": "The A embeddings mi, are then computed using an inner product with the question embedding u (this is the part where the attention is taking place, as by computing the inner product between these embeddings what we are doing is looking for matches of words from the query and the sentence, to then give more importance to these matches using a Softmax function on the resulting terms of the dot product)."
},
{
"code": null,
"e": 8911,
"s": 8633,
"text": "Lastly, we compute the output vector o using the embeddings from C (ci), and the weights or probabilities pi obtained from the dot product. With this output vector o, the weight matrix W, and the embedding of the question u, we can finally calculate the predicted answer a hat."
},
{
"code": null,
"e": 9126,
"s": 8911,
"text": "To build the entire network, we just repeat these procedure on the different layers, using the predicted output from one of them as the input for the next one. This is shown on the right part of the previous image."
},
{
"code": null,
"e": 9305,
"s": 9126,
"text": "Don’t worry if all these came too quick at you, hopefully you will get a better and complete understanding as we go through the different steps to implement this model in Python."
},
{
"code": null,
"e": 9484,
"s": 9305,
"text": "In 2015, Facebook came up with a bAbI data-set and 20 tasks for testing text understanding and reasoning in the bAbI project. The tasks are described in detail in the paper here."
},
{
"code": null,
"e": 9722,
"s": 9484,
"text": "The goal of each task is to challenge a unique aspect of machine-text related activities, testing different capabilities of learning models. In this post we will face one of these tasks, specifically the “QA with single supporting fact”."
},
{
"code": null,
"e": 9808,
"s": 9722,
"text": "The block bellow shows an example of the expected behaviour from this kind of QA bot:"
},
{
"code": null,
"e": 9922,
"s": 9808,
"text": "FACT: Sandra went back to the hallway. Sandra moved to the office. QUESTION: Is Sandra in the office?ANSWER: yes"
},
{
"code": null,
"e": 10106,
"s": 9922,
"text": "The data-set comes already separated into training data (10k instances) and test data (1k instances), where each instance has a fact, a question, and a yes/no answer to that question."
},
{
"code": null,
"e": 10515,
"s": 10106,
"text": "Now that we have seen the structure of our data, we need to build a vocabulary out of it. On a Natural Language Processing model a vocabulary is basically a set of words that the model knows and therefore can understand. If after building a vocabulary the model sees inside a sentence a word that is not in the vocabulary, it will either give it a 0 value on its sentence vectors, or represent it as unknown."
},
{
"code": null,
"e": 10845,
"s": 10515,
"text": "VOCABULARY:'.', '?', 'Daniel', 'Is', 'John', 'Mary', 'Sandra', 'apple','back','bathroom', 'bedroom', 'discarded', 'down','dropped','football', 'garden', 'got', 'grabbed', 'hallway','in', 'journeyed', 'kitchen', 'left', 'milk', 'moved','no', 'office', 'picked', 'put', 'the', 'there', 'to','took', 'travelled', 'up', 'went', 'yes'"
},
{
"code": null,
"e": 11067,
"s": 10845,
"text": "As our training data is not very varied (most questions use the same verbs and nouns but with different combinations), our vocabulary is not very big, but in moderately sized NLP projects the vocabulary can be very large."
},
{
"code": null,
"e": 11379,
"s": 11067,
"text": "Take into account that to build a vocabulary we should only use the training data most of the time; the test data should be separated from the training data at the very beginning of a Machine Learning project and not touched until it is time to asses the performance on the model that has been chosen and tuned."
},
{
"code": null,
"e": 11674,
"s": 11379,
"text": "After building the vocabulary we need to vectorize our data. As we are using normal words as the inputs to our models and computers can only deal with numbers under the hood, we need a way to represent our sentences, which are groups of words, as vectors of numbers. Vectorizing does just this."
},
{
"code": null,
"e": 11954,
"s": 11674,
"text": "There are many ways of vectorizing our sentences, like Bag of Words models, or Tf-Idf, however, for simplicity, we are going to just use an indexing vectorizing technique, in which we give each of the words in the vocabulary a unique index from 1 to the length of the vocabulary."
},
{
"code": null,
"e": 12440,
"s": 11954,
"text": "VECTORIZATION INDEX:'the': 1, 'bedroom': 2, 'bathroom': 3, 'took': 4, 'no': 5, 'hallway': 6, '.': 7, 'went': 8, 'is': 9, 'picked': 10, 'yes': 11, 'journeyed': 12, 'back': 13, 'down': 14, 'discarded': 15, 'office': 16, 'football': 17, 'daniel': 18, 'travelled': 19, 'mary': 20, 'sandra': 21, 'up': 22, 'dropped': 23, 'to': 24, '?': 25, 'milk': 26, 'got': 27, 'in': 28, 'there': 29, 'moved': 30, 'garden': 31, 'apple': 32, 'grabbed': 33, 'kitchen': 34, 'put': 35, 'left': 36, 'john': 37}"
},
{
"code": null,
"e": 12816,
"s": 12440,
"text": "Take into account that this vectorization is done using a random seed to start, so even tough you are using the same data as me, you might get different indexes for each word. Don’t worry; this will not affect the results of the project. Also, the words in our vocabulary were in upper and lowercase; when doing this vectorization all the words get lowercased for uniformity."
},
{
"code": null,
"e": 13158,
"s": 12816,
"text": "After this, because of the way Keras works, we need to pad the sentences. What does this mean? It means that we need to search for the length of the longest sentence, convert every sentence to a vector of that length, and fill the gap between the number of words of each sentence, and the number of words of the longest sentences with zeros."
},
{
"code": null,
"e": 13227,
"s": 13158,
"text": "After doing this, a random sentence of the dataset should look like:"
},
{
"code": null,
"e": 13952,
"s": 13227,
"text": "FIRST TRAINING SENTENCE VECTORIZED AND PADDED:array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 30, 24, 1, 3, 7, 21, 12, 24, 1, 2, 7])"
},
{
"code": null,
"e": 14332,
"s": 13952,
"text": "As we can see, it has zeros everywhere except in the end (this sentence was a lot shorter than the longest sentence), where it has some numbers. What are these numbers? Well, they are the indexes representing the different words of the sentence: 20 is the index representing the word Mary, 30 is moved, 24 is to, 1 is the, 3 represents bathroom and so on. The actual sentence is:"
},
{
"code": null,
"e": 14422,
"s": 14332,
"text": "FIRST TRAINING SENTENCE: \"Mary moved to the bathroom . Sandra journeyed to the bedroom .\""
},
{
"code": null,
"e": 14506,
"s": 14422,
"text": "Okay, now that we have prepared the data, we are ready to build our Neural Network!"
},
{
"code": null,
"e": 14800,
"s": 14506,
"text": "The first step to creating the network is to create what in Keras is known as placeholders for the inputs, which in our case are the stories and the questions. In an easy manner, these placeholders are containers where batches of our training data will be placed before being fed to the model."
},
{
"code": null,
"e": 14873,
"s": 14800,
"text": "#Example of a Placeholderquestion = Input((max_question_len,batch_size))"
},
{
"code": null,
"e": 15072,
"s": 14873,
"text": "They have to have the same dimension as the data that will be fed, and can also have a batch size defined, although we can leave it blank if we dont know it at the time of creating the placeholders."
},
{
"code": null,
"e": 15413,
"s": 15072,
"text": "Now we have to create the embeddings mentioned in the paper, A, C and B. An embedding turns an integer number (in this case the index of a word) into a d dimensional vector, where context is taken into account. Word embeddings are widely used in NLP and is one of the techniques that has made the field progress so much in the recent years."
},
{
"code": null,
"e": 15771,
"s": 15413,
"text": "#Create input encoder A:input_encoder_m = Sequential()input_encoder_m.add(Embedding(input_dim=vocab_len,output_dim = 64)) input_encoder_m.add(Dropout(0.3))#Outputs: (Samples, story_maxlen,embedding_dim) -- Gives a list of #the lenght of the samples where each item has the#lenght of the max story lenght and every word is embedded in the embbeding dimension"
},
{
"code": null,
"e": 16065,
"s": 15771,
"text": "The code above is an example of one of the embeddings done in the paper (A embedding). Like always in Keras, we first define the model (Sequential), and then add the embedding layer and a dropout layer, which reduces the chance of the model over-fitting by triggering off nodes of the network."
},
{
"code": null,
"e": 16461,
"s": 16065,
"text": "Once we have created the two embeddings for the input sentences, and the embeddings for the questions, we can start defining the operations that take place in our model. As mentioned previously, we compute the attention by doing the dot product between the embedding of the questions and one of the embeddings of the stories, and then doing a softmax. The following block shows how this is done:"
},
{
"code": null,
"e": 16559,
"s": 16461,
"text": "match = dot([input_encoded_m,question_encoded], axes = (2,2))match = Activation('softmax')(match)"
},
{
"code": null,
"e": 16744,
"s": 16559,
"text": "After this, we need to calculate the output o adding the match matrix with the second input vector sequence, and then calculate the response using this output and the encoded question."
},
{
"code": null,
"e": 16869,
"s": 16744,
"text": "response = add([match,input_encoded_c])response = Permute((2,1))(response)answer = concatenate([response, question_encoded])"
},
{
"code": null,
"e": 17058,
"s": 16869,
"text": "Lastly, once this is done we add the rest of the layers of the model, adding an LSTM layer (instead of an RNN like in the paper), a dropout layer and a final softmax to compute the output."
},
{
"code": null,
"e": 17257,
"s": 17058,
"text": "answer = LSTM(32)(answer)answer = Dropout(0.5)(answer)#Output layer:answer = Dense(vocab_len)(answer) #Output shape: (Samples, Vocab_size) #Yes or no and all 0sanswer = Activation('softmax')(answer)"
},
{
"code": null,
"e": 17481,
"s": 17257,
"text": "Notice here that the output is a vector of the size of the vocabulary (that is, the length of the number of words known by the model), where all the positions should be zero except the ones at the indexes of ‘yes’ and ‘no’."
},
{
"code": null,
"e": 17534,
"s": 17481,
"text": "Now we are ready to compile the model, and train it!"
},
{
"code": null,
"e": 17676,
"s": 17534,
"text": "model = Model([input_sequence,question], answer)model.compile(optimizer='rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy'])"
},
{
"code": null,
"e": 17879,
"s": 17676,
"text": "With these two lines we build the final model, and compile it, that is, define all the maths that will be going on in the background by specifying an optimiser, a loss function and a metric to optimise."
},
{
"code": null,
"e": 18382,
"s": 17879,
"text": "Now its time to train the model, here we need to define the inputs to the training, (the input stories, questions and answers), the batch size that we will be feeding the model with (that is, how many inputs at once), and the number of epochs that we will train the model for (that is, how many times the model will go through the training data in order to update the weights). I used 1000 epochs and obtained an accuracy of 98%, but even with 100 to 200 epochs you should get some pretty good results."
},
{
"code": null,
"e": 18521,
"s": 18382,
"text": "Note that depending on your hardware, this training might take a while. Just relax, sit back, keep reading Medium and wait until its done."
},
{
"code": null,
"e": 18855,
"s": 18521,
"text": "After its completed the training you might be left wondering “am I going to have to wait this long every time I want to use the model?” the obvious answer my friend is, NO. Keras allows developers to save a certain model it has trained, with the weights and all the configurations. The following block of code shows how this is done."
},
{
"code": null,
"e": 18918,
"s": 18855,
"text": "filename = 'medium_chatbot_1000_epochs.h5'model.save(filename)"
},
{
"code": null,
"e": 18987,
"s": 18918,
"text": "Now, when we want to use the model is as easy as loading it like so:"
},
{
"code": null,
"e": 19039,
"s": 18987,
"text": "model.load_weights('medium_chatbot_1000_epochs.h5')"
},
{
"code": null,
"e": 19155,
"s": 19039,
"text": "Cool cool. Now that we have trained our model, lets see how it performs on new data, and play a little bit with it!"
},
{
"code": null,
"e": 19205,
"s": 19155,
"text": "Lets see how our model performs on the test data!"
},
{
"code": null,
"e": 19266,
"s": 19205,
"text": "pred_results = model.predict(([inputs_test,questions_test]))"
},
{
"code": null,
"e": 19615,
"s": 19266,
"text": "These results are an array, as mentioned earlier that contain in every position the probabilities of each of the words in the vocabulary being the answer to the question. If we look at the first element of this array, we will see a vector of the size of the vocabulary, where all the times are close to 0 except the ones corresponding to yes or no."
},
{
"code": null,
"e": 19791,
"s": 19615,
"text": "Out of these, if we pick the index of the highest value of the array and then see to which word it corresponds to, we should find out if the answer is affirmative or negative."
},
{
"code": null,
"e": 19912,
"s": 19791,
"text": "One fun thing that we can do now, is create our own stories and questions, and feed them to the bot to see what he says!"
},
{
"code": null,
"e": 20048,
"s": 19912,
"text": "my_story = 'Sandra picked up the milk . Mary travelled left . 'my_story.split()my_question = 'Sandra got the milk ?'my_question.split()"
},
{
"code": null,
"e": 20283,
"s": 20048,
"text": "I created a story and a question somehow similar to what our little bot has seen before, and after adapting it to the format that the neural network wants the bot answered ‘YES’ (in lowercase tough, he is not as enthusiastic as I am)."
},
{
"code": null,
"e": 20318,
"s": 20283,
"text": "Lets try with something different:"
},
{
"code": null,
"e": 20447,
"s": 20318,
"text": "my_story = 'Medium is cool . Jaime really likes it. 'my_story.split()my_question = 'Does Jaime like Medium ?'my_question.split()"
},
{
"code": null,
"e": 20499,
"s": 20447,
"text": "The answer this time was: ‘Of course, who doesn’t?’"
},
{
"code": null,
"e": 20833,
"s": 20499,
"text": "Just kidding, I didn’t try that story/question combination, as many of the words included are not inside the vocabulary of our little answering machine. Also, he only knows how to say ‘yes’ and ‘no’, and does not usually give out any other answers. However, with more training data and some workarounds this could be easily achieved."
},
{
"code": null,
"e": 20971,
"s": 20833,
"text": "That is it for today! I hope you guys enjoyed reading the post as much as I enjoyed writing it. Have a good day, take care, and enjoy AI!"
},
{
"code": null,
"e": 21025,
"s": 20971,
"text": "You can find the code and the data on my Github page."
},
{
"code": null,
"e": 21209,
"s": 21025,
"text": "If you want to go deeper into attention models, or understand some word vectorizing techniques that I mentioned, check out these additional resources I’ve put together for you. Enjoy!"
},
{
"code": null,
"e": 21272,
"s": 21209,
"text": "A Beginner’s Guide to Attention Mechanisms and Memory Networks"
},
{
"code": null,
"e": 21330,
"s": 21272,
"text": "Andrew’s Ng video with the intuition to attention models."
},
{
"code": null,
"e": 21378,
"s": 21330,
"text": "A Begginner’s Guide to Tf-Idf and Bag of Words."
},
{
"code": null,
"e": 21419,
"s": 21378,
"text": "Keras guide to building this same model."
},
{
"code": null,
"e": 21437,
"s": 21419,
"text": "Have a good read!"
},
{
"code": null,
"e": 21700,
"s": 21437,
"text": "For further resources on Machine Learning and Data Science check out the following repository: How to Learn Machine Learning! For career resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers."
},
{
"code": null,
"e": 21762,
"s": 21700,
"text": "Lastly, check out my other articles on Deep Learning for NLP:"
},
{
"code": null,
"e": 21785,
"s": 21762,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 21808,
"s": 21785,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 21815,
"s": 21808,
"text": "Enjoy!"
}
] |
Lua - Environment
|
If you are still willing to set up your environment for Lua programming language, you need the following softwares available on your computer - (a) Text Editor, (b) The Lua Interpreter, and (c) Lua Compiler.
You need a text editor to type your program. Examples of a few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of the text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on Windows as well as Linux or UNIX.
The files you create with your editor are called source files and these files contain the program source code. The source files for Lua programs are typically named with the extension ".lua".
It is just a small program that enables you to type Lua commands and have them executed immediately. It stops the execution of a Lua file in case it encounters an error unlike a compiler that executes fully.
When we extend Lua to other languages/applications, we need a Software Development Kit with a compiler that is compatible with the Lua Application Program Interface.
There is a separate IDE named "SciTE" developed for the windows environment, which can be downloaded from https://code.google.com/p/luaforwindows/ download section.
Run the downloaded executable to install the Lua IDE.
Since it’s an IDE, you can both create and build the Lua code using the same.
In case, you are interested in installing Lua in command line mode, you need to install MinGW or Cygwin and then compile and install Lua in windows.
To download and build Lua, use the following command −
$ wget http://www.lua.org/ftp/lua-5.2.3.tar.gz
$ tar zxf lua-5.2.3.tar.gz
$ cd lua-5.2.3
$ make linux test
In order to install on other platforms like aix, ansi, bsd, generic linux, mingw, posix, solaris by replacing Linux in make Linux, test with the corresponding platform name.
We have a helloWorld.lua, in Lua as follows −
print("Hello World!")
Now, we can build and run a Lua file say helloWorld.lua, by switching to the folder containing the file using cd, and then using the following command −
$ lua helloWorld
We can see the following output.
Hello World!
To build/test Lua in the Mac OS X, use the following command −
$ curl -R -O http://www.lua.org/ftp/lua-5.2.3.tar.gz
$ tar zxf lua-5.2.3.tar.gz
$ cd lua-5.2.3
$ make macosx test
In certain cases, you may not have installed the Xcode and command line tools. In such cases, you won’t be able to use the make command. Install Xcode from mac app store. Then go to Preferences of Xcode, and then switch to Downloads and install the component named "Command Line Tools". Once the process is completed, make command will be available to you.
It is not mandatory for you to execute the "make macosx test" statement. Even without executing this command, you can still use Lua in Mac OS X.
We have a helloWorld.lua, in Lua, as follows −
print("Hello World!")
Now, we can build and run a Lua file say helloWorld.lua by switching to the folder containing the file using cd and then using the following command −
$ lua helloWorld
We can see the following output −
Hello World!
As mentioned earlier, for Windows SciTE, Lua IDE is the default IDE provided by the Lua creator team. The alternate IDE available is from ZeroBrane Studio, which is available across multiple platforms like Windows, Mac and Linux.
There are also plugins for eclipse that enable the Lua development. Using IDE makes it easier for development with features like code completion and is highly recommended. The IDE also provides interactive mode programming similar to the command line version of Lua.
12 Lectures
2 hours
Manish Gupta
80 Lectures
3 hours
Sanjeev Mittal
54 Lectures
3.5 hours
Mehmet GOKTEPE
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2311,
"s": 2103,
"text": "If you are still willing to set up your environment for Lua programming language, you need the following softwares available on your computer - (a) Text Editor, (b) The Lua Interpreter, and (c) Lua Compiler."
},
{
"code": null,
"e": 2462,
"s": 2311,
"text": "You need a text editor to type your program. Examples of a few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi."
},
{
"code": null,
"e": 2648,
"s": 2462,
"text": "Name and version of the text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on Windows as well as Linux or UNIX."
},
{
"code": null,
"e": 2840,
"s": 2648,
"text": "The files you create with your editor are called source files and these files contain the program source code. The source files for Lua programs are typically named with the extension \".lua\"."
},
{
"code": null,
"e": 3048,
"s": 2840,
"text": "It is just a small program that enables you to type Lua commands and have them executed immediately. It stops the execution of a Lua file in case it encounters an error unlike a compiler that executes fully."
},
{
"code": null,
"e": 3214,
"s": 3048,
"text": "When we extend Lua to other languages/applications, we need a Software Development Kit with a compiler that is compatible with the Lua Application Program Interface."
},
{
"code": null,
"e": 3379,
"s": 3214,
"text": "There is a separate IDE named \"SciTE\" developed for the windows environment, which can be downloaded from https://code.google.com/p/luaforwindows/ download section."
},
{
"code": null,
"e": 3433,
"s": 3379,
"text": "Run the downloaded executable to install the Lua IDE."
},
{
"code": null,
"e": 3511,
"s": 3433,
"text": "Since it’s an IDE, you can both create and build the Lua code using the same."
},
{
"code": null,
"e": 3660,
"s": 3511,
"text": "In case, you are interested in installing Lua in command line mode, you need to install MinGW or Cygwin and then compile and install Lua in windows."
},
{
"code": null,
"e": 3715,
"s": 3660,
"text": "To download and build Lua, use the following command −"
},
{
"code": null,
"e": 3823,
"s": 3715,
"text": "$ wget http://www.lua.org/ftp/lua-5.2.3.tar.gz\n$ tar zxf lua-5.2.3.tar.gz\n$ cd lua-5.2.3\n$ make linux test\n"
},
{
"code": null,
"e": 3997,
"s": 3823,
"text": "In order to install on other platforms like aix, ansi, bsd, generic linux, mingw, posix, solaris by replacing Linux in make Linux, test with the corresponding platform name."
},
{
"code": null,
"e": 4043,
"s": 3997,
"text": "We have a helloWorld.lua, in Lua as follows −"
},
{
"code": null,
"e": 4065,
"s": 4043,
"text": "print(\"Hello World!\")"
},
{
"code": null,
"e": 4218,
"s": 4065,
"text": "Now, we can build and run a Lua file say helloWorld.lua, by switching to the folder containing the file using cd, and then using the following command −"
},
{
"code": null,
"e": 4236,
"s": 4218,
"text": "$ lua helloWorld\n"
},
{
"code": null,
"e": 4269,
"s": 4236,
"text": "We can see the following output."
},
{
"code": null,
"e": 4283,
"s": 4269,
"text": "Hello World!\n"
},
{
"code": null,
"e": 4346,
"s": 4283,
"text": "To build/test Lua in the Mac OS X, use the following command −"
},
{
"code": null,
"e": 4461,
"s": 4346,
"text": "$ curl -R -O http://www.lua.org/ftp/lua-5.2.3.tar.gz\n$ tar zxf lua-5.2.3.tar.gz\n$ cd lua-5.2.3\n$ make macosx test\n"
},
{
"code": null,
"e": 4818,
"s": 4461,
"text": "In certain cases, you may not have installed the Xcode and command line tools. In such cases, you won’t be able to use the make command. Install Xcode from mac app store. Then go to Preferences of Xcode, and then switch to Downloads and install the component named \"Command Line Tools\". Once the process is completed, make command will be available to you."
},
{
"code": null,
"e": 4963,
"s": 4818,
"text": "It is not mandatory for you to execute the \"make macosx test\" statement. Even without executing this command, you can still use Lua in Mac OS X."
},
{
"code": null,
"e": 5010,
"s": 4963,
"text": "We have a helloWorld.lua, in Lua, as follows −"
},
{
"code": null,
"e": 5032,
"s": 5010,
"text": "print(\"Hello World!\")"
},
{
"code": null,
"e": 5183,
"s": 5032,
"text": "Now, we can build and run a Lua file say helloWorld.lua by switching to the folder containing the file using cd and then using the following command −"
},
{
"code": null,
"e": 5201,
"s": 5183,
"text": "$ lua helloWorld\n"
},
{
"code": null,
"e": 5235,
"s": 5201,
"text": "We can see the following output −"
},
{
"code": null,
"e": 5249,
"s": 5235,
"text": "Hello World!\n"
},
{
"code": null,
"e": 5479,
"s": 5249,
"text": "As mentioned earlier, for Windows SciTE, Lua IDE is the default IDE provided by the Lua creator team. The alternate IDE available is from ZeroBrane Studio, which is available across multiple platforms like Windows, Mac and Linux."
},
{
"code": null,
"e": 5746,
"s": 5479,
"text": "There are also plugins for eclipse that enable the Lua development. Using IDE makes it easier for development with features like code completion and is highly recommended. The IDE also provides interactive mode programming similar to the command line version of Lua."
},
{
"code": null,
"e": 5779,
"s": 5746,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5793,
"s": 5779,
"text": " Manish Gupta"
},
{
"code": null,
"e": 5826,
"s": 5793,
"text": "\n 80 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5842,
"s": 5826,
"text": " Sanjeev Mittal"
},
{
"code": null,
"e": 5877,
"s": 5842,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5893,
"s": 5877,
"text": " Mehmet GOKTEPE"
},
{
"code": null,
"e": 5900,
"s": 5893,
"text": " Print"
},
{
"code": null,
"e": 5911,
"s": 5900,
"text": " Add Notes"
}
] |
Swift - Deinitialization
|
Before a class instance needs to be deallocated 'deinitializer' has to be called to deallocate the memory space. The keyword 'deinit' is used to deallocate the memory spaces occupied by the system resources. Deinitialization is available only on class types.
Swift 4 automatically deallocates your instances when they are no longer needed, to free up resources. Swift 4 handles the memory management of instances through automatic reference counting (ARC), as described in Automatic Reference Counting. Typically you don't need to perform manual clean-up when your instances are deallocated. However, when you are working with your own resources, you might need to perform some additional clean-up yourself. For example, if you create a custom class to open a file and write some data to it, you might need to close the file before the class instance is deallocated.
var counter = 0; // for reference counting
class baseclass {
init() {
counter++;
}
deinit {
counter--;
}
}
var print: baseclass? = baseclass()
print(counter)
print = nil
print(counter)
When we run the above program using playground, we get the following result −
1
0
When print = nil statement is omitted the values of the counter retains the same since it is not deinitialized.
var counter = 0; // for reference counting
class baseclass {
init() {
counter++;
}
deinit {
counter--;
}
}
var print: baseclass? = baseclass()
print(counter)
print(counter)
When we run the above program using playground, we get the following result −
1
1
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2512,
"s": 2253,
"text": "Before a class instance needs to be deallocated 'deinitializer' has to be called to deallocate the memory space. The keyword 'deinit' is used to deallocate the memory spaces occupied by the system resources. Deinitialization is available only on class types."
},
{
"code": null,
"e": 3120,
"s": 2512,
"text": "Swift 4 automatically deallocates your instances when they are no longer needed, to free up resources. Swift 4 handles the memory management of instances through automatic reference counting (ARC), as described in Automatic Reference Counting. Typically you don't need to perform manual clean-up when your instances are deallocated. However, when you are working with your own resources, you might need to perform some additional clean-up yourself. For example, if you create a custom class to open a file and write some data to it, you might need to close the file before the class instance is deallocated."
},
{
"code": null,
"e": 3330,
"s": 3120,
"text": "var counter = 0; // for reference counting\nclass baseclass {\n init() {\n counter++;\n }\n deinit {\n counter--;\n }\n}\nvar print: baseclass? = baseclass()\n\nprint(counter)\nprint = nil\nprint(counter)"
},
{
"code": null,
"e": 3408,
"s": 3330,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 3413,
"s": 3408,
"text": "1\n0\n"
},
{
"code": null,
"e": 3525,
"s": 3413,
"text": "When print = nil statement is omitted the values of the counter retains the same since it is not deinitialized."
},
{
"code": null,
"e": 3723,
"s": 3525,
"text": "var counter = 0; // for reference counting\n\nclass baseclass {\n init() {\n counter++;\n }\n deinit {\n counter--;\n }\n}\nvar print: baseclass? = baseclass()\nprint(counter)\nprint(counter)"
},
{
"code": null,
"e": 3801,
"s": 3723,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 3806,
"s": 3801,
"text": "1\n1\n"
},
{
"code": null,
"e": 3839,
"s": 3806,
"text": "\n 38 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3854,
"s": 3839,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 3887,
"s": 3854,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3906,
"s": 3887,
"text": " Three Millennials"
},
{
"code": null,
"e": 3938,
"s": 3906,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3957,
"s": 3938,
"text": " Three Millennials"
},
{
"code": null,
"e": 3990,
"s": 3957,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4007,
"s": 3990,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4039,
"s": 4007,
"text": "\n 12 Lectures \n 39 mins\n"
},
{
"code": null,
"e": 4059,
"s": 4039,
"text": " Devasena Rajendran"
},
{
"code": null,
"e": 4094,
"s": 4059,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4111,
"s": 4094,
"text": " Grant Klimaytys"
},
{
"code": null,
"e": 4118,
"s": 4111,
"text": " Print"
},
{
"code": null,
"e": 4129,
"s": 4118,
"text": " Add Notes"
}
] |
Android - Emulator
|
The Android SDK includes a virtual mobile device emulator that runs on your computer. The emulator lets you prototype, develop and test Android applications without using a physical device.
In this chapter we are going to explore different functionalities in the emulator that are present in the real android device.
If you want to emulate a real device, first crate an AVD with the same device configurations as real device, then launch this AVD from AVD manager.
Usually by default when you launch the emulator, its orientation is vertical, but you can change it orientation by pressing Ctrl+F11 key from keyboard.
First launch the emulator. It is shown in the picture below −
Once it is launched, press Ctrl+F11 key to change its orientation. It is shown below −
Apart from just orientation commands, there are other very useful commands of emulator that you should keep in mind while using emulator. They are listed below −
Home
Shifts to main screen
F2
Toggles context sensitive menu
F3
Bring out call log
F4
End call
F5
Search
F6
Toggle trackball mode
F7
Power button
F8
Toggle data network
Ctrl+F5
Ring Volume up
Ctrl+F6
Ring Volume down
You can emulate sending SMS to your emulator. There are two ways to do that. You can do that from DDMS which can be found in Android studio, or from Telnet.(Network utility found in windows).
Telnet is not enabled by default in windows. You have to enable it to use it. Once enabled you can go to command prompt and start telnet by typing telnet.
In order to send SMS , note down the AVD number which can be found on the title bar of the emulator. It could be like this 5554 e.t.c. Once noted , type this command in command prompt.
telnet localhost 5554
Press enter when you type the command. It is shown below in the figure.
You will see that you are now connected to your emulator. Now type this command to send message.
sms send 1234 "hello"
Once you type this command , hit enter. Now look at the AVD. You will receive a notification displaying that you got a new text message. It is shown below −
You can easily make phone calls to your emulator using telent client. You need to connect to your emulator from telnet. It is discussed in the sending sms topic above.
After that you will type this command in the telent window to make a call. Its syntax is given below −
gsm call 1234
Once you type this command , hit enter. Now look at the AVD. You will receive a call from the number your put in the command. It is shown below −
You can easily transfer files into the emulator and vice versa. In order to do that, you need to select the DDMS utility in Android studio. After that select the file explorer tab. It is shown below −
Browse through the explorer and make new folder , view existing contents e.t.c.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3797,
"s": 3607,
"text": "The Android SDK includes a virtual mobile device emulator that runs on your computer. The emulator lets you prototype, develop and test Android applications without using a physical device."
},
{
"code": null,
"e": 3924,
"s": 3797,
"text": "In this chapter we are going to explore different functionalities in the emulator that are present in the real android device."
},
{
"code": null,
"e": 4072,
"s": 3924,
"text": "If you want to emulate a real device, first crate an AVD with the same device configurations as real device, then launch this AVD from AVD manager."
},
{
"code": null,
"e": 4224,
"s": 4072,
"text": "Usually by default when you launch the emulator, its orientation is vertical, but you can change it orientation by pressing Ctrl+F11 key from keyboard."
},
{
"code": null,
"e": 4286,
"s": 4224,
"text": "First launch the emulator. It is shown in the picture below −"
},
{
"code": null,
"e": 4373,
"s": 4286,
"text": "Once it is launched, press Ctrl+F11 key to change its orientation. It is shown below −"
},
{
"code": null,
"e": 4535,
"s": 4373,
"text": "Apart from just orientation commands, there are other very useful commands of emulator that you should keep in mind while using emulator. They are listed below −"
},
{
"code": null,
"e": 4540,
"s": 4535,
"text": "Home"
},
{
"code": null,
"e": 4562,
"s": 4540,
"text": "Shifts to main screen"
},
{
"code": null,
"e": 4565,
"s": 4562,
"text": "F2"
},
{
"code": null,
"e": 4596,
"s": 4565,
"text": "Toggles context sensitive menu"
},
{
"code": null,
"e": 4599,
"s": 4596,
"text": "F3"
},
{
"code": null,
"e": 4618,
"s": 4599,
"text": "Bring out call log"
},
{
"code": null,
"e": 4621,
"s": 4618,
"text": "F4"
},
{
"code": null,
"e": 4630,
"s": 4621,
"text": "End call"
},
{
"code": null,
"e": 4633,
"s": 4630,
"text": "F5"
},
{
"code": null,
"e": 4640,
"s": 4633,
"text": "Search"
},
{
"code": null,
"e": 4643,
"s": 4640,
"text": "F6"
},
{
"code": null,
"e": 4665,
"s": 4643,
"text": "Toggle trackball mode"
},
{
"code": null,
"e": 4668,
"s": 4665,
"text": "F7"
},
{
"code": null,
"e": 4681,
"s": 4668,
"text": "Power button"
},
{
"code": null,
"e": 4684,
"s": 4681,
"text": "F8"
},
{
"code": null,
"e": 4704,
"s": 4684,
"text": "Toggle data network"
},
{
"code": null,
"e": 4712,
"s": 4704,
"text": "Ctrl+F5"
},
{
"code": null,
"e": 4727,
"s": 4712,
"text": "Ring Volume up"
},
{
"code": null,
"e": 4735,
"s": 4727,
"text": "Ctrl+F6"
},
{
"code": null,
"e": 4752,
"s": 4735,
"text": "Ring Volume down"
},
{
"code": null,
"e": 4944,
"s": 4752,
"text": "You can emulate sending SMS to your emulator. There are two ways to do that. You can do that from DDMS which can be found in Android studio, or from Telnet.(Network utility found in windows)."
},
{
"code": null,
"e": 5099,
"s": 4944,
"text": "Telnet is not enabled by default in windows. You have to enable it to use it. Once enabled you can go to command prompt and start telnet by typing telnet."
},
{
"code": null,
"e": 5284,
"s": 5099,
"text": "In order to send SMS , note down the AVD number which can be found on the title bar of the emulator. It could be like this 5554 e.t.c. Once noted , type this command in command prompt."
},
{
"code": null,
"e": 5307,
"s": 5284,
"text": "telnet localhost 5554\n"
},
{
"code": null,
"e": 5379,
"s": 5307,
"text": "Press enter when you type the command. It is shown below in the figure."
},
{
"code": null,
"e": 5476,
"s": 5379,
"text": "You will see that you are now connected to your emulator. Now type this command to send message."
},
{
"code": null,
"e": 5499,
"s": 5476,
"text": "sms send 1234 \"hello\"\n"
},
{
"code": null,
"e": 5656,
"s": 5499,
"text": "Once you type this command , hit enter. Now look at the AVD. You will receive a notification displaying that you got a new text message. It is shown below −"
},
{
"code": null,
"e": 5824,
"s": 5656,
"text": "You can easily make phone calls to your emulator using telent client. You need to connect to your emulator from telnet. It is discussed in the sending sms topic above."
},
{
"code": null,
"e": 5927,
"s": 5824,
"text": "After that you will type this command in the telent window to make a call. Its syntax is given below −"
},
{
"code": null,
"e": 5942,
"s": 5927,
"text": "gsm call 1234\n"
},
{
"code": null,
"e": 6088,
"s": 5942,
"text": "Once you type this command , hit enter. Now look at the AVD. You will receive a call from the number your put in the command. It is shown below −"
},
{
"code": null,
"e": 6289,
"s": 6088,
"text": "You can easily transfer files into the emulator and vice versa. In order to do that, you need to select the DDMS utility in Android studio. After that select the file explorer tab. It is shown below −"
},
{
"code": null,
"e": 6369,
"s": 6289,
"text": "Browse through the explorer and make new folder , view existing contents e.t.c."
},
{
"code": null,
"e": 6404,
"s": 6369,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6416,
"s": 6404,
"text": " Aditya Dua"
},
{
"code": null,
"e": 6451,
"s": 6416,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6465,
"s": 6451,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 6497,
"s": 6465,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6514,
"s": 6497,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6549,
"s": 6514,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6566,
"s": 6549,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6601,
"s": 6566,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6618,
"s": 6601,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6651,
"s": 6618,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6668,
"s": 6651,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6675,
"s": 6668,
"text": " Print"
},
{
"code": null,
"e": 6686,
"s": 6675,
"text": " Add Notes"
}
] |
Get and Set Working Directory in R - GeeksforGeeks
|
30 Jun, 2021
In this article, we are going to see how to get and set a working directory in R Programming Language.
getwd(): The getwd() method is used to gather information about the current working pathname or default working directory. This function has no arguments. It returns an absolute pathname. It returns NULL in case there is not any working directory.
getwd()
Code:
R
# getting the working directorygetwd()
Output
[1] "/Users/mallikagupta/Desktop"
setwd(): This method is used to set the specified pathname as the current working space directory of the R console.
Syntax: setwd(dir)
Where, dir is specify a working directory.
The setwd() function allows us to move a hierarchy level up in the folder domain using the “..” argument in this method.
Code:
R
# getting the working directoryprint ("Current working directory")getwd() # set working directory to its parents directorysetwd("..")print ("Modified working directory")getwd()
Output
[1] "Current working directory"
[1] "/Users/mallikagupta/Desktop"
[1] "Modified working directory"
[1] "/Users/mallikagupta"
The subfolders can be easily accessed once the root directory has been set or is available by further specifying the character name of the sub-directory as a character string in the function arguments.
R
# setting parent directorysetwd("/Users/mallikagupta/Desktop") # adding sub directorysetwd("GFG")print ("Current working directory") # getting the working directorygetwd()
Output
[1] "Current working directory"
[1] "/Users/mallikagupta/Desktop/GFG"
Picked
R directory-programs
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Control Statements in R Programming
How to import an Excel File into R ?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
|
[
{
"code": null,
"e": 25162,
"s": 25134,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25265,
"s": 25162,
"text": "In this article, we are going to see how to get and set a working directory in R Programming Language."
},
{
"code": null,
"e": 25514,
"s": 25265,
"text": "getwd(): The getwd() method is used to gather information about the current working pathname or default working directory. This function has no arguments. It returns an absolute pathname. It returns NULL in case there is not any working directory. "
},
{
"code": null,
"e": 25522,
"s": 25514,
"text": "getwd()"
},
{
"code": null,
"e": 25528,
"s": 25522,
"text": "Code:"
},
{
"code": null,
"e": 25530,
"s": 25528,
"text": "R"
},
{
"code": "# getting the working directorygetwd()",
"e": 25569,
"s": 25530,
"text": null
},
{
"code": null,
"e": 25576,
"s": 25569,
"text": "Output"
},
{
"code": null,
"e": 25610,
"s": 25576,
"text": "[1] \"/Users/mallikagupta/Desktop\""
},
{
"code": null,
"e": 25727,
"s": 25610,
"text": "setwd(): This method is used to set the specified pathname as the current working space directory of the R console. "
},
{
"code": null,
"e": 25747,
"s": 25727,
"text": "Syntax: setwd(dir) "
},
{
"code": null,
"e": 25791,
"s": 25747,
"text": "Where, dir is specify a working directory. "
},
{
"code": null,
"e": 25913,
"s": 25791,
"text": "The setwd() function allows us to move a hierarchy level up in the folder domain using the “..” argument in this method. "
},
{
"code": null,
"e": 25919,
"s": 25913,
"text": "Code:"
},
{
"code": null,
"e": 25921,
"s": 25919,
"text": "R"
},
{
"code": "# getting the working directoryprint (\"Current working directory\")getwd() # set working directory to its parents directorysetwd(\"..\")print (\"Modified working directory\")getwd()",
"e": 26099,
"s": 25921,
"text": null
},
{
"code": null,
"e": 26106,
"s": 26099,
"text": "Output"
},
{
"code": null,
"e": 26233,
"s": 26106,
"text": "[1] \"Current working directory\"\n[1] \"/Users/mallikagupta/Desktop\" \n[1] \"Modified working directory\" \n[1] \"/Users/mallikagupta\""
},
{
"code": null,
"e": 26436,
"s": 26233,
"text": "The subfolders can be easily accessed once the root directory has been set or is available by further specifying the character name of the sub-directory as a character string in the function arguments. "
},
{
"code": null,
"e": 26438,
"s": 26436,
"text": "R"
},
{
"code": "# setting parent directorysetwd(\"/Users/mallikagupta/Desktop\") # adding sub directorysetwd(\"GFG\")print (\"Current working directory\") # getting the working directorygetwd()",
"e": 26612,
"s": 26438,
"text": null
},
{
"code": null,
"e": 26619,
"s": 26612,
"text": "Output"
},
{
"code": null,
"e": 26690,
"s": 26619,
"text": "[1] \"Current working directory\" \n[1] \"/Users/mallikagupta/Desktop/GFG\""
},
{
"code": null,
"e": 26697,
"s": 26690,
"text": "Picked"
},
{
"code": null,
"e": 26718,
"s": 26697,
"text": "R directory-programs"
},
{
"code": null,
"e": 26729,
"s": 26718,
"text": "R Language"
},
{
"code": null,
"e": 26827,
"s": 26729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26836,
"s": 26827,
"text": "Comments"
},
{
"code": null,
"e": 26849,
"s": 26836,
"text": "Old Comments"
},
{
"code": null,
"e": 26901,
"s": 26849,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26925,
"s": 26901,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 26963,
"s": 26925,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26998,
"s": 26963,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27035,
"s": 26998,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 27093,
"s": 27035,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27129,
"s": 27093,
"text": "Control Statements in R Programming"
},
{
"code": null,
"e": 27166,
"s": 27129,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 27209,
"s": 27166,
"text": "Replace Specific Characters in String in R"
}
] |
How to update only one property in MongoDB?
|
To update only one property, use $addToSet in MongoDB. Let us create a collection with documents −
> db.demo336.insertOne({"Name":"Chris","Score":[45,67,78]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522cb1f8647eb59e562097")
}
> db.demo336.insertOne({"Name":"David","Score":[89,93,47]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522cb2f8647eb59e562098")
}
Display all documents from a collection with the help of find() method −
> db.demo336.find();
This will produce the following output −
{ "_id" : ObjectId("5e522cb1f8647eb59e562097"), "Name" : "Chris", "Score" : [ 45, 67, 78 ] }
{ "_id" : ObjectId("5e522cb2f8647eb59e562098"), "Name" : "David", "Score" : [ 89, 93, 47 ] }
Following is the query to update only one property in MongoDB −
> db.demo336.update({Name:"David"},{ $addToSet: {Score: [56,34,71] }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo336.find();
This will produce the following output −
{ "_id" : ObjectId("5e522cb1f8647eb59e562097"), "Name" : "Chris", "Score" : [ 45, 67, 78 ] }
{ "_id" : ObjectId("5e522cb2f8647eb59e562098"), "Name" : "David", "Score" : [ 89, 93, 47, [ 56, 34, 71 ] ] }
|
[
{
"code": null,
"e": 1161,
"s": 1062,
"text": "To update only one property, use $addToSet in MongoDB. Let us create a collection with documents −"
},
{
"code": null,
"e": 1453,
"s": 1161,
"text": "> db.demo336.insertOne({\"Name\":\"Chris\",\"Score\":[45,67,78]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e522cb1f8647eb59e562097\")\n}\n> db.demo336.insertOne({\"Name\":\"David\",\"Score\":[89,93,47]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e522cb2f8647eb59e562098\")\n}"
},
{
"code": null,
"e": 1526,
"s": 1453,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1547,
"s": 1526,
"text": "> db.demo336.find();"
},
{
"code": null,
"e": 1588,
"s": 1547,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1774,
"s": 1588,
"text": "{ \"_id\" : ObjectId(\"5e522cb1f8647eb59e562097\"), \"Name\" : \"Chris\", \"Score\" : [ 45, 67, 78 ] }\n{ \"_id\" : ObjectId(\"5e522cb2f8647eb59e562098\"), \"Name\" : \"David\", \"Score\" : [ 89, 93, 47 ] }"
},
{
"code": null,
"e": 1838,
"s": 1774,
"text": "Following is the query to update only one property in MongoDB −"
},
{
"code": null,
"e": 1976,
"s": 1838,
"text": "> db.demo336.update({Name:\"David\"},{ $addToSet: {Score: [56,34,71] }});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2049,
"s": 1976,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2070,
"s": 2049,
"text": "> db.demo336.find();"
},
{
"code": null,
"e": 2111,
"s": 2070,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2313,
"s": 2111,
"text": "{ \"_id\" : ObjectId(\"5e522cb1f8647eb59e562097\"), \"Name\" : \"Chris\", \"Score\" : [ 45, 67, 78 ] }\n{ \"_id\" : ObjectId(\"5e522cb2f8647eb59e562098\"), \"Name\" : \"David\", \"Score\" : [ 89, 93, 47, [ 56, 34, 71 ] ] }"
}
] |
Parse and format a number to decimal in Java
|
To parse and format a number to decimal, try the following code.
Live Demo
public class Demo {
public static void main( String args[] ) {
int val = Integer.parseInt("5");
String str = Integer.toString(val);
System.out.println(str);
}
}
5
In the above program, we have used the Integer.parseInt() and Integer.toString() method to convert a number to decimal.
int val = Integer.parseInt("5");
String str = Integer.toString(val);
The toString() method above represents a value in string and formats.
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "To parse and format a number to decimal, try the following code."
},
{
"code": null,
"e": 1138,
"s": 1127,
"text": " Live Demo"
},
{
"code": null,
"e": 1323,
"s": 1138,
"text": "public class Demo {\n public static void main( String args[] ) {\n int val = Integer.parseInt(\"5\");\n String str = Integer.toString(val);\n System.out.println(str);\n }\n}"
},
{
"code": null,
"e": 1325,
"s": 1323,
"text": "5"
},
{
"code": null,
"e": 1445,
"s": 1325,
"text": "In the above program, we have used the Integer.parseInt() and Integer.toString() method to convert a number to decimal."
},
{
"code": null,
"e": 1514,
"s": 1445,
"text": "int val = Integer.parseInt(\"5\");\nString str = Integer.toString(val);"
},
{
"code": null,
"e": 1584,
"s": 1514,
"text": "The toString() method above represents a value in string and formats."
}
] |
Java Examples - Spliting a String
|
How to split a string into a number of substrings ?
Following example splits a string into a number of substrings with the help of str split(string) method and then prints the substrings.
public class JavaStringSplitEmp{
public static void main(String args[]) {
String str = "jan-feb-march";
String[] temp;
String delimeter = "-";
temp = str.split(delimeter);
for(int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
System.out.println("");
str = "jan.feb.march";
delimeter = "\\.";
temp = str.split(delimeter);
}
for(int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
System.out.println("");
temp = str.split(delimeter,2);
for(int j = 0; j < temp.length; j++){
System.out.println(temp[j]);
}
}
}
}
The above code sample will produce the following result.
jan
feb
march
jan
jan
feb.march
feb.march
jan
feb.march
This is another example of string split
public class HelloWorld {
public static void main(String args[]) {
String s1 = "t u t o r i a l s";
String[] words = s1.split("\\s");
for(String w:words) {
System.out.println(w);
}
}
}
The above code sample will produce the following result.
t
u
t
o
r
i
a
l
s
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2120,
"s": 2068,
"text": "How to split a string into a number of substrings ?"
},
{
"code": null,
"e": 2256,
"s": 2120,
"text": "Following example splits a string into a number of substrings with the help of str split(string) method and then prints the substrings."
},
{
"code": null,
"e": 2964,
"s": 2256,
"text": "public class JavaStringSplitEmp{\n public static void main(String args[]) {\n String str = \"jan-feb-march\";\n String[] temp;\n String delimeter = \"-\";\n temp = str.split(delimeter);\n \n for(int i = 0; i < temp.length; i++) {\n System.out.println(temp[i]);\n System.out.println(\"\");\n str = \"jan.feb.march\";\n delimeter = \"\\\\.\";\n temp = str.split(delimeter);\n }\n for(int i = 0; i < temp.length; i++) {\n System.out.println(temp[i]);\n System.out.println(\"\");\n temp = str.split(delimeter,2);\n \n for(int j = 0; j < temp.length; j++){\n System.out.println(temp[j]);\n }\n }\n }\n}"
},
{
"code": null,
"e": 3021,
"s": 2964,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3083,
"s": 3021,
"text": "jan\n\nfeb\n\nmarch\n\njan\n\njan\nfeb.march\nfeb.march\n\njan\nfeb.march\n"
},
{
"code": null,
"e": 3123,
"s": 3083,
"text": "This is another example of string split"
},
{
"code": null,
"e": 3353,
"s": 3123,
"text": "public class HelloWorld {\n public static void main(String args[]) {\n String s1 = \"t u t o r i a l s\"; \n String[] words = s1.split(\"\\\\s\"); \n for(String w:words) {\n System.out.println(w); \n } \n }\n}"
},
{
"code": null,
"e": 3410,
"s": 3353,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3438,
"s": 3410,
"text": "t \nu \nt \no \nr \ni \na \nl \ns \n"
},
{
"code": null,
"e": 3445,
"s": 3438,
"text": " Print"
},
{
"code": null,
"e": 3456,
"s": 3445,
"text": " Add Notes"
}
] |
Address Binding and its Types - GeeksforGeeks
|
23 Oct, 2020
In this article, We are going to cover address binding with the help of an example and Its types like compile time, load time, and execution time address binding. Let’s discuss one by one.
Address Binding :The Association of program instruction and data to the actual physical memory locations is called the Address Binding. Let’s consider the following example given below for better understanding.
Consider a program P1 has the set of instruction such that I1, I2, I3, I4, and program counter value is 10, 20, 30, 40 respectively.
Program P1
I1 --> 10
I2 --> 20
I3 --> 30
I4 --> 40
Program Counter = 10, 20, 30, 40
Types of Address Binding :
Address Binding divided into three types as follows.
Compile-time Address BindingLoad time Address BindingExecution time Address Binding
Compile-time Address Binding
Load time Address Binding
Execution time Address Binding
Compile-time Address Binding :
If the compiler is responsible for performing address binding then it is called compile-time address binding.
It will be done before loading the program into memory.
The compiler requires interacts with an OS memory manager to perform compile-time address binding.
Load time Address Binding :
It will be done after loading the program into memory.
This type of address binding will be done by the OS memory manager i.e loader.
Execution time or dynamic Address Binding :
It will be postponed even after loading the program into memory.
The program will be kept on changing the locations in memory until the time of program execution.
The dynamic type of address binding done by the processor at the time of program execution.
Note :The majority of the Operating System practically implement dynamic loading, dynamic linking, dynamic address binding. For example – Windows, Linux, Unix all popular OS.
Compiler Design
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Difference between Top down parsing and Bottom up parsing
Loop Optimization in Compiler Design
S - attributed and L - attributed SDTs in Syntax directed translation
Why FIRST and FOLLOW in Compiler Design?
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
|
[
{
"code": null,
"e": 24446,
"s": 24418,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 24635,
"s": 24446,
"text": "In this article, We are going to cover address binding with the help of an example and Its types like compile time, load time, and execution time address binding. Let’s discuss one by one."
},
{
"code": null,
"e": 24846,
"s": 24635,
"text": "Address Binding :The Association of program instruction and data to the actual physical memory locations is called the Address Binding. Let’s consider the following example given below for better understanding."
},
{
"code": null,
"e": 24979,
"s": 24846,
"text": "Consider a program P1 has the set of instruction such that I1, I2, I3, I4, and program counter value is 10, 20, 30, 40 respectively."
},
{
"code": null,
"e": 25068,
"s": 24979,
"text": "Program P1\nI1 --> 10 \nI2 --> 20 \nI3 --> 30 \nI4 --> 40\n\nProgram Counter = 10, 20, 30, 40\n"
},
{
"code": null,
"e": 25095,
"s": 25068,
"text": "Types of Address Binding :"
},
{
"code": null,
"e": 25148,
"s": 25095,
"text": "Address Binding divided into three types as follows."
},
{
"code": null,
"e": 25232,
"s": 25148,
"text": "Compile-time Address BindingLoad time Address BindingExecution time Address Binding"
},
{
"code": null,
"e": 25261,
"s": 25232,
"text": "Compile-time Address Binding"
},
{
"code": null,
"e": 25287,
"s": 25261,
"text": "Load time Address Binding"
},
{
"code": null,
"e": 25318,
"s": 25287,
"text": "Execution time Address Binding"
},
{
"code": null,
"e": 25349,
"s": 25318,
"text": "Compile-time Address Binding :"
},
{
"code": null,
"e": 25459,
"s": 25349,
"text": "If the compiler is responsible for performing address binding then it is called compile-time address binding."
},
{
"code": null,
"e": 25515,
"s": 25459,
"text": "It will be done before loading the program into memory."
},
{
"code": null,
"e": 25614,
"s": 25515,
"text": "The compiler requires interacts with an OS memory manager to perform compile-time address binding."
},
{
"code": null,
"e": 25642,
"s": 25614,
"text": "Load time Address Binding :"
},
{
"code": null,
"e": 25697,
"s": 25642,
"text": "It will be done after loading the program into memory."
},
{
"code": null,
"e": 25776,
"s": 25697,
"text": "This type of address binding will be done by the OS memory manager i.e loader."
},
{
"code": null,
"e": 25820,
"s": 25776,
"text": "Execution time or dynamic Address Binding :"
},
{
"code": null,
"e": 25885,
"s": 25820,
"text": "It will be postponed even after loading the program into memory."
},
{
"code": null,
"e": 25983,
"s": 25885,
"text": "The program will be kept on changing the locations in memory until the time of program execution."
},
{
"code": null,
"e": 26075,
"s": 25983,
"text": "The dynamic type of address binding done by the processor at the time of program execution."
},
{
"code": null,
"e": 26250,
"s": 26075,
"text": "Note :The majority of the Operating System practically implement dynamic loading, dynamic linking, dynamic address binding. For example – Windows, Linux, Unix all popular OS."
},
{
"code": null,
"e": 26266,
"s": 26250,
"text": "Compiler Design"
},
{
"code": null,
"e": 26274,
"s": 26266,
"text": "GATE CS"
},
{
"code": null,
"e": 26292,
"s": 26274,
"text": "Operating Systems"
},
{
"code": null,
"e": 26310,
"s": 26292,
"text": "Operating Systems"
},
{
"code": null,
"e": 26408,
"s": 26310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26466,
"s": 26408,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 26524,
"s": 26466,
"text": "Difference between Top down parsing and Bottom up parsing"
},
{
"code": null,
"e": 26561,
"s": 26524,
"text": "Loop Optimization in Compiler Design"
},
{
"code": null,
"e": 26631,
"s": 26561,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 26672,
"s": 26631,
"text": "Why FIRST and FOLLOW in Compiler Design?"
},
{
"code": null,
"e": 26692,
"s": 26672,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 26716,
"s": 26692,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 26729,
"s": 26716,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 26778,
"s": 26729,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
How to add a black hover to an image using bootstrap? - GeeksforGeeks
|
15 Sep, 2020
Bootstrap is a popular CSS framework widely used by frontend developers to create interactive UI for web applications. Bootstrap is widely used because of its simplicity and ease to use. BootStrap allows multiple utilities to make images interactive. One of these utilities can be changing the color of the image when hovered over. Hovering is basically moving the cursor over the image. The code snippet below demonstrates how to add a black hover to an image using bootstrap.
First Approach:In this method, the content-overlay class specifies the required properties of the image while the mouse hovers over it. The background property in the content-overlay class specifies the opacity of the image when the user hovers over it. The content-details class specifies the set of properties that are used for the content displayed on top of the image when the mouse hovers over it.Example:
<!DOCTYPE html><html> <head> <title></title> <!-- importing bootstrap cdn--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <style> /*setting the properties for container which contains the image */ .container { margin-top: 100px; } /*setting the properties for title*/ .title { color: #1a1a1a; text-align: center; margin-bottom: 10px; } /*setting the properties of content within the image*/ .content { position: relative; width: 90%; max-width: 400px; margin: auto; overflow: hidden; } /* rgb(0,0,0) indicates black and the fourth parameter is the opacity */ .content .content-overlay { /*setting 0.8 to 1 will turn the overlay opaque*/ background: rgba(0, 0, 0, 0.8); position: absolute; height: 99%; width: 100%; left: 0; top: 0; bottom: 0; right: 0; opacity: 0; /*transition time and effect*/ -webkit-transition: all 0.4s ease-in-out 0s; /*transition time and effect*/ -moz-transition: all 0.4s ease-in-out 0s; /*transition time and effect*/ transition: all 0.4s ease-in-out 0s; } /* setting hover properties */ .content:hover .content-overlay { opacity: 1; } .content-image { width: 100%; } /*setting image properties*/ img { box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); border-radius: 5px; } .content-details { position: absolute; text-align: center; padding-left: 1em; padding-right: 1em; width: 100%; top: 50%; left: 50%; opacity: 0; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); transform: translate(-50%, -50%); /*transition time and effect*/ -webkit-transition: all 0.3s ease-in-out 0s; /*transition time and effect*/ -moz-transition: all 0.3s ease-in-out 0s; /*transition time and effect*/ transition: all 0.3s ease-in-out 0s; } .content:hover .content-details { top: 50%; left: 50%; opacity: 1; } .content-details h3 { color: #fff; font-weight: 500; letter-spacing: 0.15em; margin-bottom: 0.5em; text-transform: uppercase; } .content-details p { color: #fff; font-size: 0.8em; } </style> </head> <body> <div class="container"> <div class="content"> <div class="content-overlay"></div> <img class="content-image" src="IMAGE.png" /> <div class="content-details"> <h3 class="content-title"> Workstation</h3> <p class="content-text"> Hover out to view image</p> </div> </div> </div> </body></html>
Output:
Alternate approach:The second approach also deals with hovering effect but here the hovering opacity is set to 1 which means the underlying image becomes completely hidden. The overlay class contains the set of specifications for the image when hovered over. The background color is set to black. The transition time and nature is also set.Example:
<!DOCTYPE html><html> <head> <!--helps in scaling the web page according to the device screen size--> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> .container { position: relative; width: 50%; } /*image class sets the properties of the image used*/ .image { display: block; width: 100%; height: auto; } /*overlay class sets the properties of the overlay image*/ .overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; width: 100%; opacity: 0; /*the transition time between the actual image to overlay*/ transition: 0.3s ease; /*ensures black hover on the image*/ background-color: black; } /*hovering property is set*/ .container:hover .overlay { opacity: 1; } /*properties for the text on the overlay image*/ .text { color: white; font-size: 20px; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; } </style> </head> <body> <h2>Adding black color to image using the overlay class</h2> <p>Hover over the image to see the effect.</p> <div class="container"> <img src="IMAGE.png" /> <div class="overlay"> <div class="text">Click to view image</div> </div> </div> </body></html>
Output:
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to align navbar items to the right in Bootstrap 4 ?
How to pass data into a bootstrap modal?
How to Show Images on Click 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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 28440,
"s": 28412,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 28918,
"s": 28440,
"text": "Bootstrap is a popular CSS framework widely used by frontend developers to create interactive UI for web applications. Bootstrap is widely used because of its simplicity and ease to use. BootStrap allows multiple utilities to make images interactive. One of these utilities can be changing the color of the image when hovered over. Hovering is basically moving the cursor over the image. The code snippet below demonstrates how to add a black hover to an image using bootstrap."
},
{
"code": null,
"e": 29329,
"s": 28918,
"text": "First Approach:In this method, the content-overlay class specifies the required properties of the image while the mouse hovers over it. The background property in the content-overlay class specifies the opacity of the image when the user hovers over it. The content-details class specifies the set of properties that are used for the content displayed on top of the image when the mouse hovers over it.Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title></title> <!-- importing bootstrap cdn--> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\" /> <style> /*setting the properties for container which contains the image */ .container { margin-top: 100px; } /*setting the properties for title*/ .title { color: #1a1a1a; text-align: center; margin-bottom: 10px; } /*setting the properties of content within the image*/ .content { position: relative; width: 90%; max-width: 400px; margin: auto; overflow: hidden; } /* rgb(0,0,0) indicates black and the fourth parameter is the opacity */ .content .content-overlay { /*setting 0.8 to 1 will turn the overlay opaque*/ background: rgba(0, 0, 0, 0.8); position: absolute; height: 99%; width: 100%; left: 0; top: 0; bottom: 0; right: 0; opacity: 0; /*transition time and effect*/ -webkit-transition: all 0.4s ease-in-out 0s; /*transition time and effect*/ -moz-transition: all 0.4s ease-in-out 0s; /*transition time and effect*/ transition: all 0.4s ease-in-out 0s; } /* setting hover properties */ .content:hover .content-overlay { opacity: 1; } .content-image { width: 100%; } /*setting image properties*/ img { box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); border-radius: 5px; } .content-details { position: absolute; text-align: center; padding-left: 1em; padding-right: 1em; width: 100%; top: 50%; left: 50%; opacity: 0; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); transform: translate(-50%, -50%); /*transition time and effect*/ -webkit-transition: all 0.3s ease-in-out 0s; /*transition time and effect*/ -moz-transition: all 0.3s ease-in-out 0s; /*transition time and effect*/ transition: all 0.3s ease-in-out 0s; } .content:hover .content-details { top: 50%; left: 50%; opacity: 1; } .content-details h3 { color: #fff; font-weight: 500; letter-spacing: 0.15em; margin-bottom: 0.5em; text-transform: uppercase; } .content-details p { color: #fff; font-size: 0.8em; } </style> </head> <body> <div class=\"container\"> <div class=\"content\"> <div class=\"content-overlay\"></div> <img class=\"content-image\" src=\"IMAGE.png\" /> <div class=\"content-details\"> <h3 class=\"content-title\"> Workstation</h3> <p class=\"content-text\"> Hover out to view image</p> </div> </div> </div> </body></html>",
"e": 33309,
"s": 29329,
"text": null
},
{
"code": null,
"e": 33317,
"s": 33309,
"text": "Output:"
},
{
"code": null,
"e": 33666,
"s": 33317,
"text": "Alternate approach:The second approach also deals with hovering effect but here the hovering opacity is set to 1 which means the underlying image becomes completely hidden. The overlay class contains the set of specifications for the image when hovered over. The background color is set to black. The transition time and nature is also set.Example:"
},
{
"code": " <!DOCTYPE html><html> <head> <!--helps in scaling the web page according to the device screen size--> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <style> .container { position: relative; width: 50%; } /*image class sets the properties of the image used*/ .image { display: block; width: 100%; height: auto; } /*overlay class sets the properties of the overlay image*/ .overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; width: 100%; opacity: 0; /*the transition time between the actual image to overlay*/ transition: 0.3s ease; /*ensures black hover on the image*/ background-color: black; } /*hovering property is set*/ .container:hover .overlay { opacity: 1; } /*properties for the text on the overlay image*/ .text { color: white; font-size: 20px; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; } </style> </head> <body> <h2>Adding black color to image using the overlay class</h2> <p>Hover over the image to see the effect.</p> <div class=\"container\"> <img src=\"IMAGE.png\" /> <div class=\"overlay\"> <div class=\"text\">Click to view image</div> </div> </div> </body></html>",
"e": 35722,
"s": 33666,
"text": null
},
{
"code": null,
"e": 35730,
"s": 35722,
"text": "Output:"
},
{
"code": null,
"e": 35745,
"s": 35730,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 35752,
"s": 35745,
"text": "Picked"
},
{
"code": null,
"e": 35762,
"s": 35752,
"text": "Bootstrap"
},
{
"code": null,
"e": 35779,
"s": 35762,
"text": "Web Technologies"
},
{
"code": null,
"e": 35877,
"s": 35779,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35927,
"s": 35877,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 35956,
"s": 35927,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 36012,
"s": 35956,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 36053,
"s": 36012,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 36094,
"s": 36053,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 36136,
"s": 36094,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 36169,
"s": 36136,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 36212,
"s": 36169,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 36274,
"s": 36212,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How do I get the 'state' of a Tkinter Checkbutton?
|
Tkinter provides a variety of input widgets such as entry widget, text widget, listbox, combobox, spinbox, checkbox, etc. Checkboxes are used for taking validity input and the state gets active whenever the user clicks on the checkbutton. In terms of a particular application, we can check the state of the tkinter CheckButtons by using the state() method. It prints the actual state of the tkinter checkbuttons.
#Import the required library
from tkinter import*
from tkinter import ttk
#Create an instance of tkinter frame
win= Tk()
#Set the geometry
win.geometry("750x250")
#Define geometry of the window
win.geometry("750x250")
#Create CheckButtons
chk= ttk.Checkbutton(win, text="Python")
chk.pack()
chk.config(state=NORMAL)
print(chk.state())
win.mainloop()
Running the example code will display a window with a check button that is initially defined as normal state.
Now, remove the line "win.mainloop()" from the program to print the state of the checkbox on the console.
('alternate',)
|
[
{
"code": null,
"e": 1475,
"s": 1062,
"text": "Tkinter provides a variety of input widgets such as entry widget, text widget, listbox, combobox, spinbox, checkbox, etc. Checkboxes are used for taking validity input and the state gets active whenever the user clicks on the checkbutton. In terms of a particular application, we can check the state of the tkinter CheckButtons by using the state() method. It prints the actual state of the tkinter checkbuttons."
},
{
"code": null,
"e": 1825,
"s": 1475,
"text": "#Import the required library\nfrom tkinter import*\nfrom tkinter import ttk\n#Create an instance of tkinter frame\nwin= Tk()\n#Set the geometry\nwin.geometry(\"750x250\")\n#Define geometry of the window\nwin.geometry(\"750x250\")\n#Create CheckButtons\nchk= ttk.Checkbutton(win, text=\"Python\")\nchk.pack()\nchk.config(state=NORMAL)\nprint(chk.state())\nwin.mainloop()"
},
{
"code": null,
"e": 1935,
"s": 1825,
"text": "Running the example code will display a window with a check button that is initially defined as normal state."
},
{
"code": null,
"e": 2041,
"s": 1935,
"text": "Now, remove the line \"win.mainloop()\" from the program to print the state of the checkbox on the console."
},
{
"code": null,
"e": 2056,
"s": 2041,
"text": "('alternate',)"
}
] |
C# - Indexers
|
An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]).
A one dimensional indexer has the following syntax −
element-type this[int index] {
// The get accessor.
get {
// return the value specified by index
}
// The set accessor.
set {
// set the value specified by index
}
}
Declaration of behavior of an indexer is to some extent similar to a property. similar to the properties, you use get and set accessors for defining an indexer. However, properties return or set a specific data member, whereas indexers returns or sets a particular value from the object instance. In other words, it breaks the instance data into smaller parts and indexes each part, gets or sets each part.
Defining a property involves providing a property name. Indexers are not defined with names, but with the this keyword, which refers to the object instance. The following example demonstrates the concept −
using System;
namespace IndexerApplication {
class IndexedNames {
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames() {
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index] {
get {
string tmp;
if( index >= 0 && index <= size-1 ) {
tmp = namelist[index];
} else {
tmp = "";
}
return ( tmp );
}
set {
if( index >= 0 && index <= size-1 ) {
namelist[index] = value;
}
}
}
static void Main(string[] args) {
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
for ( int i = 0; i < IndexedNames.size; i++ ) {
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. It is not necessary that the indexes have to be integers. C# allows indexes to be of other types, for example, a string.
The following example demonstrates overloaded indexers −
using System;
namespace IndexerApplication {
class IndexedNames {
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames() {
for (int i = 0; i < size; i++) {
namelist[i] = "N. A.";
}
}
public string this[int index] {
get {
string tmp;
if( index >= 0 && index <= size-1 ) {
tmp = namelist[index];
} else {
tmp = "";
}
return ( tmp );
}
set {
if( index >= 0 && index <= size-1 ) {
namelist[index] = value;
}
}
}
public int this[string name] {
get {
int index = 0;
while(index < size) {
if (namelist[index] == name) {
return index;
}
index++;
}
return index;
}
}
static void Main(string[] args) {
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
//using the first indexer with int parameter
for (int i = 0; i < IndexedNames.size; i++) {
Console.WriteLine(names[i]);
}
//using the second indexer with the string parameter
Console.WriteLine(names["Nuha"]);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
2
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2503,
"s": 2270,
"text": "An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ])."
},
{
"code": null,
"e": 2556,
"s": 2503,
"text": "A one dimensional indexer has the following syntax −"
},
{
"code": null,
"e": 2758,
"s": 2556,
"text": "element-type this[int index] {\n\n // The get accessor.\n get {\n // return the value specified by index\n }\n \n // The set accessor.\n set {\n // set the value specified by index\n }\n}\n"
},
{
"code": null,
"e": 3166,
"s": 2758,
"text": "Declaration of behavior of an indexer is to some extent similar to a property. similar to the properties, you use get and set accessors for defining an indexer. However, properties return or set a specific data member, whereas indexers returns or sets a particular value from the object instance. In other words, it breaks the instance data into smaller parts and indexes each part, gets or sets each part."
},
{
"code": null,
"e": 3372,
"s": 3166,
"text": "Defining a property involves providing a property name. Indexers are not defined with names, but with the this keyword, which refers to the object instance. The following example demonstrates the concept −"
},
{
"code": null,
"e": 4528,
"s": 3372,
"text": "using System;\n\nnamespace IndexerApplication {\n \n class IndexedNames {\n private string[] namelist = new string[size];\n static public int size = 10;\n \n public IndexedNames() {\n for (int i = 0; i < size; i++)\n namelist[i] = \"N. A.\";\n }\n public string this[int index] {\n get {\n string tmp;\n \n if( index >= 0 && index <= size-1 ) {\n tmp = namelist[index];\n } else {\n tmp = \"\";\n }\n \n return ( tmp );\n }\n set {\n if( index >= 0 && index <= size-1 ) {\n namelist[index] = value;\n }\n }\n }\n static void Main(string[] args) {\n IndexedNames names = new IndexedNames();\n names[0] = \"Zara\";\n names[1] = \"Riz\";\n names[2] = \"Nuha\";\n names[3] = \"Asif\";\n names[4] = \"Davinder\";\n names[5] = \"Sunil\";\n names[6] = \"Rubic\";\n \n for ( int i = 0; i < IndexedNames.size; i++ ) {\n Console.WriteLine(names[i]);\n }\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 4609,
"s": 4528,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4668,
"s": 4609,
"text": "Zara\nRiz\nNuha\nAsif\nDavinder\nSunil\nRubic\nN. A.\nN. A.\nN. A.\n"
},
{
"code": null,
"e": 4916,
"s": 4668,
"text": "Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. It is not necessary that the indexes have to be integers. C# allows indexes to be of other types, for example, a string."
},
{
"code": null,
"e": 4973,
"s": 4916,
"text": "The following example demonstrates overloaded indexers −"
},
{
"code": null,
"e": 6621,
"s": 4973,
"text": "using System;\n\nnamespace IndexerApplication {\n class IndexedNames {\n private string[] namelist = new string[size];\n static public int size = 10;\n \n public IndexedNames() {\n for (int i = 0; i < size; i++) {\n namelist[i] = \"N. A.\";\n }\n }\n public string this[int index] {\n get {\n string tmp;\n \n if( index >= 0 && index <= size-1 ) {\n tmp = namelist[index];\n } else {\n tmp = \"\";\n }\n \n return ( tmp );\n }\n set {\n if( index >= 0 && index <= size-1 ) {\n namelist[index] = value;\n }\n }\n }\n \n public int this[string name] {\n get {\n int index = 0;\n \n while(index < size) {\n if (namelist[index] == name) {\n return index;\n }\n index++;\n }\n return index;\n }\n }\n\n static void Main(string[] args) {\n IndexedNames names = new IndexedNames();\n names[0] = \"Zara\";\n names[1] = \"Riz\";\n names[2] = \"Nuha\";\n names[3] = \"Asif\";\n names[4] = \"Davinder\";\n names[5] = \"Sunil\";\n names[6] = \"Rubic\";\n \n //using the first indexer with int parameter\n for (int i = 0; i < IndexedNames.size; i++) {\n Console.WriteLine(names[i]);\n }\n \n //using the second indexer with the string parameter\n Console.WriteLine(names[\"Nuha\"]);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 6702,
"s": 6621,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6763,
"s": 6702,
"text": "Zara\nRiz\nNuha\nAsif\nDavinder\nSunil\nRubic\nN. A.\nN. A.\nN. A.\n2\n"
},
{
"code": null,
"e": 6800,
"s": 6763,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 6813,
"s": 6800,
"text": " Raja Biswas"
},
{
"code": null,
"e": 6847,
"s": 6813,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6865,
"s": 6847,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 6898,
"s": 6865,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6912,
"s": 6898,
"text": " Peter Jepson"
},
{
"code": null,
"e": 6949,
"s": 6912,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 6964,
"s": 6949,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 6999,
"s": 6964,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 7014,
"s": 6999,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 7049,
"s": 7014,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7061,
"s": 7049,
"text": " Eric Frick"
},
{
"code": null,
"e": 7068,
"s": 7061,
"text": " Print"
},
{
"code": null,
"e": 7079,
"s": 7068,
"text": " Add Notes"
}
] |
Real World Example on Web Scraping with Selenium and Beautiful Soup | by Timothy Tan | Towards Data Science
|
5.39 Billion.
That’s how many pages the World Wide Web has got.
In terms of data?
Over 1,200 petabytes worth.
That’s equivalent to 1,200,000 terabytes, and 1,200,000,000 gigabytes.
All I’m saying is that there is a hell lot of unstructured data out there on the web.
Just sitting there...
Waiting to be scraped and analyzed. 😉
In this post, I will be going through code snippets on how to scrape the web with Selenium and Beautiful Soup.
I will start off with an introduction to the technologies before proceeding to an actual real world example of it.
I will also be surfacing issues I came across while working on this scraping project so you are made aware of them how to mitigate them for your own work.
Let’s get started!
For the uninitiated, let’s begin by a brief introduction of the technologies we will be using.
Born in 2004, Selenium is an open-sourced automated testing framework that is used to validate web applications across different browsers and platforms.
These test scripts can be built using different programming languages such as Java, C#, PHP, Python, Ruby and Perl.
In this post, we will be using a Selenium Python package (Selenium Web Driver) to create the test scripts.
As a quick introduction to how it works, here’s a GIF on me working with Selenium off a Jupyter Notebook.
In the GIF, I started off importing the relevant packages and initializing a chrome browser. At the same time, I told the browser to get “http://www.google.com”.
Next, I triggered a command to search “Selenium python API” in the Google Search bar before exiting.
If you would like to try it out, go ahead and start up your local Jupyter Notebook.
The first thing you will need to do is to install selenium.
pip install selenium
You will also need to install chrome driver here.
Then run the code below step by step.
Notice on line 13, the class name is “gLFyf.gsfi”?
How did I know that the Google Search Bar uses this tag?
To find out the different tags of a HTML page, all you need to do is to right-click on the page and enter developer mode with “inspect”.
Next, click on the icon at top left hand corner. This will enable you to select elements on page.
To view the tags for the search bar, simply hover your mouse over the search bar.
Once you find the relevant class tag you are interested in, you can tell Selenium to grab it with the code
elem = browser.find_element_by_class_name("gLFyf.gsfi")
A note of caution here though.
From experiences in this particular scraping project, I noticed a bug in the “find_element_by_class_name” function.
If the class names got too long with too many spaces, this function will fail to work.
I have Googled for tons of solutions. Even if you put those periods between the tokens i.e. “gLFyf<period>gsfi”
It doesn’t always work...
Very unreliable in this aspect.
A better way to filter out the class tags in particular is to use Beautiful Soup.
So if Selenium caused me such pain...
Why Selenium?
The reason why I had to use Selenium for this project was due to a limitation in Beautiful Soup.
When Beautiful Soup parses a HTML page, it will not parse the sections of the page that needs to be loaded by java script.
Sometimes, there are web pages that require the user to scroll down before a new section of a web page is loaded — the loading is usually done by java script.
Thus, if your web page require you to scroll down to load the segments of the page, the Beautiful Soup parser will never parse the full HTML.
To mitigate this issue, you should use Selenium to automate the scrolling process before parsing the HTML page in it’s entirety.
That way, you have a flexibility to either use Selenium or Beautiful Soup to start your information extraction process.
I used both because each of them had their own merits and together, they are like a power couple. 😃
Created in 2004, Beautiful Soup is a Python library made for parsing HTML and XML files seamlessly.
What do I mean by that?
Well, let’s go through a modified version of their example from their documentation.
I modified the example to make things a little clearer.
The first thing to do is to install Beautiful Soup.
pip install beautifulsoup4
Here are the codes:
As you can see, Beautiful Soup is pretty easy and intuitive to use.
I suggest you try them out yourself if you have the time.
Alright then!
Now that introductions are out of the way, here comes the meat of the post!
Let’s get to it!
If you went through the introductory steps above, well done!
But here’s where web scraping can get tad bit more complex.
The whole scraping project was to scrape post titles from TDS writers.
I wanted to analyze what topics TDS writers were writing about and approximate reader interest through the number of claps received per post.
I will not be going through the results in this post but it will be in another post.
However, I will be covering in the codes used to accomplish the scraping task.
This took me about 2 days to get it working as I faced a lot of different bugs along the way.
Here we go!
I accomplished this in two steps.
Step 1 — Define the web pages that needed to be scraped and find the common tags used through the differing pages.
This step takes awhile because you will need to find all relevant tags and cross-reference them with other pages to determine if they are pointing to the same element you want to scrape.
I did this manually by opening up multiple tabs of different pages and entering the developer mode i.e. right-click “Inspect” or hit F12.
Then I hovered on the elements I wanted to extract and searched for a common tag that all of these elements use.
Let’s take my profile for example.
The information of interest to me were:
Publisher Name
Date Posted
Read Time
Title of Post
No. of Claps
What I was looking for were the “div” tags that hold the information I want extracted.
Here, I found the “div” tag I needed and also noticed it had “class” tags!
Perfect!
Notice how there are 7 identical “class” tags above?
That’s because each post in my profile page has the same tag name.
<div class = "gk gl gm gn go y c">...</div>
This is something you would want to look out for.
But the question is, do other user profiles follow the same tag?
Let’s cross-reference this finding with another profile.
It turns out, not quite.
<div class = "gm gn go gp gq y c">...</div>
But after taking a look at another profile...
There is a pattern.
<div class = "go gp gp gr gs y c">...</div>
The pattern to all the “div” tags that I need follows a regex pattern of:
re.compile(r'(..\s){5}y c')
In English, there will be a 2 characters followed by a space that occurs exactly 5 times. Next to this, the characters “y c” will appear.
Hence, this was the regex pattern I used for the scraping process.
I won’t be going through all the patterns that are needed but you get the idea.
Web scraping is kind of hackish and filled with hard-coded tags.
Anyway, I rinsed and repeated the above steps for everything that I needed to extract.
Let’s move on to the next step.
Step 2 — Define the logical flow in which the script will follow
Recall that the goal is to get all TDS post titles.
We know from step 1 what we want to extract and how to do it.
What we need now is to know how to dynamically extract post titles from all writer profile pages.
This means loading up each writers’ profile and initiate the scraping process.
Keyword “each”.
How do we go about it?
This a three-step process:
We first run a scraping job to extract out all TDS writer profile links.Then use each link to enter into their profile page to extract out all the post titles they had written before.As a sub-task of (2), for each post “div”, create a new entry for the base DataFrame and append the row to it.
We first run a scraping job to extract out all TDS writer profile links.
Then use each link to enter into their profile page to extract out all the post titles they had written before.
As a sub-task of (2), for each post “div”, create a new entry for the base DataFrame and append the row to it.
Here’s how the code looks like if you apply all 3 steps.
Let’s breakdown what you see in the code snippet above.
First, I called a definition “get_profile_urls(...)” that accepts a link to all TDS writers’ profile.
Once the definition scrapes the URL links for each writer, it returns a python list of them.
url_list =['https://medium.com/@kozyrkov','https://medium.com/@ssrosa','https://medium.com/@neha_mangal','https://medium.com/@parulnith', ...]
Each of these links are then looped through and used as inputs to another definition called “extract_information(...)”.
At gist, this definition initializes a Selenium browser for each URL and uses Selenium to scroll all the way down to the end of a profile before setting off two sub-tasks: “get_post(...)” and “get_writer_profile(...)”.
Here’s how the definition of extract_information(...) looks like:
Note lines 21 to 37:
# Path to webdriver browser = webdriver.Chrome(webdriver_path)# URL to scrape browser.get(pub_url) time.sleep(1)# Get body elem = browser.find_element_by_tag_name("body")# No. of times to scroll no_of_pagedowns = 100while no_of_pagedowns: elem.send_keys(Keys.PAGE_DOWN) time.sleep(0.5) no_of_pagedowns-=1
This is Selenium starting up a browser for each profile, defining the “body” of the page and scrolling down the page every 0.5 secs for 100 scrolls.
Yes, the 100 is hard-coded. I figured you would reach the end of each profile within 100 scrolls.
If not, just increase it to 150 scroll and that should do the trick.
Moving on, note how I’m keeping track of error counts here.
When it comes to web scraping, there will be a lot of unexpected things that could occur.
In this case, I faced issues with:
Posts having no claps. Thus I had to account for this.
Posts having no H1 title tags.
Posts H4 tags not being equal across all posts.
and more...
With all these little errors, I used “try and except” to log the error counts and allow the program to continuous run even if there were errors.
If the post did not conform to the data frame columns, that would be an error and I logged the count.
In total I scraped, 5524 post titles with 435 errors.
Yikes.
But it’s okay, I make do with 5524. 😏
Let’s now go through how “get_posts(...)” and “”get_writer_profiles(...)” look like.
This definition extracts all relevant information from each post and creates a new entry for the base data frame and appends the new entry to it.
In addition, any posts that fails the extraction process is ignored and an error counter is kept.
Here’s how the code looks like:
Note line 25 and 26:
ends_with_yc = re.compile(r'(..\s){5}y c') for row in page_content.find_all('div', class_=ends_with_yc):
Recall that I am using a regex match to find the location of each post.
The reason why I’m using Beautiful Soup and not Selenium to do the extraction is because of the matching of the class tag.
As mentioned earlier, there seems to be a bug in Selenium where the matching of class tags aren’t working as they should.
In this project, it was crucial to use the class tag to locate where the relevant “div” tags were.
The next thing I would like to call to attention is in line 63:
dp_rt_tag = row.find_all('span')[3].find('div')
Sometimes it is really helpful to find a parent tag to search it’s child tags.
In line 63, the parent tag was “span” and the child tag, “div”.
You see, web pages tend to be hierarchical in nature and it’s sometimes easier to extract things out knowing the parent tag.
Here’s an example of the hierarchy I’m referring to.
In the image above, the parent tag could be “section” that has a lot of children tags — “div”, “figure”, “h1”, “h2”etc.
Besides extracting out post titles, I also took the liberty of extracting the name of writers and whether they were top writers or not.
This is essentially what this definition does. Pretty straight forward.
I used Selenium for the extraction.
Note the different syntax.
Note that with Selenium, to find a tag, you would run:
match_tag = browser.find_element_by_tag_name("p")ORmatch_tag = browser.find_elements_by_tag_name("p")
Subtle difference between the words “element” vs “elements”.
In Beautiful Soup, the equivalent will be:
match_tag = browser.find("p")ORmatch_tag = browser.find_all("p")
To find a class in Selenium, you would write:
match_tag = browser.find_element_by_class_name("go.gp.gp.gr.gs.y.c")
In Beautiful Soup:
match_tag = browser.find('div', class_="go gp gp gr gs y c")
But finding “class ”tags in Selenium doesn’t always work.
What’s weird is that it works for some class tags but not others. 😅
It worked for the Google example in the introduction didn’t it?
Very strange indeed...
After running the codes you have seen, the final extracted results will have looked like this:
I filtered for TDS as the publisher.
For the writers’ profile:
If you have been following so far, notice how I’ve skipped over one definition? 😉
I did not mention anything about the “get_profile_url(...)” definition.
I skipped this definition so you can get to try it out yourself.
It’s very straight forward compared to the other definitions I shared.
Give it a shot yourself and see how Selenium or Beautiful Soup works!
If all else fails, my scripts and notebooks are in my GitHub page made available below.
You can check them out once you have tried the extraction process yourself.
GitHub link for this post:
github.com
Well, that’s it!
In this post, I’ve given you an introduction to how Selenium and Beautiful Soup works with simple exercises.
Then I gave you the codes to try web scraping on a more realistic set of data. i.e. TDS web page
Note that this scraper can work on any publication not just TDS and in some sense, can be the basis for other web scraping projects you got.
Hopefully this post has given you some insight to web scraping.
With that, I’ll see you in the next post!
Bye!
LinkedIn Profile: Timothy Tan
|
[
{
"code": null,
"e": 61,
"s": 47,
"text": "5.39 Billion."
},
{
"code": null,
"e": 111,
"s": 61,
"text": "That’s how many pages the World Wide Web has got."
},
{
"code": null,
"e": 129,
"s": 111,
"text": "In terms of data?"
},
{
"code": null,
"e": 157,
"s": 129,
"text": "Over 1,200 petabytes worth."
},
{
"code": null,
"e": 228,
"s": 157,
"text": "That’s equivalent to 1,200,000 terabytes, and 1,200,000,000 gigabytes."
},
{
"code": null,
"e": 314,
"s": 228,
"text": "All I’m saying is that there is a hell lot of unstructured data out there on the web."
},
{
"code": null,
"e": 336,
"s": 314,
"text": "Just sitting there..."
},
{
"code": null,
"e": 374,
"s": 336,
"text": "Waiting to be scraped and analyzed. 😉"
},
{
"code": null,
"e": 485,
"s": 374,
"text": "In this post, I will be going through code snippets on how to scrape the web with Selenium and Beautiful Soup."
},
{
"code": null,
"e": 600,
"s": 485,
"text": "I will start off with an introduction to the technologies before proceeding to an actual real world example of it."
},
{
"code": null,
"e": 755,
"s": 600,
"text": "I will also be surfacing issues I came across while working on this scraping project so you are made aware of them how to mitigate them for your own work."
},
{
"code": null,
"e": 774,
"s": 755,
"text": "Let’s get started!"
},
{
"code": null,
"e": 869,
"s": 774,
"text": "For the uninitiated, let’s begin by a brief introduction of the technologies we will be using."
},
{
"code": null,
"e": 1022,
"s": 869,
"text": "Born in 2004, Selenium is an open-sourced automated testing framework that is used to validate web applications across different browsers and platforms."
},
{
"code": null,
"e": 1138,
"s": 1022,
"text": "These test scripts can be built using different programming languages such as Java, C#, PHP, Python, Ruby and Perl."
},
{
"code": null,
"e": 1245,
"s": 1138,
"text": "In this post, we will be using a Selenium Python package (Selenium Web Driver) to create the test scripts."
},
{
"code": null,
"e": 1351,
"s": 1245,
"text": "As a quick introduction to how it works, here’s a GIF on me working with Selenium off a Jupyter Notebook."
},
{
"code": null,
"e": 1513,
"s": 1351,
"text": "In the GIF, I started off importing the relevant packages and initializing a chrome browser. At the same time, I told the browser to get “http://www.google.com”."
},
{
"code": null,
"e": 1614,
"s": 1513,
"text": "Next, I triggered a command to search “Selenium python API” in the Google Search bar before exiting."
},
{
"code": null,
"e": 1698,
"s": 1614,
"text": "If you would like to try it out, go ahead and start up your local Jupyter Notebook."
},
{
"code": null,
"e": 1758,
"s": 1698,
"text": "The first thing you will need to do is to install selenium."
},
{
"code": null,
"e": 1779,
"s": 1758,
"text": "pip install selenium"
},
{
"code": null,
"e": 1829,
"s": 1779,
"text": "You will also need to install chrome driver here."
},
{
"code": null,
"e": 1867,
"s": 1829,
"text": "Then run the code below step by step."
},
{
"code": null,
"e": 1918,
"s": 1867,
"text": "Notice on line 13, the class name is “gLFyf.gsfi”?"
},
{
"code": null,
"e": 1975,
"s": 1918,
"text": "How did I know that the Google Search Bar uses this tag?"
},
{
"code": null,
"e": 2112,
"s": 1975,
"text": "To find out the different tags of a HTML page, all you need to do is to right-click on the page and enter developer mode with “inspect”."
},
{
"code": null,
"e": 2210,
"s": 2112,
"text": "Next, click on the icon at top left hand corner. This will enable you to select elements on page."
},
{
"code": null,
"e": 2292,
"s": 2210,
"text": "To view the tags for the search bar, simply hover your mouse over the search bar."
},
{
"code": null,
"e": 2399,
"s": 2292,
"text": "Once you find the relevant class tag you are interested in, you can tell Selenium to grab it with the code"
},
{
"code": null,
"e": 2455,
"s": 2399,
"text": "elem = browser.find_element_by_class_name(\"gLFyf.gsfi\")"
},
{
"code": null,
"e": 2486,
"s": 2455,
"text": "A note of caution here though."
},
{
"code": null,
"e": 2602,
"s": 2486,
"text": "From experiences in this particular scraping project, I noticed a bug in the “find_element_by_class_name” function."
},
{
"code": null,
"e": 2689,
"s": 2602,
"text": "If the class names got too long with too many spaces, this function will fail to work."
},
{
"code": null,
"e": 2801,
"s": 2689,
"text": "I have Googled for tons of solutions. Even if you put those periods between the tokens i.e. “gLFyf<period>gsfi”"
},
{
"code": null,
"e": 2827,
"s": 2801,
"text": "It doesn’t always work..."
},
{
"code": null,
"e": 2859,
"s": 2827,
"text": "Very unreliable in this aspect."
},
{
"code": null,
"e": 2941,
"s": 2859,
"text": "A better way to filter out the class tags in particular is to use Beautiful Soup."
},
{
"code": null,
"e": 2979,
"s": 2941,
"text": "So if Selenium caused me such pain..."
},
{
"code": null,
"e": 2993,
"s": 2979,
"text": "Why Selenium?"
},
{
"code": null,
"e": 3090,
"s": 2993,
"text": "The reason why I had to use Selenium for this project was due to a limitation in Beautiful Soup."
},
{
"code": null,
"e": 3213,
"s": 3090,
"text": "When Beautiful Soup parses a HTML page, it will not parse the sections of the page that needs to be loaded by java script."
},
{
"code": null,
"e": 3372,
"s": 3213,
"text": "Sometimes, there are web pages that require the user to scroll down before a new section of a web page is loaded — the loading is usually done by java script."
},
{
"code": null,
"e": 3514,
"s": 3372,
"text": "Thus, if your web page require you to scroll down to load the segments of the page, the Beautiful Soup parser will never parse the full HTML."
},
{
"code": null,
"e": 3643,
"s": 3514,
"text": "To mitigate this issue, you should use Selenium to automate the scrolling process before parsing the HTML page in it’s entirety."
},
{
"code": null,
"e": 3763,
"s": 3643,
"text": "That way, you have a flexibility to either use Selenium or Beautiful Soup to start your information extraction process."
},
{
"code": null,
"e": 3863,
"s": 3763,
"text": "I used both because each of them had their own merits and together, they are like a power couple. 😃"
},
{
"code": null,
"e": 3963,
"s": 3863,
"text": "Created in 2004, Beautiful Soup is a Python library made for parsing HTML and XML files seamlessly."
},
{
"code": null,
"e": 3987,
"s": 3963,
"text": "What do I mean by that?"
},
{
"code": null,
"e": 4072,
"s": 3987,
"text": "Well, let’s go through a modified version of their example from their documentation."
},
{
"code": null,
"e": 4128,
"s": 4072,
"text": "I modified the example to make things a little clearer."
},
{
"code": null,
"e": 4180,
"s": 4128,
"text": "The first thing to do is to install Beautiful Soup."
},
{
"code": null,
"e": 4207,
"s": 4180,
"text": "pip install beautifulsoup4"
},
{
"code": null,
"e": 4227,
"s": 4207,
"text": "Here are the codes:"
},
{
"code": null,
"e": 4295,
"s": 4227,
"text": "As you can see, Beautiful Soup is pretty easy and intuitive to use."
},
{
"code": null,
"e": 4353,
"s": 4295,
"text": "I suggest you try them out yourself if you have the time."
},
{
"code": null,
"e": 4367,
"s": 4353,
"text": "Alright then!"
},
{
"code": null,
"e": 4443,
"s": 4367,
"text": "Now that introductions are out of the way, here comes the meat of the post!"
},
{
"code": null,
"e": 4460,
"s": 4443,
"text": "Let’s get to it!"
},
{
"code": null,
"e": 4521,
"s": 4460,
"text": "If you went through the introductory steps above, well done!"
},
{
"code": null,
"e": 4581,
"s": 4521,
"text": "But here’s where web scraping can get tad bit more complex."
},
{
"code": null,
"e": 4652,
"s": 4581,
"text": "The whole scraping project was to scrape post titles from TDS writers."
},
{
"code": null,
"e": 4794,
"s": 4652,
"text": "I wanted to analyze what topics TDS writers were writing about and approximate reader interest through the number of claps received per post."
},
{
"code": null,
"e": 4879,
"s": 4794,
"text": "I will not be going through the results in this post but it will be in another post."
},
{
"code": null,
"e": 4958,
"s": 4879,
"text": "However, I will be covering in the codes used to accomplish the scraping task."
},
{
"code": null,
"e": 5052,
"s": 4958,
"text": "This took me about 2 days to get it working as I faced a lot of different bugs along the way."
},
{
"code": null,
"e": 5064,
"s": 5052,
"text": "Here we go!"
},
{
"code": null,
"e": 5098,
"s": 5064,
"text": "I accomplished this in two steps."
},
{
"code": null,
"e": 5213,
"s": 5098,
"text": "Step 1 — Define the web pages that needed to be scraped and find the common tags used through the differing pages."
},
{
"code": null,
"e": 5400,
"s": 5213,
"text": "This step takes awhile because you will need to find all relevant tags and cross-reference them with other pages to determine if they are pointing to the same element you want to scrape."
},
{
"code": null,
"e": 5538,
"s": 5400,
"text": "I did this manually by opening up multiple tabs of different pages and entering the developer mode i.e. right-click “Inspect” or hit F12."
},
{
"code": null,
"e": 5651,
"s": 5538,
"text": "Then I hovered on the elements I wanted to extract and searched for a common tag that all of these elements use."
},
{
"code": null,
"e": 5686,
"s": 5651,
"text": "Let’s take my profile for example."
},
{
"code": null,
"e": 5726,
"s": 5686,
"text": "The information of interest to me were:"
},
{
"code": null,
"e": 5741,
"s": 5726,
"text": "Publisher Name"
},
{
"code": null,
"e": 5753,
"s": 5741,
"text": "Date Posted"
},
{
"code": null,
"e": 5763,
"s": 5753,
"text": "Read Time"
},
{
"code": null,
"e": 5777,
"s": 5763,
"text": "Title of Post"
},
{
"code": null,
"e": 5790,
"s": 5777,
"text": "No. of Claps"
},
{
"code": null,
"e": 5877,
"s": 5790,
"text": "What I was looking for were the “div” tags that hold the information I want extracted."
},
{
"code": null,
"e": 5952,
"s": 5877,
"text": "Here, I found the “div” tag I needed and also noticed it had “class” tags!"
},
{
"code": null,
"e": 5961,
"s": 5952,
"text": "Perfect!"
},
{
"code": null,
"e": 6014,
"s": 5961,
"text": "Notice how there are 7 identical “class” tags above?"
},
{
"code": null,
"e": 6081,
"s": 6014,
"text": "That’s because each post in my profile page has the same tag name."
},
{
"code": null,
"e": 6125,
"s": 6081,
"text": "<div class = \"gk gl gm gn go y c\">...</div>"
},
{
"code": null,
"e": 6175,
"s": 6125,
"text": "This is something you would want to look out for."
},
{
"code": null,
"e": 6240,
"s": 6175,
"text": "But the question is, do other user profiles follow the same tag?"
},
{
"code": null,
"e": 6297,
"s": 6240,
"text": "Let’s cross-reference this finding with another profile."
},
{
"code": null,
"e": 6322,
"s": 6297,
"text": "It turns out, not quite."
},
{
"code": null,
"e": 6366,
"s": 6322,
"text": "<div class = \"gm gn go gp gq y c\">...</div>"
},
{
"code": null,
"e": 6412,
"s": 6366,
"text": "But after taking a look at another profile..."
},
{
"code": null,
"e": 6432,
"s": 6412,
"text": "There is a pattern."
},
{
"code": null,
"e": 6476,
"s": 6432,
"text": "<div class = \"go gp gp gr gs y c\">...</div>"
},
{
"code": null,
"e": 6550,
"s": 6476,
"text": "The pattern to all the “div” tags that I need follows a regex pattern of:"
},
{
"code": null,
"e": 6578,
"s": 6550,
"text": "re.compile(r'(..\\s){5}y c')"
},
{
"code": null,
"e": 6716,
"s": 6578,
"text": "In English, there will be a 2 characters followed by a space that occurs exactly 5 times. Next to this, the characters “y c” will appear."
},
{
"code": null,
"e": 6783,
"s": 6716,
"text": "Hence, this was the regex pattern I used for the scraping process."
},
{
"code": null,
"e": 6863,
"s": 6783,
"text": "I won’t be going through all the patterns that are needed but you get the idea."
},
{
"code": null,
"e": 6928,
"s": 6863,
"text": "Web scraping is kind of hackish and filled with hard-coded tags."
},
{
"code": null,
"e": 7015,
"s": 6928,
"text": "Anyway, I rinsed and repeated the above steps for everything that I needed to extract."
},
{
"code": null,
"e": 7047,
"s": 7015,
"text": "Let’s move on to the next step."
},
{
"code": null,
"e": 7112,
"s": 7047,
"text": "Step 2 — Define the logical flow in which the script will follow"
},
{
"code": null,
"e": 7164,
"s": 7112,
"text": "Recall that the goal is to get all TDS post titles."
},
{
"code": null,
"e": 7226,
"s": 7164,
"text": "We know from step 1 what we want to extract and how to do it."
},
{
"code": null,
"e": 7324,
"s": 7226,
"text": "What we need now is to know how to dynamically extract post titles from all writer profile pages."
},
{
"code": null,
"e": 7403,
"s": 7324,
"text": "This means loading up each writers’ profile and initiate the scraping process."
},
{
"code": null,
"e": 7419,
"s": 7403,
"text": "Keyword “each”."
},
{
"code": null,
"e": 7442,
"s": 7419,
"text": "How do we go about it?"
},
{
"code": null,
"e": 7469,
"s": 7442,
"text": "This a three-step process:"
},
{
"code": null,
"e": 7763,
"s": 7469,
"text": "We first run a scraping job to extract out all TDS writer profile links.Then use each link to enter into their profile page to extract out all the post titles they had written before.As a sub-task of (2), for each post “div”, create a new entry for the base DataFrame and append the row to it."
},
{
"code": null,
"e": 7836,
"s": 7763,
"text": "We first run a scraping job to extract out all TDS writer profile links."
},
{
"code": null,
"e": 7948,
"s": 7836,
"text": "Then use each link to enter into their profile page to extract out all the post titles they had written before."
},
{
"code": null,
"e": 8059,
"s": 7948,
"text": "As a sub-task of (2), for each post “div”, create a new entry for the base DataFrame and append the row to it."
},
{
"code": null,
"e": 8116,
"s": 8059,
"text": "Here’s how the code looks like if you apply all 3 steps."
},
{
"code": null,
"e": 8172,
"s": 8116,
"text": "Let’s breakdown what you see in the code snippet above."
},
{
"code": null,
"e": 8274,
"s": 8172,
"text": "First, I called a definition “get_profile_urls(...)” that accepts a link to all TDS writers’ profile."
},
{
"code": null,
"e": 8367,
"s": 8274,
"text": "Once the definition scrapes the URL links for each writer, it returns a python list of them."
},
{
"code": null,
"e": 8510,
"s": 8367,
"text": "url_list =['https://medium.com/@kozyrkov','https://medium.com/@ssrosa','https://medium.com/@neha_mangal','https://medium.com/@parulnith', ...]"
},
{
"code": null,
"e": 8630,
"s": 8510,
"text": "Each of these links are then looped through and used as inputs to another definition called “extract_information(...)”."
},
{
"code": null,
"e": 8849,
"s": 8630,
"text": "At gist, this definition initializes a Selenium browser for each URL and uses Selenium to scroll all the way down to the end of a profile before setting off two sub-tasks: “get_post(...)” and “get_writer_profile(...)”."
},
{
"code": null,
"e": 8915,
"s": 8849,
"text": "Here’s how the definition of extract_information(...) looks like:"
},
{
"code": null,
"e": 8936,
"s": 8915,
"text": "Note lines 21 to 37:"
},
{
"code": null,
"e": 9277,
"s": 8936,
"text": "# Path to webdriver browser = webdriver.Chrome(webdriver_path)# URL to scrape browser.get(pub_url) time.sleep(1)# Get body elem = browser.find_element_by_tag_name(\"body\")# No. of times to scroll no_of_pagedowns = 100while no_of_pagedowns: elem.send_keys(Keys.PAGE_DOWN) time.sleep(0.5) no_of_pagedowns-=1"
},
{
"code": null,
"e": 9426,
"s": 9277,
"text": "This is Selenium starting up a browser for each profile, defining the “body” of the page and scrolling down the page every 0.5 secs for 100 scrolls."
},
{
"code": null,
"e": 9524,
"s": 9426,
"text": "Yes, the 100 is hard-coded. I figured you would reach the end of each profile within 100 scrolls."
},
{
"code": null,
"e": 9593,
"s": 9524,
"text": "If not, just increase it to 150 scroll and that should do the trick."
},
{
"code": null,
"e": 9653,
"s": 9593,
"text": "Moving on, note how I’m keeping track of error counts here."
},
{
"code": null,
"e": 9743,
"s": 9653,
"text": "When it comes to web scraping, there will be a lot of unexpected things that could occur."
},
{
"code": null,
"e": 9778,
"s": 9743,
"text": "In this case, I faced issues with:"
},
{
"code": null,
"e": 9833,
"s": 9778,
"text": "Posts having no claps. Thus I had to account for this."
},
{
"code": null,
"e": 9864,
"s": 9833,
"text": "Posts having no H1 title tags."
},
{
"code": null,
"e": 9912,
"s": 9864,
"text": "Posts H4 tags not being equal across all posts."
},
{
"code": null,
"e": 9924,
"s": 9912,
"text": "and more..."
},
{
"code": null,
"e": 10069,
"s": 9924,
"text": "With all these little errors, I used “try and except” to log the error counts and allow the program to continuous run even if there were errors."
},
{
"code": null,
"e": 10171,
"s": 10069,
"text": "If the post did not conform to the data frame columns, that would be an error and I logged the count."
},
{
"code": null,
"e": 10225,
"s": 10171,
"text": "In total I scraped, 5524 post titles with 435 errors."
},
{
"code": null,
"e": 10232,
"s": 10225,
"text": "Yikes."
},
{
"code": null,
"e": 10270,
"s": 10232,
"text": "But it’s okay, I make do with 5524. 😏"
},
{
"code": null,
"e": 10355,
"s": 10270,
"text": "Let’s now go through how “get_posts(...)” and “”get_writer_profiles(...)” look like."
},
{
"code": null,
"e": 10501,
"s": 10355,
"text": "This definition extracts all relevant information from each post and creates a new entry for the base data frame and appends the new entry to it."
},
{
"code": null,
"e": 10599,
"s": 10501,
"text": "In addition, any posts that fails the extraction process is ignored and an error counter is kept."
},
{
"code": null,
"e": 10631,
"s": 10599,
"text": "Here’s how the code looks like:"
},
{
"code": null,
"e": 10652,
"s": 10631,
"text": "Note line 25 and 26:"
},
{
"code": null,
"e": 10760,
"s": 10652,
"text": "ends_with_yc = re.compile(r'(..\\s){5}y c') for row in page_content.find_all('div', class_=ends_with_yc):"
},
{
"code": null,
"e": 10832,
"s": 10760,
"text": "Recall that I am using a regex match to find the location of each post."
},
{
"code": null,
"e": 10955,
"s": 10832,
"text": "The reason why I’m using Beautiful Soup and not Selenium to do the extraction is because of the matching of the class tag."
},
{
"code": null,
"e": 11077,
"s": 10955,
"text": "As mentioned earlier, there seems to be a bug in Selenium where the matching of class tags aren’t working as they should."
},
{
"code": null,
"e": 11176,
"s": 11077,
"text": "In this project, it was crucial to use the class tag to locate where the relevant “div” tags were."
},
{
"code": null,
"e": 11240,
"s": 11176,
"text": "The next thing I would like to call to attention is in line 63:"
},
{
"code": null,
"e": 11288,
"s": 11240,
"text": "dp_rt_tag = row.find_all('span')[3].find('div')"
},
{
"code": null,
"e": 11367,
"s": 11288,
"text": "Sometimes it is really helpful to find a parent tag to search it’s child tags."
},
{
"code": null,
"e": 11431,
"s": 11367,
"text": "In line 63, the parent tag was “span” and the child tag, “div”."
},
{
"code": null,
"e": 11556,
"s": 11431,
"text": "You see, web pages tend to be hierarchical in nature and it’s sometimes easier to extract things out knowing the parent tag."
},
{
"code": null,
"e": 11609,
"s": 11556,
"text": "Here’s an example of the hierarchy I’m referring to."
},
{
"code": null,
"e": 11729,
"s": 11609,
"text": "In the image above, the parent tag could be “section” that has a lot of children tags — “div”, “figure”, “h1”, “h2”etc."
},
{
"code": null,
"e": 11865,
"s": 11729,
"text": "Besides extracting out post titles, I also took the liberty of extracting the name of writers and whether they were top writers or not."
},
{
"code": null,
"e": 11937,
"s": 11865,
"text": "This is essentially what this definition does. Pretty straight forward."
},
{
"code": null,
"e": 11973,
"s": 11937,
"text": "I used Selenium for the extraction."
},
{
"code": null,
"e": 12000,
"s": 11973,
"text": "Note the different syntax."
},
{
"code": null,
"e": 12055,
"s": 12000,
"text": "Note that with Selenium, to find a tag, you would run:"
},
{
"code": null,
"e": 12157,
"s": 12055,
"text": "match_tag = browser.find_element_by_tag_name(\"p\")ORmatch_tag = browser.find_elements_by_tag_name(\"p\")"
},
{
"code": null,
"e": 12218,
"s": 12157,
"text": "Subtle difference between the words “element” vs “elements”."
},
{
"code": null,
"e": 12261,
"s": 12218,
"text": "In Beautiful Soup, the equivalent will be:"
},
{
"code": null,
"e": 12326,
"s": 12261,
"text": "match_tag = browser.find(\"p\")ORmatch_tag = browser.find_all(\"p\")"
},
{
"code": null,
"e": 12372,
"s": 12326,
"text": "To find a class in Selenium, you would write:"
},
{
"code": null,
"e": 12441,
"s": 12372,
"text": "match_tag = browser.find_element_by_class_name(\"go.gp.gp.gr.gs.y.c\")"
},
{
"code": null,
"e": 12460,
"s": 12441,
"text": "In Beautiful Soup:"
},
{
"code": null,
"e": 12521,
"s": 12460,
"text": "match_tag = browser.find('div', class_=\"go gp gp gr gs y c\")"
},
{
"code": null,
"e": 12579,
"s": 12521,
"text": "But finding “class ”tags in Selenium doesn’t always work."
},
{
"code": null,
"e": 12647,
"s": 12579,
"text": "What’s weird is that it works for some class tags but not others. 😅"
},
{
"code": null,
"e": 12711,
"s": 12647,
"text": "It worked for the Google example in the introduction didn’t it?"
},
{
"code": null,
"e": 12734,
"s": 12711,
"text": "Very strange indeed..."
},
{
"code": null,
"e": 12829,
"s": 12734,
"text": "After running the codes you have seen, the final extracted results will have looked like this:"
},
{
"code": null,
"e": 12866,
"s": 12829,
"text": "I filtered for TDS as the publisher."
},
{
"code": null,
"e": 12892,
"s": 12866,
"text": "For the writers’ profile:"
},
{
"code": null,
"e": 12974,
"s": 12892,
"text": "If you have been following so far, notice how I’ve skipped over one definition? 😉"
},
{
"code": null,
"e": 13046,
"s": 12974,
"text": "I did not mention anything about the “get_profile_url(...)” definition."
},
{
"code": null,
"e": 13111,
"s": 13046,
"text": "I skipped this definition so you can get to try it out yourself."
},
{
"code": null,
"e": 13182,
"s": 13111,
"text": "It’s very straight forward compared to the other definitions I shared."
},
{
"code": null,
"e": 13252,
"s": 13182,
"text": "Give it a shot yourself and see how Selenium or Beautiful Soup works!"
},
{
"code": null,
"e": 13340,
"s": 13252,
"text": "If all else fails, my scripts and notebooks are in my GitHub page made available below."
},
{
"code": null,
"e": 13416,
"s": 13340,
"text": "You can check them out once you have tried the extraction process yourself."
},
{
"code": null,
"e": 13443,
"s": 13416,
"text": "GitHub link for this post:"
},
{
"code": null,
"e": 13454,
"s": 13443,
"text": "github.com"
},
{
"code": null,
"e": 13471,
"s": 13454,
"text": "Well, that’s it!"
},
{
"code": null,
"e": 13580,
"s": 13471,
"text": "In this post, I’ve given you an introduction to how Selenium and Beautiful Soup works with simple exercises."
},
{
"code": null,
"e": 13677,
"s": 13580,
"text": "Then I gave you the codes to try web scraping on a more realistic set of data. i.e. TDS web page"
},
{
"code": null,
"e": 13818,
"s": 13677,
"text": "Note that this scraper can work on any publication not just TDS and in some sense, can be the basis for other web scraping projects you got."
},
{
"code": null,
"e": 13882,
"s": 13818,
"text": "Hopefully this post has given you some insight to web scraping."
},
{
"code": null,
"e": 13924,
"s": 13882,
"text": "With that, I’ll see you in the next post!"
},
{
"code": null,
"e": 13929,
"s": 13924,
"text": "Bye!"
}
] |
How to set Row Header View for JScrollPane in Java?
|
Set Row Header View using the setRowHeaderView() method. Let us first create a KScrollPane and set a list −
List<String> myList = new ArrayList<>(10);
for (int index = 0; index < 20; index++) {
myList.add("List Item " + index);
}
final JList<String> list = new JList<String>(myList.toArray(new String[myList.size()]));
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(list);
Now, set the row header view −
scrollPane.setRowHeaderView(new JLabel("All List Items "));
The following is an example to set row header view for JScrollPane in Java −
package my;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class SwingDemo {
public static void main(String[] args) {
JPanel panel = new JPanel(new BorderLayout());
List<String> myList = new ArrayListlt;>(10);
for (int index = 0; index lt; 20; index++) {
myList.add("List Item " + index);
}
final JListlt;String> list = new JListlt;String>(myList.toArray(new String[myList.size()]));
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(list);
scrollPane.setRowHeaderView(new JLabel("All List Items "));
list.setLayoutOrientation(JList.VERTICAL);
panel.add(scrollPane);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(500, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "Set Row Header View using the setRowHeaderView() method. Let us first create a KScrollPane and set a list −"
},
{
"code": null,
"e": 1462,
"s": 1170,
"text": "List<String> myList = new ArrayList<>(10);\nfor (int index = 0; index < 20; index++) {\n myList.add(\"List Item \" + index);\n}\nfinal JList<String> list = new JList<String>(myList.toArray(new String[myList.size()]));\nJScrollPane scrollPane = new JScrollPane();\nscrollPane.setViewportView(list);"
},
{
"code": null,
"e": 1493,
"s": 1462,
"text": "Now, set the row header view −"
},
{
"code": null,
"e": 1553,
"s": 1493,
"text": "scrollPane.setRowHeaderView(new JLabel(\"All List Items \"));"
},
{
"code": null,
"e": 1630,
"s": 1553,
"text": "The following is an example to set row header view for JScrollPane in Java −"
},
{
"code": null,
"e": 2704,
"s": 1630,
"text": "package my;\nimport java.awt.BorderLayout;\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JList;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\npublic class SwingDemo {\n public static void main(String[] args) {\n JPanel panel = new JPanel(new BorderLayout());\n List<String> myList = new ArrayListlt;>(10);\n for (int index = 0; index lt; 20; index++) {\n myList.add(\"List Item \" + index);\n }\n final JListlt;String> list = new JListlt;String>(myList.toArray(new String[myList.size()]));\n JScrollPane scrollPane = new JScrollPane();\n scrollPane.setViewportView(list);\n scrollPane.setRowHeaderView(new JLabel(\"All List Items \"));\n list.setLayoutOrientation(JList.VERTICAL);\n panel.add(scrollPane);\n JFrame frame = new JFrame(\"Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(panel);\n frame.setSize(500, 250);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n}"
}
] |
Node.js response.writeHead() Method - GeeksforGeeks
|
23 Sep, 2020
The response.writeHead() (Added in v1..0) property is an inbuilt property of the ‘http’ module which sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.
When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence. If this method is called and response.setHeader() has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If the progressive population of headers is desired with potential future retrieval and modification, use response.setHeader() instead.
In order to get a response and a proper result, we need to import ‘http’ module.
Import:
const http = require('http');
Syntax:
response.writeHead(statusCode[, statusMessage][, headers]);
Parameters: It accepts three parameters as mentioned above and described below:
statusCode <number>: It accepts the status codes that are of number type.
statusMessage <string>: It accepts any string that shows the status message.
headers <Object>: It accepts any function, array, or string.
Return Value <http.ServerResponse>: It returns a reference to the ServerResponse, so that calls can be chained.
The below example illustrates the use of response.writeHead() property in Node.js.
Example 1: Filename: index.js
// Node.js program to demonstrate the // response.writeHead() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer( function(request, response){ const body = 'hello world'; // Calling response.writeHead method response.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain' }); response.end(body);}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log("Server is running at port 3000...");});
Output:
Output: In-Console
Server is running at port 3000...
Now run http://localhost:3000/ in the browser.
Output: In-Browser
hello world
Example 2: Filename: index.js
// Node.js program to demonstrate the // response.writeHead() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer( function(request, response){ // Setting up Headers response.setHeader('Content-Type', 'text/html'); response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); response.setHeader('X-Foo', 'bar'); // Calling response.writeHead method response.writeHead(200, { 'Content-Type': 'text/plain' }); // Getting the set Headers const headers = response.getHeaders(); // Printing those headers console.log(headers); // Prints Output on the // browser in response response.end('ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log("Server is running at port 3000...");});
Run index.js file using the following command:
node index.js
Output:
Output: In-Console
Server is running at port 3000...
[Object: null prototype] {
‘content-type’: ‘text/plain’,
‘set-cookie’: [ ‘type=ninja’, ‘language=javascript’ ],
‘x-foo’: ‘bar’}
Now run http://localhost:3000/ in the browser.
Output: In-Browser
ok
Content-Length is given in bytes, not characters. Use Buffer.byteLength() to determine the length of the body in bytes. Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not. Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.
Reference: https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to read and write Excel file in Node.js ?
How to use an ES6 import in Node.js?
Express.js res.render() Function
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24498,
"s": 24470,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 24829,
"s": 24498,
"text": "The response.writeHead() (Added in v1..0) property is an inbuilt property of the ‘http’ module which sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument."
},
{
"code": null,
"e": 25407,
"s": 24829,
"text": "When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence. If this method is called and response.setHeader() has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If the progressive population of headers is desired with potential future retrieval and modification, use response.setHeader() instead."
},
{
"code": null,
"e": 25488,
"s": 25407,
"text": "In order to get a response and a proper result, we need to import ‘http’ module."
},
{
"code": null,
"e": 25496,
"s": 25488,
"text": "Import:"
},
{
"code": null,
"e": 25527,
"s": 25496,
"text": "const http = require('http');\n"
},
{
"code": null,
"e": 25535,
"s": 25527,
"text": "Syntax:"
},
{
"code": null,
"e": 25596,
"s": 25535,
"text": "response.writeHead(statusCode[, statusMessage][, headers]);\n"
},
{
"code": null,
"e": 25676,
"s": 25596,
"text": "Parameters: It accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25750,
"s": 25676,
"text": "statusCode <number>: It accepts the status codes that are of number type."
},
{
"code": null,
"e": 25827,
"s": 25750,
"text": "statusMessage <string>: It accepts any string that shows the status message."
},
{
"code": null,
"e": 25888,
"s": 25827,
"text": "headers <Object>: It accepts any function, array, or string."
},
{
"code": null,
"e": 26000,
"s": 25888,
"text": "Return Value <http.ServerResponse>: It returns a reference to the ServerResponse, so that calls can be chained."
},
{
"code": null,
"e": 26083,
"s": 26000,
"text": "The below example illustrates the use of response.writeHead() property in Node.js."
},
{
"code": null,
"e": 26113,
"s": 26083,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // response.writeHead() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer( function(request, response){ const body = 'hello world'; // Calling response.writeHead method response.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain' }); response.end(body);}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\");});",
"e": 26715,
"s": 26113,
"text": null
},
{
"code": null,
"e": 26723,
"s": 26715,
"text": "Output:"
},
{
"code": null,
"e": 26742,
"s": 26723,
"text": "Output: In-Console"
},
{
"code": null,
"e": 26776,
"s": 26742,
"text": "Server is running at port 3000..."
},
{
"code": null,
"e": 26823,
"s": 26776,
"text": "Now run http://localhost:3000/ in the browser."
},
{
"code": null,
"e": 26842,
"s": 26823,
"text": "Output: In-Browser"
},
{
"code": null,
"e": 26854,
"s": 26842,
"text": "hello world"
},
{
"code": null,
"e": 26884,
"s": 26854,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // response.writeHead() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer( function(request, response){ // Setting up Headers response.setHeader('Content-Type', 'text/html'); response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); response.setHeader('X-Foo', 'bar'); // Calling response.writeHead method response.writeHead(200, { 'Content-Type': 'text/plain' }); // Getting the set Headers const headers = response.getHeaders(); // Printing those headers console.log(headers); // Prints Output on the // browser in response response.end('ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\");});",
"e": 27770,
"s": 26884,
"text": null
},
{
"code": null,
"e": 27817,
"s": 27770,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 27832,
"s": 27817,
"text": "node index.js\n"
},
{
"code": null,
"e": 27840,
"s": 27832,
"text": "Output:"
},
{
"code": null,
"e": 27859,
"s": 27840,
"text": "Output: In-Console"
},
{
"code": null,
"e": 27893,
"s": 27859,
"text": "Server is running at port 3000..."
},
{
"code": null,
"e": 27920,
"s": 27893,
"text": "[Object: null prototype] {"
},
{
"code": null,
"e": 27951,
"s": 27920,
"text": " ‘content-type’: ‘text/plain’,"
},
{
"code": null,
"e": 28007,
"s": 27951,
"text": " ‘set-cookie’: [ ‘type=ninja’, ‘language=javascript’ ],"
},
{
"code": null,
"e": 28024,
"s": 28007,
"text": " ‘x-foo’: ‘bar’}"
},
{
"code": null,
"e": 28071,
"s": 28024,
"text": "Now run http://localhost:3000/ in the browser."
},
{
"code": null,
"e": 28090,
"s": 28071,
"text": "Output: In-Browser"
},
{
"code": null,
"e": 28093,
"s": 28090,
"text": "ok"
},
{
"code": null,
"e": 28452,
"s": 28093,
"text": "Content-Length is given in bytes, not characters. Use Buffer.byteLength() to determine the length of the body in bytes. Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not. Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown."
},
{
"code": null,
"e": 28553,
"s": 28452,
"text": "Reference: https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers"
},
{
"code": null,
"e": 28569,
"s": 28553,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 28577,
"s": 28569,
"text": "Node.js"
},
{
"code": null,
"e": 28594,
"s": 28577,
"text": "Web Technologies"
},
{
"code": null,
"e": 28692,
"s": 28594,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28749,
"s": 28692,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 28803,
"s": 28749,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 28849,
"s": 28803,
"text": "How to read and write Excel file in Node.js ?"
},
{
"code": null,
"e": 28886,
"s": 28849,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 28919,
"s": 28886,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 28961,
"s": 28919,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29004,
"s": 28961,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29054,
"s": 29004,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29116,
"s": 29054,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
An array of streams in C#
|
Set the string array for the values −
string[] names = new string[] {"Jack", "Tom"};
Now using foreach array, write the content in the file −
using (StreamWriter sw = new StreamWriter("names.txt")) {
foreach (string s in names) {
sw.WriteLine(s);
}
}
The following is an example showing an array of streams to write text to a file −
using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
string[] names = new string[] {"Jack", "Tom"};
using (StreamWriter sw = new StreamWriter("names.txt")) {
foreach (string s in names) {
sw.WriteLine(s);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("names.txt")) {
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}
|
[
{
"code": null,
"e": 1100,
"s": 1062,
"text": "Set the string array for the values −"
},
{
"code": null,
"e": 1147,
"s": 1100,
"text": "string[] names = new string[] {\"Jack\", \"Tom\"};"
},
{
"code": null,
"e": 1204,
"s": 1147,
"text": "Now using foreach array, write the content in the file −"
},
{
"code": null,
"e": 1326,
"s": 1204,
"text": "using (StreamWriter sw = new StreamWriter(\"names.txt\")) {\n\n foreach (string s in names) {\n sw.WriteLine(s);\n }\n}"
},
{
"code": null,
"e": 1408,
"s": 1326,
"text": "The following is an example showing an array of streams to write text to a file −"
},
{
"code": null,
"e": 2058,
"s": 1408,
"text": "using System;\nusing System.IO;\n\nnamespace FileApplication {\n class Program {\n static void Main(string[] args) {\n string[] names = new string[] {\"Jack\", \"Tom\"};\n\n using (StreamWriter sw = new StreamWriter(\"names.txt\")) {\n\n foreach (string s in names) {\n sw.WriteLine(s);\n }\n }\n\n // Read and show each line from the file.\n string line = \"\";\n using (StreamReader sr = new StreamReader(\"names.txt\")) {\n while ((line = sr.ReadLine()) != null) {\n Console.WriteLine(line);\n }\n }\n Console.ReadKey();\n }\n }\n}"
}
] |
How to assign int value to char variable in Java
|
To assign int value to a char variable in Java would consider the ASCII value and display the associated character/ digit.
Here, we have a char.
char val;
Now assign int value to it.
val = 77;
Now, when you will print the value of “val”, it would display the character associate with the value (ASCII) 77.
The following is the complete example.
Live Demo
public class Demo {
public static void main(String []args) {
char val;
val = 77;
System.out.print("Value: ");
System.out.println(val);
}
}
Value: M
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "To assign int value to a char variable in Java would consider the ASCII value and display the associated character/ digit."
},
{
"code": null,
"e": 1207,
"s": 1185,
"text": "Here, we have a char."
},
{
"code": null,
"e": 1217,
"s": 1207,
"text": "char val;"
},
{
"code": null,
"e": 1245,
"s": 1217,
"text": "Now assign int value to it."
},
{
"code": null,
"e": 1255,
"s": 1245,
"text": "val = 77;"
},
{
"code": null,
"e": 1368,
"s": 1255,
"text": "Now, when you will print the value of “val”, it would display the character associate with the value (ASCII) 77."
},
{
"code": null,
"e": 1407,
"s": 1368,
"text": "The following is the complete example."
},
{
"code": null,
"e": 1418,
"s": 1407,
"text": " Live Demo"
},
{
"code": null,
"e": 1587,
"s": 1418,
"text": "public class Demo {\n public static void main(String []args) {\n char val;\n val = 77;\n System.out.print(\"Value: \");\n System.out.println(val);\n }\n}"
},
{
"code": null,
"e": 1596,
"s": 1587,
"text": "Value: M"
}
] |
Center links in a Navigation Bar with CSS
|
To center links in a navigation bar, you need to add ‘text-align: center’ to <li>
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
}
li a {
display: block;
background-color: #F0E7E7;
}
.active {
background-color: #4CAF50;
color: white;
}
li {
text-align: center;
border-bottom: 1px solid #555;
}
</style>
</head>
<body>
<ul>
<li><a href = "#home">Home</a></li>
<li><a href = "#company" class = "active">Company</a></li>
<li><a href = "#product">Product</a></li>
<li><a href = "#services">Services</a></li>
<li><a href = "#contact">Contact</a></li>
</ul>
</body>
</html>
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To center links in a navigation bar, you need to add ‘text-align: center’ to <li>"
},
{
"code": null,
"e": 1154,
"s": 1144,
"text": "Live Demo"
},
{
"code": null,
"e": 1969,
"s": 1154,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n ul {\n list-style-type: none;\n margin: 0;\n padding: 0;\n width: 200px;\n }\n li a {\n display: block;\n background-color: #F0E7E7;\n }\n .active {\n background-color: #4CAF50;\n color: white;\n }\n li {\n text-align: center;\n border-bottom: 1px solid #555;\n }\n </style>\n </head>\n <body>\n <ul>\n <li><a href = \"#home\">Home</a></li>\n <li><a href = \"#company\" class = \"active\">Company</a></li>\n <li><a href = \"#product\">Product</a></li>\n <li><a href = \"#services\">Services</a></li>\n <li><a href = \"#contact\">Contact</a></li>\n </ul>\n </body>\n</html>"
}
] |
How to show a Soft Keyboard based on Android EditText focused using Kotlin?
|
This example demonstrates how to show a Soft Keyboard based on Android EditText focused using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f6f4"
android:padding="10dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text2"
android:layout_centerInParent="true"
android:layout_marginTop="50dp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var editText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
editText = findViewById(R.id.editText)
showSoftKeyboard(editText)
}
private fun showSoftKeyboard(view: View) {
if (view.requestFocus()) {
val inputMethodManager: InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "This example demonstrates how to show a Soft Keyboard based on Android EditText focused using Kotlin."
},
{
"code": null,
"e": 1293,
"s": 1164,
"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": 1358,
"s": 1293,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2395,
"s": 1358,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/rl\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:background=\"#f2f6f4\"\n android:padding=\"10dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/text2\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"50dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2450,
"s": 2395,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3289,
"s": 2450,
"text": "import android.content.Context\nimport android.os.Bundle\nimport android.view.View\nimport android.view.inputmethod.InputMethodManager\nimport android.widget.EditText\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var editText: EditText\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n editText = findViewById(R.id.editText)\n showSoftKeyboard(editText)\n }\n private fun showSoftKeyboard(view: View) {\n if (view.requestFocus()) {\n val inputMethodManager: InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager\n inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)\n }\n }\n}"
},
{
"code": null,
"e": 3344,
"s": 3289,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4018,
"s": 3344,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4367,
"s": 4018,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.