title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
dump command in Linux with examples - GeeksforGeeks
|
30 Sep, 2019
dump command in Linux is used for backup the filesystem to some storage device. It backs up the complete file system and not the individual files. In other words, it backups the required files to tape, disk or any other storage device for safe storage. The dump command in Linux works only with ext2/ext3 filesystem and not with others like FAT and ReiserFS. One special feature of dump is that it allows incremental backups. Incremental backups mean that the user can set up a backup plan according to which the file systems will be backed up weekly or only those files will be backed up which have been changed or added recently.
Syntax:
dump [-level#] [-a autosize] [-A file] [-B records] [-b blocksize][-d density] [-D file] [-e inode numbers] [-E file] [-f file][-F script] [-h level] [-I nr errors] [-jcompression level] [-L label][-Q file] [-s feet] [-T date] [-y] [-zcompression level] files-to-dumpdump [-W | -w]
dump command without any options: It prints the general syntax of the command along with the various options that can be used with the dump command. It also prints the version number of the dump command being used.
Options:
-level # : The dump level which is an integer ranging from 0-9. If the user has asked to perform a full backup or a backup of only those new files added after the last dump of a lower level.
– f file : This specifies the file where the backup will be written to. The file can be a tape drive, a floppy disk, ordinary file or standard output.
-u : This records and updates the backup in /etc/dumpdates file.
sudo dump 0uf /dev/qft0 /dev/sda6
sudo dump 0uf /dev/qft0 /dev/sda6
-B records : It displays the number of dump records per volumes. In other words, it shows the amount of data that can fit in the tape. This is not always required as DUMP can detect the end of media or storage. This takes a numerical value and is used in combination with -b (mentioned below).
-b blocksize : The block size specifies the number of kilobytes per dump record. The default value of block size is 10. Notice here how in the 4th line of DUMP the block size is 20 instead of 10.
sudo dump 0uBbf /dev/qft0 /dev/sda6
sudo dump 0uBbf /dev/qft0 /dev/sda6
-W : Lists the file systems that need to be backed up.
dump -W
dump -W
-a : ‘a’ stands for ‘auto-size’. This is useful because it helps us bypass all tape length calculations and works best when we have to append to an existing disk.
sudo dump 0uaf /dev/qft0 /dev/sda9
sudo dump 0uaf /dev/qft0 /dev/sda9
-z compression level : Compresses every block to be written on to the tape using the zlib library. The default compression level is 2.
sudo dump 0ufz /dev/qft0 /dev/sda6
sudo dump 0ufz /dev/qft0 /dev/sda6
S : Estimates the size even before doing it. The output is the estimated number of bytes the dump will take. It is helpful in case of incremental dumps in order to determine how many volumes of media will be used.
sudo dump S /dev/sda6
sudo dump S /dev/sda6
-I nr errors : The dump by default ignores first 32 read errors. This value can be manually changed to any value according to the user choice.
sudo dump 0ufI20 /dev/qft0 /dev/sda9
sudo dump 0ufI20 /dev/qft0 /dev/sda9
Some other options(which are less frequently used):
– A archive_file : Archives a dump table-of-contents into the specified archive_file.
-d density : This sets the tape density . It takes a numerical argument and its default value is 1600 bits per inch.
-n : When there is some change to the tape or there are some other changes, the dump sends a message to the user. This option takes no argument.
-s feet : This specifies the length of dump tape in feet. This takes a numerical argument.
-t date : This specifies a date and time entry according to which the incremental backups take place. Any modification or addition after the specified time will be backed up.
shubham_singh
linux-command
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
Tail command in Linux with examples
Mutex lock for Linux Thread Synchronization
|
[
{
"code": null,
"e": 23657,
"s": 23629,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 24289,
"s": 23657,
"text": "dump command in Linux is used for backup the filesystem to some storage device. It backs up the complete file system and not the individual files. In other words, it backups the required files to tape, disk or any other storage device for safe storage. The dump command in Linux works only with ext2/ext3 filesystem and not with others like FAT and ReiserFS. One special feature of dump is that it allows incremental backups. Incremental backups mean that the user can set up a backup plan according to which the file systems will be backed up weekly or only those files will be backed up which have been changed or added recently."
},
{
"code": null,
"e": 24297,
"s": 24289,
"text": "Syntax:"
},
{
"code": null,
"e": 24579,
"s": 24297,
"text": "dump [-level#] [-a autosize] [-A file] [-B records] [-b blocksize][-d density] [-D file] [-e inode numbers] [-E file] [-f file][-F script] [-h level] [-I nr errors] [-jcompression level] [-L label][-Q file] [-s feet] [-T date] [-y] [-zcompression level] files-to-dumpdump [-W | -w]"
},
{
"code": null,
"e": 24794,
"s": 24579,
"text": "dump command without any options: It prints the general syntax of the command along with the various options that can be used with the dump command. It also prints the version number of the dump command being used."
},
{
"code": null,
"e": 24803,
"s": 24794,
"text": "Options:"
},
{
"code": null,
"e": 24994,
"s": 24803,
"text": "-level # : The dump level which is an integer ranging from 0-9. If the user has asked to perform a full backup or a backup of only those new files added after the last dump of a lower level."
},
{
"code": null,
"e": 25145,
"s": 24994,
"text": "– f file : This specifies the file where the backup will be written to. The file can be a tape drive, a floppy disk, ordinary file or standard output."
},
{
"code": null,
"e": 25247,
"s": 25145,
"text": "-u : This records and updates the backup in /etc/dumpdates file. \nsudo dump 0uf /dev/qft0 /dev/sda6\n"
},
{
"code": null,
"e": 25285,
"s": 25247,
"text": " \nsudo dump 0uf /dev/qft0 /dev/sda6\n"
},
{
"code": null,
"e": 25579,
"s": 25285,
"text": "-B records : It displays the number of dump records per volumes. In other words, it shows the amount of data that can fit in the tape. This is not always required as DUMP can detect the end of media or storage. This takes a numerical value and is used in combination with -b (mentioned below)."
},
{
"code": null,
"e": 25814,
"s": 25579,
"text": "-b blocksize : The block size specifies the number of kilobytes per dump record. The default value of block size is 10. Notice here how in the 4th line of DUMP the block size is 20 instead of 10. \nsudo dump 0uBbf /dev/qft0 /dev/sda6\n"
},
{
"code": null,
"e": 25854,
"s": 25814,
"text": " \nsudo dump 0uBbf /dev/qft0 /dev/sda6\n"
},
{
"code": null,
"e": 25919,
"s": 25854,
"text": "-W : Lists the file systems that need to be backed up. \ndump -W\n"
},
{
"code": null,
"e": 25930,
"s": 25919,
"text": " \ndump -W\n"
},
{
"code": null,
"e": 26131,
"s": 25930,
"text": "-a : ‘a’ stands for ‘auto-size’. This is useful because it helps us bypass all tape length calculations and works best when we have to append to an existing disk. \nsudo dump 0uaf /dev/qft0 /dev/sda9\n"
},
{
"code": null,
"e": 26170,
"s": 26131,
"text": " \nsudo dump 0uaf /dev/qft0 /dev/sda9\n"
},
{
"code": null,
"e": 26343,
"s": 26170,
"text": "-z compression level : Compresses every block to be written on to the tape using the zlib library. The default compression level is 2. \nsudo dump 0ufz /dev/qft0 /dev/sda6\n"
},
{
"code": null,
"e": 26382,
"s": 26343,
"text": " \nsudo dump 0ufz /dev/qft0 /dev/sda6\n"
},
{
"code": null,
"e": 26620,
"s": 26382,
"text": "S : Estimates the size even before doing it. The output is the estimated number of bytes the dump will take. It is helpful in case of incremental dumps in order to determine how many volumes of media will be used. \nsudo dump S /dev/sda6\n"
},
{
"code": null,
"e": 26645,
"s": 26620,
"text": " \nsudo dump S /dev/sda6\n"
},
{
"code": null,
"e": 26828,
"s": 26645,
"text": "-I nr errors : The dump by default ignores first 32 read errors. This value can be manually changed to any value according to the user choice. \nsudo dump 0ufI20 /dev/qft0 /dev/sda9\n"
},
{
"code": null,
"e": 26869,
"s": 26828,
"text": " \nsudo dump 0ufI20 /dev/qft0 /dev/sda9\n"
},
{
"code": null,
"e": 26921,
"s": 26869,
"text": "Some other options(which are less frequently used):"
},
{
"code": null,
"e": 27007,
"s": 26921,
"text": "– A archive_file : Archives a dump table-of-contents into the specified archive_file."
},
{
"code": null,
"e": 27124,
"s": 27007,
"text": "-d density : This sets the tape density . It takes a numerical argument and its default value is 1600 bits per inch."
},
{
"code": null,
"e": 27269,
"s": 27124,
"text": "-n : When there is some change to the tape or there are some other changes, the dump sends a message to the user. This option takes no argument."
},
{
"code": null,
"e": 27360,
"s": 27269,
"text": "-s feet : This specifies the length of dump tape in feet. This takes a numerical argument."
},
{
"code": null,
"e": 27535,
"s": 27360,
"text": "-t date : This specifies a date and time entry according to which the incremental backups take place. Any modification or addition after the specified time will be backed up."
},
{
"code": null,
"e": 27549,
"s": 27535,
"text": "shubham_singh"
},
{
"code": null,
"e": 27563,
"s": 27549,
"text": "linux-command"
},
{
"code": null,
"e": 27583,
"s": 27563,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 27590,
"s": 27583,
"text": "Picked"
},
{
"code": null,
"e": 27601,
"s": 27590,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27699,
"s": 27601,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27708,
"s": 27699,
"text": "Comments"
},
{
"code": null,
"e": 27721,
"s": 27708,
"text": "Old Comments"
},
{
"code": null,
"e": 27759,
"s": 27721,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27795,
"s": 27759,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27833,
"s": 27795,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27871,
"s": 27833,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27906,
"s": 27871,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 27943,
"s": 27906,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 27979,
"s": 27943,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 27998,
"s": 27979,
"text": "Compiling with g++"
},
{
"code": null,
"e": 28034,
"s": 27998,
"text": "Tail command in Linux with examples"
}
] |
Split a string in equal parts (grouper in Python) - GeeksforGeeks
|
16 Jun, 2020
Grouper recipe is an extended toolset made using an existing itertool as building blocks. It collects data into fixed-length chunks or blocks.
Existing Itertools Used:izip_longest(*iterables[, fillvalue]) : Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.
Performance:
The extended tools offer the same high performance as the underlying toolset.
The superior memory performance is kept by processing elements one at a time rather than bringing the whole iterable into memory all at once.
Code volume is kept small by linking the tools together in a functional style which helps eliminate temporary variables.
High speed is retained by preferring “vectorized” building blocks over the use of for-loops and generators which incur interpreter overhead.
Examples:
Input : str = ABCDEFG, l = 3
Output : ABC DEF Gxx
Explanation:
Grouping characters of string in set of 3: ABC DEF Gxx.
'x' is added to the set which doesn't have 3 elements in it.
Input : str = GEEKSFORGEEKS, l = 5
Output : GEEKS FORGE EKSxx
Below is the Python3 code :
# Python3 code for the grouper recipe # import the existing itertool izip_longestfrom itertools import izip_longest # function for the grouper recipedef grouper(iterable, n, fillvalue ='x'): # create 'n'-blocks for collection args = [iter(iterable)] * n # collect data into fixed length blocks of # length 'n' using izip_longest and store # result as a list ans = list(izip_longest(fillvalue = fillvalue, *args)) # (optional) loop to convert ans to string t = len(ans) for i in range(t): ans[i] = "".join(ans[i]) # return ans as string return " ".join(ans) # Driver codes = "ABCDEFG"k = 3 result = grouper(s, k)print(result)
Output:
ABC DEF Gxx
adisakshya
Akanksha_Rai
python-string
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n16 Jun, 2020"
},
{
"code": null,
"e": 24355,
"s": 24212,
"text": "Grouper recipe is an extended toolset made using an existing itertool as building blocks. It collects data into fixed-length chunks or blocks."
},
{
"code": null,
"e": 24634,
"s": 24355,
"text": "Existing Itertools Used:izip_longest(*iterables[, fillvalue]) : Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted."
},
{
"code": null,
"e": 24647,
"s": 24634,
"text": "Performance:"
},
{
"code": null,
"e": 24725,
"s": 24647,
"text": "The extended tools offer the same high performance as the underlying toolset."
},
{
"code": null,
"e": 24867,
"s": 24725,
"text": "The superior memory performance is kept by processing elements one at a time rather than bringing the whole iterable into memory all at once."
},
{
"code": null,
"e": 24988,
"s": 24867,
"text": "Code volume is kept small by linking the tools together in a functional style which helps eliminate temporary variables."
},
{
"code": null,
"e": 25129,
"s": 24988,
"text": "High speed is retained by preferring “vectorized” building blocks over the use of for-loops and generators which incur interpreter overhead."
},
{
"code": null,
"e": 25139,
"s": 25129,
"text": "Examples:"
},
{
"code": null,
"e": 25384,
"s": 25139,
"text": "Input : str = ABCDEFG, l = 3\nOutput : ABC DEF Gxx\nExplanation: \nGrouping characters of string in set of 3: ABC DEF Gxx.\n'x' is added to the set which doesn't have 3 elements in it. \n\nInput : str = GEEKSFORGEEKS, l = 5\nOutput : GEEKS FORGE EKSxx"
},
{
"code": null,
"e": 25413,
"s": 25384,
"text": " Below is the Python3 code :"
},
{
"code": "# Python3 code for the grouper recipe # import the existing itertool izip_longestfrom itertools import izip_longest # function for the grouper recipedef grouper(iterable, n, fillvalue ='x'): # create 'n'-blocks for collection args = [iter(iterable)] * n # collect data into fixed length blocks of # length 'n' using izip_longest and store # result as a list ans = list(izip_longest(fillvalue = fillvalue, *args)) # (optional) loop to convert ans to string t = len(ans) for i in range(t): ans[i] = \"\".join(ans[i]) # return ans as string return \" \".join(ans) # Driver codes = \"ABCDEFG\"k = 3 result = grouper(s, k)print(result) ",
"e": 26120,
"s": 25413,
"text": null
},
{
"code": null,
"e": 26128,
"s": 26120,
"text": "Output:"
},
{
"code": null,
"e": 26140,
"s": 26128,
"text": "ABC DEF Gxx"
},
{
"code": null,
"e": 26151,
"s": 26140,
"text": "adisakshya"
},
{
"code": null,
"e": 26164,
"s": 26151,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26178,
"s": 26164,
"text": "python-string"
},
{
"code": null,
"e": 26202,
"s": 26178,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 26209,
"s": 26202,
"text": "Python"
},
{
"code": null,
"e": 26228,
"s": 26209,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26326,
"s": 26228,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26335,
"s": 26326,
"text": "Comments"
},
{
"code": null,
"e": 26348,
"s": 26335,
"text": "Old Comments"
},
{
"code": null,
"e": 26380,
"s": 26348,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26436,
"s": 26380,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26457,
"s": 26436,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26496,
"s": 26457,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26538,
"s": 26496,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26565,
"s": 26538,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26596,
"s": 26565,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26638,
"s": 26596,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26674,
"s": 26638,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Working with Geospatial Data in Python — PART 1 | by Ben Bogart | Towards Data Science
|
Let's be honest; geospatial data is scary. I don’t think there is any good reason for this other than that information on how to work with geospatial data in Python is not as easily accessible as information on working with other kinds of data.
This is the first article in a series focused on various must-know aspects of working with geospatial data in Python. Over the next several weeks, we will look at the main topics in working with geospatial data, including file formats, data types, coordinate systems, and tools to work with the data. I will try to keep these posts bite-sized. I hope that we will develop a comfort with the topic throughout the series, and our fear will fade away.
The first 2/3 of this post introduces concepts. In the last 1/3, we will get our hands dirty by pulling in two LiDAR rasters from opentopography.org and calculating a Canopy Height Model from a Digital Surface Model and a Digital Terrain Model.
I’ve organized the article is organized as follows:
Data TypesMetadataHands-on with raster data.
Data Types
Metadata
Hands-on with raster data.
There are two primary data types used in geospatial data: raster data and vector data. This is probably not surprising. If you have done any work on anything visual on a computer recently, you have probably interacted with both. Below we’ll take a brief look at each kind of data.
Raster Data is data in a grid. This is very similar to the data in a photo. In the case of satellite images, this data is like a photo. The difference between this geospatial raster data and photographic raster data is that geospatial data has a way of relating that data to specific locations on earth. It can also contain either float or integer data, unlike an image that only contains integer data.
Raster data can also be categorical. For example, you might classify ground cover as low, medium, or high. In such a case, we map integer data to a category.
Vector geospatial data is also very similar to its design counterpart that you might have worked with in Adobe Illustrator. Again, the difference is that geospatial vector data is mapped to specific places on earth.
Vector data comes in three types.
Each type of vector data can represent different kinds of information.
A point can represent the location of something like a tree or a building.
A line can represent a road or a river.
A polygon can represent geographical units like the boundaries of a country, state, or other areas like national parks.
Geospatial rasters use metadata to communicate many vital aspects of the data to us. Below are a couple of the essential elements found in a raster file’s metadata.
I mentioned above that the essential characteristic of geospatial data is that it connects the data to a specific point on earth. The mechanism which makes this connection is the Coordinate Reference System or CRS.
There is one significant complication. The earth is a globe, and our data representation is two-dimensional. Like any paper map, our data is projected into two dimensions. Different CRS handle this projection differently. For example, some CRS are focused on only a specific area of the earth. Others are more general for projecting large portions of the earth's surface. There are many, many different CRS. Some are more common than others, but for our purposes, we need to know that two rasters with different CRS won’t line up when we visualize or make calculations from them. We will need to have a way to convert both rasters to the same CRS (more on this in a future article).
Another critical piece of metadata is the NoData value. The grid format of a raster requires there to be data in every square. The NoData value tells us the number used by the raster to indicate that it has no value for that part of the grid. For integer and float rasters, common NoData data are -9999 and -3.4e+38 respectively, but any value can be used.
If you want to take a deeper dive into other metadata often found with geospatial raster data, this ArcGIS help page does an excellent job of running through the possibilities.
We can all admit that we are by no means experts in geospatial data yet, but that shouldn’t stop us from digging in and seeing what we can accomplish.
For this example, I grabbed some LiDAR data from the Illilouette Creek Basin Lidar Survey, Yosemite Valley, CA 2018 dataset on opentopography.org. The data is open-source, and the interface is straightforward to use. If you prefer, I’ve uploaded the exact data I’m using the Github repository associated with this article.
The next thing we need is a tool that will let us read in our raster data. xarray is a python library that allows us to work with multi-dimensional labeled arrays in python. It's something like Pandas for multi-dimensional data. rioxarray is a package built on top of xarray that provides methods for reading and writing raster files with their metadata. To load in our data, we do the following.
import rioxarrayterrain_file = 'data/rasters_CA18Thompson/output_be.tif'terrain = rioxarray.open_rasterio(terrain_file)surface_file = 'data/rasters_CA18Thompson/output_hh.tif'surface = rioxarray.open_rasterio(surface_file)
If we take a look at surface we can see some information about the data.
We can see that this raster file has one band and that the data on both the x and y axes are float64 values. We can also see the _FillValue which is the same as the NoData value discussed above. To take a more direct look at the metadata, we can inspect individual properties of our xarray. The raster-specific data is in a sub-class called rio.
# Get no data valuesurface.rio.nodata
1.70141e+38
# Show surface CRSprint(surface.rio.crs)
EPSG:6340
The above tells us that our NoData value is 1.70141e+38, and our CRS is EPSG:6340. Go to https://epsg.io/6340 to learn more about this CRS. For our purposes, we only need to know that the CRS for the two files matches. Fortunately, it does.
# Show terrain CRSprint(terrain.rio.crs)
EPSG:6340
Let's take a look at what happens if we plot one of these rasters.
plt.figure(figsize=(10,8))surface.plot()
Hmm. That was less impressive than you hoped, wasn’t it? Looking at the color map on the right-hand side of the plot, we see that the max value is quite large and very similar to our NoData value. We forgot to replace our no data value with np.nan which is the pythonic way of representing missing values. The easiest way to do this is to reimport the file passingmasked=True to the rasterio method.
# reload the surface raster masking nan valuessurface = rioxarray.open_rasterio(surface_file, masked=True)# plot surface rasterplt.figure(figsize=(10,8))surface.plot()plt.title('Digital Surface Model')
That's much better! It is clear now that the white area is outside the dataset and does not contain measurements. Let's take a look at the surface model raster.
# reload the terrain raster masking nan valuesterrain = rioxarray.open_rasterio(terrain_file, masked=True)# plot terrain rasterplt.figure(figsize=(10,8))terrain.plot()plt.title('Digital Terrain Model')
That looks very similar to the surface model.
Lastly, we are going to do a little raster math. We want to know the height of the canopy. In other words, we want to see the height of trees and ground cover relative to the ground. We have a surface model which gives us the contour of all the objects on the land and a terrain model which provides us with the contour of the land itself. To get a canopy height model, we subtract the terrain model from the surface model.
# calculate canopy height modelcanopy = surface - terrain# plot surface rasterplt.figure(figsize=(10,8))canopy.plot()plt.title('Canopy Height Model')
There we have it. We can see this area mostly has low or no ground cover with some sparse trees up to 60 meters tall.
I hope the big takeaway from this article is that geospatial data is not that scary. It deals with one problem that we don’t usually have to deal with in flat datasets: projecting a 3-dimensional globe onto a 2-dimensional raster. We will learn about reprojecting and dealing with data from different sources in future articles in this series. Still, today we learned some basic terminology and worked with some basic geospatial python packages.
The is just the first article in this series. Follow me here on medium if you want to get notified when I post the next article in this series.
Introduction to Geospatial Raster and Vector data with python on carpentries-incubator maintained by Ryan Avery
What is geodata? in the ArcGIS help pages.
OpenTopography.org — Open-source high-resolution topography data and tools.
|
[
{
"code": null,
"e": 416,
"s": 171,
"text": "Let's be honest; geospatial data is scary. I don’t think there is any good reason for this other than that information on how to work with geospatial data in Python is not as easily accessible as information on working with other kinds of data."
},
{
"code": null,
"e": 865,
"s": 416,
"text": "This is the first article in a series focused on various must-know aspects of working with geospatial data in Python. Over the next several weeks, we will look at the main topics in working with geospatial data, including file formats, data types, coordinate systems, and tools to work with the data. I will try to keep these posts bite-sized. I hope that we will develop a comfort with the topic throughout the series, and our fear will fade away."
},
{
"code": null,
"e": 1110,
"s": 865,
"text": "The first 2/3 of this post introduces concepts. In the last 1/3, we will get our hands dirty by pulling in two LiDAR rasters from opentopography.org and calculating a Canopy Height Model from a Digital Surface Model and a Digital Terrain Model."
},
{
"code": null,
"e": 1162,
"s": 1110,
"text": "I’ve organized the article is organized as follows:"
},
{
"code": null,
"e": 1207,
"s": 1162,
"text": "Data TypesMetadataHands-on with raster data."
},
{
"code": null,
"e": 1218,
"s": 1207,
"text": "Data Types"
},
{
"code": null,
"e": 1227,
"s": 1218,
"text": "Metadata"
},
{
"code": null,
"e": 1254,
"s": 1227,
"text": "Hands-on with raster data."
},
{
"code": null,
"e": 1535,
"s": 1254,
"text": "There are two primary data types used in geospatial data: raster data and vector data. This is probably not surprising. If you have done any work on anything visual on a computer recently, you have probably interacted with both. Below we’ll take a brief look at each kind of data."
},
{
"code": null,
"e": 1938,
"s": 1535,
"text": "Raster Data is data in a grid. This is very similar to the data in a photo. In the case of satellite images, this data is like a photo. The difference between this geospatial raster data and photographic raster data is that geospatial data has a way of relating that data to specific locations on earth. It can also contain either float or integer data, unlike an image that only contains integer data."
},
{
"code": null,
"e": 2096,
"s": 1938,
"text": "Raster data can also be categorical. For example, you might classify ground cover as low, medium, or high. In such a case, we map integer data to a category."
},
{
"code": null,
"e": 2312,
"s": 2096,
"text": "Vector geospatial data is also very similar to its design counterpart that you might have worked with in Adobe Illustrator. Again, the difference is that geospatial vector data is mapped to specific places on earth."
},
{
"code": null,
"e": 2346,
"s": 2312,
"text": "Vector data comes in three types."
},
{
"code": null,
"e": 2417,
"s": 2346,
"text": "Each type of vector data can represent different kinds of information."
},
{
"code": null,
"e": 2492,
"s": 2417,
"text": "A point can represent the location of something like a tree or a building."
},
{
"code": null,
"e": 2532,
"s": 2492,
"text": "A line can represent a road or a river."
},
{
"code": null,
"e": 2652,
"s": 2532,
"text": "A polygon can represent geographical units like the boundaries of a country, state, or other areas like national parks."
},
{
"code": null,
"e": 2817,
"s": 2652,
"text": "Geospatial rasters use metadata to communicate many vital aspects of the data to us. Below are a couple of the essential elements found in a raster file’s metadata."
},
{
"code": null,
"e": 3032,
"s": 2817,
"text": "I mentioned above that the essential characteristic of geospatial data is that it connects the data to a specific point on earth. The mechanism which makes this connection is the Coordinate Reference System or CRS."
},
{
"code": null,
"e": 3715,
"s": 3032,
"text": "There is one significant complication. The earth is a globe, and our data representation is two-dimensional. Like any paper map, our data is projected into two dimensions. Different CRS handle this projection differently. For example, some CRS are focused on only a specific area of the earth. Others are more general for projecting large portions of the earth's surface. There are many, many different CRS. Some are more common than others, but for our purposes, we need to know that two rasters with different CRS won’t line up when we visualize or make calculations from them. We will need to have a way to convert both rasters to the same CRS (more on this in a future article)."
},
{
"code": null,
"e": 4072,
"s": 3715,
"text": "Another critical piece of metadata is the NoData value. The grid format of a raster requires there to be data in every square. The NoData value tells us the number used by the raster to indicate that it has no value for that part of the grid. For integer and float rasters, common NoData data are -9999 and -3.4e+38 respectively, but any value can be used."
},
{
"code": null,
"e": 4249,
"s": 4072,
"text": "If you want to take a deeper dive into other metadata often found with geospatial raster data, this ArcGIS help page does an excellent job of running through the possibilities."
},
{
"code": null,
"e": 4400,
"s": 4249,
"text": "We can all admit that we are by no means experts in geospatial data yet, but that shouldn’t stop us from digging in and seeing what we can accomplish."
},
{
"code": null,
"e": 4723,
"s": 4400,
"text": "For this example, I grabbed some LiDAR data from the Illilouette Creek Basin Lidar Survey, Yosemite Valley, CA 2018 dataset on opentopography.org. The data is open-source, and the interface is straightforward to use. If you prefer, I’ve uploaded the exact data I’m using the Github repository associated with this article."
},
{
"code": null,
"e": 5120,
"s": 4723,
"text": "The next thing we need is a tool that will let us read in our raster data. xarray is a python library that allows us to work with multi-dimensional labeled arrays in python. It's something like Pandas for multi-dimensional data. rioxarray is a package built on top of xarray that provides methods for reading and writing raster files with their metadata. To load in our data, we do the following."
},
{
"code": null,
"e": 5343,
"s": 5120,
"text": "import rioxarrayterrain_file = 'data/rasters_CA18Thompson/output_be.tif'terrain = rioxarray.open_rasterio(terrain_file)surface_file = 'data/rasters_CA18Thompson/output_hh.tif'surface = rioxarray.open_rasterio(surface_file)"
},
{
"code": null,
"e": 5416,
"s": 5343,
"text": "If we take a look at surface we can see some information about the data."
},
{
"code": null,
"e": 5762,
"s": 5416,
"text": "We can see that this raster file has one band and that the data on both the x and y axes are float64 values. We can also see the _FillValue which is the same as the NoData value discussed above. To take a more direct look at the metadata, we can inspect individual properties of our xarray. The raster-specific data is in a sub-class called rio."
},
{
"code": null,
"e": 5800,
"s": 5762,
"text": "# Get no data valuesurface.rio.nodata"
},
{
"code": null,
"e": 5812,
"s": 5800,
"text": "1.70141e+38"
},
{
"code": null,
"e": 5853,
"s": 5812,
"text": "# Show surface CRSprint(surface.rio.crs)"
},
{
"code": null,
"e": 5863,
"s": 5853,
"text": "EPSG:6340"
},
{
"code": null,
"e": 6104,
"s": 5863,
"text": "The above tells us that our NoData value is 1.70141e+38, and our CRS is EPSG:6340. Go to https://epsg.io/6340 to learn more about this CRS. For our purposes, we only need to know that the CRS for the two files matches. Fortunately, it does."
},
{
"code": null,
"e": 6145,
"s": 6104,
"text": "# Show terrain CRSprint(terrain.rio.crs)"
},
{
"code": null,
"e": 6155,
"s": 6145,
"text": "EPSG:6340"
},
{
"code": null,
"e": 6222,
"s": 6155,
"text": "Let's take a look at what happens if we plot one of these rasters."
},
{
"code": null,
"e": 6263,
"s": 6222,
"text": "plt.figure(figsize=(10,8))surface.plot()"
},
{
"code": null,
"e": 6663,
"s": 6263,
"text": "Hmm. That was less impressive than you hoped, wasn’t it? Looking at the color map on the right-hand side of the plot, we see that the max value is quite large and very similar to our NoData value. We forgot to replace our no data value with np.nan which is the pythonic way of representing missing values. The easiest way to do this is to reimport the file passingmasked=True to the rasterio method."
},
{
"code": null,
"e": 6865,
"s": 6663,
"text": "# reload the surface raster masking nan valuessurface = rioxarray.open_rasterio(surface_file, masked=True)# plot surface rasterplt.figure(figsize=(10,8))surface.plot()plt.title('Digital Surface Model')"
},
{
"code": null,
"e": 7026,
"s": 6865,
"text": "That's much better! It is clear now that the white area is outside the dataset and does not contain measurements. Let's take a look at the surface model raster."
},
{
"code": null,
"e": 7228,
"s": 7026,
"text": "# reload the terrain raster masking nan valuesterrain = rioxarray.open_rasterio(terrain_file, masked=True)# plot terrain rasterplt.figure(figsize=(10,8))terrain.plot()plt.title('Digital Terrain Model')"
},
{
"code": null,
"e": 7274,
"s": 7228,
"text": "That looks very similar to the surface model."
},
{
"code": null,
"e": 7698,
"s": 7274,
"text": "Lastly, we are going to do a little raster math. We want to know the height of the canopy. In other words, we want to see the height of trees and ground cover relative to the ground. We have a surface model which gives us the contour of all the objects on the land and a terrain model which provides us with the contour of the land itself. To get a canopy height model, we subtract the terrain model from the surface model."
},
{
"code": null,
"e": 7848,
"s": 7698,
"text": "# calculate canopy height modelcanopy = surface - terrain# plot surface rasterplt.figure(figsize=(10,8))canopy.plot()plt.title('Canopy Height Model')"
},
{
"code": null,
"e": 7966,
"s": 7848,
"text": "There we have it. We can see this area mostly has low or no ground cover with some sparse trees up to 60 meters tall."
},
{
"code": null,
"e": 8412,
"s": 7966,
"text": "I hope the big takeaway from this article is that geospatial data is not that scary. It deals with one problem that we don’t usually have to deal with in flat datasets: projecting a 3-dimensional globe onto a 2-dimensional raster. We will learn about reprojecting and dealing with data from different sources in future articles in this series. Still, today we learned some basic terminology and worked with some basic geospatial python packages."
},
{
"code": null,
"e": 8556,
"s": 8412,
"text": "The is just the first article in this series. Follow me here on medium if you want to get notified when I post the next article in this series."
},
{
"code": null,
"e": 8668,
"s": 8556,
"text": "Introduction to Geospatial Raster and Vector data with python on carpentries-incubator maintained by Ryan Avery"
},
{
"code": null,
"e": 8711,
"s": 8668,
"text": "What is geodata? in the ArcGIS help pages."
}
] |
Lua - Database Access
|
For simple data operations, we may use files, but, sometimes, these file operations may not be efficient, scalable, and powerful. For this purpose, we may often switch to using databases. LuaSQL is a simple interface from Lua to a number of database management systems. LuaSQL is the library, which provides support for different types of SQL. This include,
SQLite
Mysql
ODBC
In this tutorial, we will be covering database handling of MySQL an SQLite in Lua. This uses a generic interface for both and should be possible to port this implementation to other types of databases as well. First let see how you can do the operations in MySQL.
In order to use the following examples to work as expected, we need the initial db setup. The assumptions are listed below.
You have installed and setup MySQL with default user as root and password as '123456'.
You have installed and setup MySQL with default user as root and password as '123456'.
You have created a database test.
You have created a database test.
You have gone through MySQL tutorial to understand MySQL Basics.
You have gone through MySQL tutorial to understand MySQL Basics.
We can use a simple require statement to import the sqlite library assuming that your Lua implementation was done correctly.
mysql = require "luasql.mysql"
The variable mysql will provide access to the functions by referring to the main mysql table.
We can set up the connection by initiating a MySQL environment and then creating a connection for the environment. It is shown below.
local env = mysql.mysql()
local conn = env:connect('test','root','123456')
The above connection will connect to an existing MySQL file and establishes the connection with the newly created file.
There is a simple execute function available with the connection that will help us to do all the db operations from create, insert, delete, update and so on. The syntax is shown below −
conn:execute([[ 'MySQLSTATEMENT' ]])
In the above syntax, we need to ensure that conn is open and existing MySQL connection and replace the 'MySQLSTATEMENT' with the correct statement.
A simple create table example is shown below. It creates a table with two parameters id of type integer and name of type varchar.
mysql = require "luasql.mysql"
local env = mysql.mysql()
local conn = env:connect('test','root','123456')
print(env,conn)
status,errorString = conn:execute([[CREATE TABLE sample2 (id INTEGER, name TEXT);]])
print(status,errorString )
When you run the above program, a table named sample will be created with two columns namely, id and name.
MySQL environment (004BB178) MySQL connection (004BE3C8)
0 nil
In case there is any error, you would be returned an error statement instead of nil. A simple error statement is shown below.
LuaSQL: Error executing query. MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"id INTEGER, name TEXT)' at line 1
An insert statement for MySQL is shown below.
conn:execute([[INSERT INTO sample values('11','Raj')]])
An update statement for MySQL is shown below.
conn:execute([[UPDATE sample3 SET name='John' where id ='12']])
A delete statement for MySQL is shown below.
conn:execute([[DELETE from sample3 where id ='12']])
As far as select statement is concerned, we need to loop through each of the rows and extract the required data. A simple select statement is shown below.
cursor,errorString = conn:execute([[select * from sample]])
row = cursor:fetch ({}, "a")
while row do
print(string.format("Id: %s, Name: %s", row.id, row.name))
-- reusing the table of results
row = cursor:fetch (row, "a")
end
In the above code, conn is an open MySQL connection. With the help of the cursor returned by the execute statement, you can loop through the table response and fetch the required select data.
A complete example including all the above statements is given below.
mysql = require "luasql.mysql"
local env = mysql.mysql()
local conn = env:connect('test','root','123456')
print(env,conn)
status,errorString = conn:execute([[CREATE TABLE sample3 (id INTEGER, name TEXT)]])
print(status,errorString )
status,errorString = conn:execute([[INSERT INTO sample3 values('12','Raj')]])
print(status,errorString )
cursor,errorString = conn:execute([[select * from sample3]])
print(cursor,errorString)
row = cursor:fetch ({}, "a")
while row do
print(string.format("Id: %s, Name: %s", row.id, row.name))
row = cursor:fetch (row, "a")
end
-- close everything
cursor:close()
conn:close()
env:close()
When you run the above program, you will get the following output.
MySQL environment (0037B178) MySQL connection (0037EBA8)
0 nil
1 nil
MySQL cursor (003778A8) nil
Id: 12, Name: Raj
Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties −
Atomicity − Either a transaction completes or nothing happens at all.
Atomicity − Either a transaction completes or nothing happens at all.
Consistency − A transaction must start in a consistent state and leave the system in a consistent state.
Consistency − A transaction must start in a consistent state and leave the system in a consistent state.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Durability − Once a transaction was committed, the effects are persistent, even after a system failure.
Durability − Once a transaction was committed, the effects are persistent, even after a system failure.
Transaction starts with START TRANSACTION; and ends with commit or rollback statement.
In order to initiate a transaction, we need to execute the following statement in Lua, assuming conn is an open MySQL connection.
conn:execute([[START TRANSACTION;]])
We need to execute the following statement to rollback changes made after start transaction is executed.
conn:execute([[ROLLBACK;]])
We need to execute the following statement to commit changes made after start transaction is executed.
conn:execute([[COMMIT;]])
We have known about MySQL in the above and following section explains about basic SQL operations. Remember transactions, though not explained again for SQLite3 but the same statements should work for SQLite3 as well.
We can use a simple require statement to import the SQLite library assuming that your Lua implementation was done correctly. During installation, a folder libsql that contains the database related files.
sqlite3 = require "luasql.sqlite3"
The variable sqlite3 will provide access to the functions by referring to the main sqlite3 table.
We can set up the connection by initiating an SQLite environment and then creating a connection for the environment. It is shown below.
local env = sqlite3.sqlite3()
local conn = env:connect('mydb.sqlite')
The above connection will connect to an existing SQLite file or creates a new SQLite file and establishes the connection with the newly created file.
There is a simple execute function available with the connection that will help us to do all the db operations from create, insert, delete, update and so on. The syntax is shown below −
conn:execute([[ 'SQLite3STATEMENT' ]])
In the above syntax we need to ensure that conn is open and existing sqlite3 connection and replace the 'SQLite3STATEMENT' with the correct statement.
A simple create table example is shown below. It creates a table with two parameters id of type integer and name of type varchar.
sqlite3 = require "luasql.sqlite3"
local env = sqlite3.sqlite3()
local conn = env:connect('mydb.sqlite')
print(env,conn)
status,errorString = conn:execute([[CREATE TABLE sample ('id' INTEGER, 'name' TEXT)]])
print(status,errorString )
When you run the above program, a table named sample will be created with two columns namely, id and name.
SQLite3 environment (003EC918) SQLite3 connection (00421F08)
0 nil
In case of an error, you would be returned a error statement instead of nil. A simple error statement is shown below.
LuaSQL: unrecognized token: ""'id' INTEGER, 'name' TEXT)"
An insert statement for SQLite is shown below.
conn:execute([[INSERT INTO sample values('11','Raj')]])
As far as select statement is concerned, we need to loop through each of the rows and extract the required data. A simple select statement is shown below.
cursor,errorString = conn:execute([[select * from sample]])
row = cursor:fetch ({}, "a")
while row do
print(string.format("Id: %s, Name: %s", row.id, row.name))
-- reusing the table of results
row = cursor:fetch (row, "a")
end
In the above code, conn is an open sqlite3 connection. With the help of the cursor returned by the execute statement, you can loop through the table response and fetch the required select data.
A complete example including all the above statements is given below.
sqlite3 = require "luasql.sqlite3"
local env = sqlite3.sqlite3()
local conn = env:connect('mydb.sqlite')
print(env,conn)
status,errorString = conn:execute([[CREATE TABLE sample ('id' INTEGER, 'name' TEXT)]])
print(status,errorString )
status,errorString = conn:execute([[INSERT INTO sample values('1','Raj')]])
print(status,errorString )
cursor,errorString = conn:execute([[select * from sample]])
print(cursor,errorString)
row = cursor:fetch ({}, "a")
while row do
print(string.format("Id: %s, Name: %s", row.id, row.name))
row = cursor:fetch (row, "a")
end
-- close everything
cursor:close()
conn:close()
env:close()
When you run the above program, you will get the following output.
SQLite3 environment (005EC918) SQLite3 connection (005E77B0)
0 nil
1 nil
SQLite3 cursor (005E9200) nil
Id: 1, Name: Raj
We can execute all the available queries with the help of this libsql library. So, please don't stop with these examples. Experiment various query statement available in respective MySQL, SQLite3 and other supported db in 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": 2461,
"s": 2103,
"text": "For simple data operations, we may use files, but, sometimes, these file operations may not be efficient, scalable, and powerful. For this purpose, we may often switch to using databases. LuaSQL is a simple interface from Lua to a number of database management systems. LuaSQL is the library, which provides support for different types of SQL. This include,"
},
{
"code": null,
"e": 2468,
"s": 2461,
"text": "SQLite"
},
{
"code": null,
"e": 2474,
"s": 2468,
"text": "Mysql"
},
{
"code": null,
"e": 2479,
"s": 2474,
"text": "ODBC"
},
{
"code": null,
"e": 2743,
"s": 2479,
"text": "In this tutorial, we will be covering database handling of MySQL an SQLite in Lua. This uses a generic interface for both and should be possible to port this implementation to other types of databases as well. First let see how you can do the operations in MySQL."
},
{
"code": null,
"e": 2867,
"s": 2743,
"text": "In order to use the following examples to work as expected, we need the initial db setup. The assumptions are listed below."
},
{
"code": null,
"e": 2954,
"s": 2867,
"text": "You have installed and setup MySQL with default user as root and password as '123456'."
},
{
"code": null,
"e": 3041,
"s": 2954,
"text": "You have installed and setup MySQL with default user as root and password as '123456'."
},
{
"code": null,
"e": 3075,
"s": 3041,
"text": "You have created a database test."
},
{
"code": null,
"e": 3109,
"s": 3075,
"text": "You have created a database test."
},
{
"code": null,
"e": 3174,
"s": 3109,
"text": "You have gone through MySQL tutorial to understand MySQL Basics."
},
{
"code": null,
"e": 3239,
"s": 3174,
"text": "You have gone through MySQL tutorial to understand MySQL Basics."
},
{
"code": null,
"e": 3364,
"s": 3239,
"text": "We can use a simple require statement to import the sqlite library assuming that your Lua implementation was done correctly."
},
{
"code": null,
"e": 3396,
"s": 3364,
"text": "mysql = require \"luasql.mysql\"\n"
},
{
"code": null,
"e": 3490,
"s": 3396,
"text": "The variable mysql will provide access to the functions by referring to the main mysql table."
},
{
"code": null,
"e": 3624,
"s": 3490,
"text": "We can set up the connection by initiating a MySQL environment and then creating a connection for the environment. It is shown below."
},
{
"code": null,
"e": 3701,
"s": 3624,
"text": "local env = mysql.mysql()\nlocal conn = env:connect('test','root','123456')\n"
},
{
"code": null,
"e": 3821,
"s": 3701,
"text": "The above connection will connect to an existing MySQL file and establishes the connection with the newly created file."
},
{
"code": null,
"e": 4007,
"s": 3821,
"text": "There is a simple execute function available with the connection that will help us to do all the db operations from create, insert, delete, update and so on. The syntax is shown below −"
},
{
"code": null,
"e": 4045,
"s": 4007,
"text": "conn:execute([[ 'MySQLSTATEMENT' ]])\n"
},
{
"code": null,
"e": 4193,
"s": 4045,
"text": "In the above syntax, we need to ensure that conn is open and existing MySQL connection and replace the 'MySQLSTATEMENT' with the correct statement."
},
{
"code": null,
"e": 4323,
"s": 4193,
"text": "A simple create table example is shown below. It creates a table with two parameters id of type integer and name of type varchar."
},
{
"code": null,
"e": 4561,
"s": 4323,
"text": "mysql = require \"luasql.mysql\"\n\nlocal env = mysql.mysql()\nlocal conn = env:connect('test','root','123456')\n\nprint(env,conn)\n\nstatus,errorString = conn:execute([[CREATE TABLE sample2 (id INTEGER, name TEXT);]])\nprint(status,errorString )"
},
{
"code": null,
"e": 4668,
"s": 4561,
"text": "When you run the above program, a table named sample will be created with two columns namely, id and name."
},
{
"code": null,
"e": 4732,
"s": 4668,
"text": "MySQL environment (004BB178)\tMySQL connection (004BE3C8)\n0\tnil\n"
},
{
"code": null,
"e": 4858,
"s": 4732,
"text": "In case there is any error, you would be returned an error statement instead of nil. A simple error statement is shown below."
},
{
"code": null,
"e": 5067,
"s": 4858,
"text": "LuaSQL: Error executing query. MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\"id INTEGER, name TEXT)' at line 1\n"
},
{
"code": null,
"e": 5113,
"s": 5067,
"text": "An insert statement for MySQL is shown below."
},
{
"code": null,
"e": 5170,
"s": 5113,
"text": "conn:execute([[INSERT INTO sample values('11','Raj')]])\n"
},
{
"code": null,
"e": 5216,
"s": 5170,
"text": "An update statement for MySQL is shown below."
},
{
"code": null,
"e": 5281,
"s": 5216,
"text": "conn:execute([[UPDATE sample3 SET name='John' where id ='12']])\n"
},
{
"code": null,
"e": 5326,
"s": 5281,
"text": "A delete statement for MySQL is shown below."
},
{
"code": null,
"e": 5380,
"s": 5326,
"text": "conn:execute([[DELETE from sample3 where id ='12']])\n"
},
{
"code": null,
"e": 5535,
"s": 5380,
"text": "As far as select statement is concerned, we need to loop through each of the rows and extract the required data. A simple select statement is shown below."
},
{
"code": null,
"e": 5772,
"s": 5535,
"text": "cursor,errorString = conn:execute([[select * from sample]])\nrow = cursor:fetch ({}, \"a\")\n\nwhile row do\n print(string.format(\"Id: %s, Name: %s\", row.id, row.name))\n -- reusing the table of results\n row = cursor:fetch (row, \"a\")\nend"
},
{
"code": null,
"e": 5964,
"s": 5772,
"text": "In the above code, conn is an open MySQL connection. With the help of the cursor returned by the execute statement, you can loop through the table response and fetch the required select data."
},
{
"code": null,
"e": 6034,
"s": 5964,
"text": "A complete example including all the above statements is given below."
},
{
"code": null,
"e": 6668,
"s": 6034,
"text": "mysql = require \"luasql.mysql\"\n\nlocal env = mysql.mysql()\nlocal conn = env:connect('test','root','123456')\nprint(env,conn)\n\nstatus,errorString = conn:execute([[CREATE TABLE sample3 (id INTEGER, name TEXT)]])\nprint(status,errorString )\n\nstatus,errorString = conn:execute([[INSERT INTO sample3 values('12','Raj')]])\nprint(status,errorString )\n\ncursor,errorString = conn:execute([[select * from sample3]])\nprint(cursor,errorString)\n\nrow = cursor:fetch ({}, \"a\")\n\nwhile row do\n print(string.format(\"Id: %s, Name: %s\", row.id, row.name))\n row = cursor:fetch (row, \"a\")\nend\n\n-- close everything\ncursor:close()\nconn:close()\nenv:close()"
},
{
"code": null,
"e": 6735,
"s": 6668,
"text": "When you run the above program, you will get the following output."
},
{
"code": null,
"e": 6851,
"s": 6735,
"text": "MySQL environment (0037B178)\tMySQL connection (0037EBA8)\n0\tnil\n1\tnil\nMySQL cursor (003778A8)\tnil\nId: 12, Name: Raj\n"
},
{
"code": null,
"e": 6968,
"s": 6851,
"text": "Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties −"
},
{
"code": null,
"e": 7038,
"s": 6968,
"text": "Atomicity − Either a transaction completes or nothing happens at all."
},
{
"code": null,
"e": 7108,
"s": 7038,
"text": "Atomicity − Either a transaction completes or nothing happens at all."
},
{
"code": null,
"e": 7213,
"s": 7108,
"text": "Consistency − A transaction must start in a consistent state and leave the system in a consistent state."
},
{
"code": null,
"e": 7318,
"s": 7213,
"text": "Consistency − A transaction must start in a consistent state and leave the system in a consistent state."
},
{
"code": null,
"e": 7417,
"s": 7318,
"text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction."
},
{
"code": null,
"e": 7516,
"s": 7417,
"text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction."
},
{
"code": null,
"e": 7620,
"s": 7516,
"text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure."
},
{
"code": null,
"e": 7724,
"s": 7620,
"text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure."
},
{
"code": null,
"e": 7811,
"s": 7724,
"text": "Transaction starts with START TRANSACTION; and ends with commit or rollback statement."
},
{
"code": null,
"e": 7941,
"s": 7811,
"text": "In order to initiate a transaction, we need to execute the following statement in Lua, assuming conn is an open MySQL connection."
},
{
"code": null,
"e": 7979,
"s": 7941,
"text": "conn:execute([[START TRANSACTION;]])\n"
},
{
"code": null,
"e": 8084,
"s": 7979,
"text": "We need to execute the following statement to rollback changes made after start transaction is executed."
},
{
"code": null,
"e": 8113,
"s": 8084,
"text": "conn:execute([[ROLLBACK;]])\n"
},
{
"code": null,
"e": 8216,
"s": 8113,
"text": "We need to execute the following statement to commit changes made after start transaction is executed."
},
{
"code": null,
"e": 8243,
"s": 8216,
"text": "conn:execute([[COMMIT;]])\n"
},
{
"code": null,
"e": 8460,
"s": 8243,
"text": "We have known about MySQL in the above and following section explains about basic SQL operations. Remember transactions, though not explained again for SQLite3 but the same statements should work for SQLite3 as well."
},
{
"code": null,
"e": 8664,
"s": 8460,
"text": "We can use a simple require statement to import the SQLite library assuming that your Lua implementation was done correctly. During installation, a folder libsql that contains the database related files."
},
{
"code": null,
"e": 8700,
"s": 8664,
"text": "sqlite3 = require \"luasql.sqlite3\"\n"
},
{
"code": null,
"e": 8798,
"s": 8700,
"text": "The variable sqlite3 will provide access to the functions by referring to the main sqlite3 table."
},
{
"code": null,
"e": 8934,
"s": 8798,
"text": "We can set up the connection by initiating an SQLite environment and then creating a connection for the environment. It is shown below."
},
{
"code": null,
"e": 9006,
"s": 8934,
"text": "local env = sqlite3.sqlite3()\nlocal conn = env:connect('mydb.sqlite')\n"
},
{
"code": null,
"e": 9156,
"s": 9006,
"text": "The above connection will connect to an existing SQLite file or creates a new SQLite file and establishes the connection with the newly created file."
},
{
"code": null,
"e": 9342,
"s": 9156,
"text": "There is a simple execute function available with the connection that will help us to do all the db operations from create, insert, delete, update and so on. The syntax is shown below −"
},
{
"code": null,
"e": 9382,
"s": 9342,
"text": "conn:execute([[ 'SQLite3STATEMENT' ]])\n"
},
{
"code": null,
"e": 9533,
"s": 9382,
"text": "In the above syntax we need to ensure that conn is open and existing sqlite3 connection and replace the 'SQLite3STATEMENT' with the correct statement."
},
{
"code": null,
"e": 9663,
"s": 9533,
"text": "A simple create table example is shown below. It creates a table with two parameters id of type integer and name of type varchar."
},
{
"code": null,
"e": 9901,
"s": 9663,
"text": "sqlite3 = require \"luasql.sqlite3\"\n\nlocal env = sqlite3.sqlite3()\nlocal conn = env:connect('mydb.sqlite')\nprint(env,conn)\n\nstatus,errorString = conn:execute([[CREATE TABLE sample ('id' INTEGER, 'name' TEXT)]])\nprint(status,errorString )"
},
{
"code": null,
"e": 10008,
"s": 9901,
"text": "When you run the above program, a table named sample will be created with two columns namely, id and name."
},
{
"code": null,
"e": 10076,
"s": 10008,
"text": "SQLite3 environment (003EC918)\tSQLite3 connection (00421F08)\n0\tnil\n"
},
{
"code": null,
"e": 10194,
"s": 10076,
"text": "In case of an error, you would be returned a error statement instead of nil. A simple error statement is shown below."
},
{
"code": null,
"e": 10253,
"s": 10194,
"text": "LuaSQL: unrecognized token: \"\"'id' INTEGER, 'name' TEXT)\"\n"
},
{
"code": null,
"e": 10300,
"s": 10253,
"text": "An insert statement for SQLite is shown below."
},
{
"code": null,
"e": 10358,
"s": 10300,
"text": " conn:execute([[INSERT INTO sample values('11','Raj')]])\n"
},
{
"code": null,
"e": 10513,
"s": 10358,
"text": "As far as select statement is concerned, we need to loop through each of the rows and extract the required data. A simple select statement is shown below."
},
{
"code": null,
"e": 10750,
"s": 10513,
"text": "cursor,errorString = conn:execute([[select * from sample]])\nrow = cursor:fetch ({}, \"a\")\n\nwhile row do\n print(string.format(\"Id: %s, Name: %s\", row.id, row.name))\n -- reusing the table of results\n row = cursor:fetch (row, \"a\")\nend"
},
{
"code": null,
"e": 10944,
"s": 10750,
"text": "In the above code, conn is an open sqlite3 connection. With the help of the cursor returned by the execute statement, you can loop through the table response and fetch the required select data."
},
{
"code": null,
"e": 11014,
"s": 10944,
"text": "A complete example including all the above statements is given below."
},
{
"code": null,
"e": 11647,
"s": 11014,
"text": "sqlite3 = require \"luasql.sqlite3\"\n\nlocal env = sqlite3.sqlite3()\nlocal conn = env:connect('mydb.sqlite')\nprint(env,conn)\n\nstatus,errorString = conn:execute([[CREATE TABLE sample ('id' INTEGER, 'name' TEXT)]])\nprint(status,errorString )\n\nstatus,errorString = conn:execute([[INSERT INTO sample values('1','Raj')]])\nprint(status,errorString )\n\ncursor,errorString = conn:execute([[select * from sample]])\nprint(cursor,errorString)\n\nrow = cursor:fetch ({}, \"a\")\n\nwhile row do\n print(string.format(\"Id: %s, Name: %s\", row.id, row.name))\n row = cursor:fetch (row, \"a\")\nend\n\n-- close everything\ncursor:close()\nconn:close()\nenv:close()"
},
{
"code": null,
"e": 11714,
"s": 11647,
"text": "When you run the above program, you will get the following output."
},
{
"code": null,
"e": 11835,
"s": 11714,
"text": "SQLite3 environment (005EC918)\tSQLite3 connection (005E77B0)\n0\tnil\n1\tnil\nSQLite3 cursor (005E9200)\tnil\nId: 1, Name: Raj\n"
},
{
"code": null,
"e": 12062,
"s": 11835,
"text": "We can execute all the available queries with the help of this libsql library. So, please don't stop with these examples. Experiment various query statement available in respective MySQL, SQLite3 and other supported db in Lua."
},
{
"code": null,
"e": 12095,
"s": 12062,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12109,
"s": 12095,
"text": " Manish Gupta"
},
{
"code": null,
"e": 12142,
"s": 12109,
"text": "\n 80 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 12158,
"s": 12142,
"text": " Sanjeev Mittal"
},
{
"code": null,
"e": 12193,
"s": 12158,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12209,
"s": 12193,
"text": " Mehmet GOKTEPE"
},
{
"code": null,
"e": 12216,
"s": 12209,
"text": " Print"
},
{
"code": null,
"e": 12227,
"s": 12216,
"text": " Add Notes"
}
] |
Print boundary elements of a given matrix in clockwise manner - GeeksforGeeks
|
26 Apr, 2021
Given a matrix arr[][] of size N * M, the task is to print the boundary elements of the given matrix in a clockwise form.
Examples:
Input: arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9} }Output: 1 2 3 6 9 8 7 4Explanation:Boundary elements of the matrix are: 1 2 3 4 5 6 7 8 <strong>9 Therefore, the sequence of boundary elements in clockwise form is {1, 2, 3, 6, 9, 8, 7, 4}.
Input: arr[][] = {{11, 12, 33}, {64, 57, 61}, {74, 88, 39}}Output: 11 12 33 61 39 88 74 64
Naive Approach: The simplest approach to solve this problem is to traverse the given matrix and check if the current element is the boundary element or not. If found to be true, then print the element.
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to traverse only the first and last rows and the first and last columns of the matrix. Follow the steps below to solve the problem:
Print the first row of the matrix.
Print the last column of the matrix except the first row.
Print the last row of the matrix except the last column.
Print the first column of the matrix except the first and last row.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function to print the boundary elements// of the matrix in clockwisevoid boundaryTraversal(vector<vector<int> > arr, int N, int M){ // Print the first row for (int i = 0; i < M; i++) { cout << arr[0][i] << " "; } // Print the last column // except the first row for (int i = 1; i < N; i++) { cout << arr[i][M - 1] << " "; } // Print the last row // except the last column if (N > 1) { // Print the last row for (int i = M - 2; i >= 0; i--) { cout << arr[N - 1][i] << " "; } } // Print the first column except // the first and last row if (M > 1) { // Print the first column for (int i = N - 2; i > 0; i--) { cout << arr[i][0] << " "; } }} // Driver Codeint main(){ vector<vector<int> > arr{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int N = arr.size(); int M = arr[0].size(); // Function Call boundaryTraversal(arr, N, M); return 0;} // This code is contributed by Dharanendra L V
// Java program of the above approachimport java.util.*; class GFG { // Function to print the boundary elements // of the matrix in clockwise public static void boundaryTraversal( int arr[][], int N, int M) { // Print the first row for (int i = 0; i < M; i++) { System.out.print(arr[0][i] + " "); } // Print the last column // except the first row for (int i = 1; i < N; i++) { System.out.print(arr[i][M - 1] + " "); } // Print the last row // except the last column if (N > 1) { // Print the last row for (int i = M - 2; i >= 0; i--) { System.out.print(arr[N - 1][i] + " "); } } // Print the first column except // the first and last row if (M > 1) { // Print the first column for (int i = N - 2; i > 0; i--) { System.out.print(arr[i][0] + " "); } } } // Driver Code public static void main(String[] args) { int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int N = arr.length; int M = arr[0].length; // Function Call boundaryTraversal(arr, N, M); }}
# Python program of the above approach # Function to print the boundary elements# of the matrix in clockwisedef boundaryTraversal(arr, N, M): # Print the first row for i in range(M): print(arr[0][i], end = " "); # Print the last column # except the first row for i in range(1, N): print(arr[i][M - 1], end = " "); # Print the last row # except the last column if (N > 1): # Print the last row for i in range(M - 2, -1, -1): print(arr[N - 1][i], end = " "); # Print the first column except # the first and last row if (M > 1): # Print the first column for i in range(N - 2, 0, -1): print(arr[i][0], end = " "); # Driver Codeif __name__ == '__main__': arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; N = len(arr); M = len(arr[0]); # Function Call boundaryTraversal(arr, N, M); # This code is contributed by 29AjayKumar
// C# program of the above approachusing System; class GFG{ // Function to print the boundary elements// of the matrix in clockwisestatic void boundaryTraversal(int[,] arr, int N, int M){ // Print the first row for(int i = 0; i < M; i++) { Console.Write(arr[0, i] + " "); } // Print the last column // except the first row for(int i = 1; i < N; i++) { Console.Write(arr[i, M - 1] + " "); } // Print the last row // except the last column if (N > 1) { // Print the last row for(int i = M - 2; i >= 0; i--) { Console.Write(arr[N - 1, i] + " "); } } // Print the first column except // the first and last row if (M > 1) { // Print the first column for(int i = N - 2; i > 0; i--) { Console.Write(arr[i, 0] + " "); } }} // Driver code static void Main(){ int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int N = 3; int M = 3; // Function Call boundaryTraversal(arr, N, M);}} // This code is contributed by divyeshrabadiya07
<script> // Javascript program of the above approach // Function to print the boundary elements// of the matrix in clockwisefunction boundaryTraversal(arr, N, M){ // Print the first row for (let i = 0; i < M; i++) { document.write(arr[0][i] + " "); } // Print the last column // except the first row for (let i = 1; i < N; i++) { document.write(arr[i][M - 1] + " "); } // Print the last row // except the last column if (N > 1) { // Print the last row for (let i = M - 2; i >= 0; i--) { document.write(arr[N - 1][i] + " "); } } // Print the first column except // the first and last row if (M > 1) { // Print the first column for (let i = N - 2; i > 0; i--) { document.write(arr[i][0] + " "); } }} // Driver Code let arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; let N = arr.length; let M = arr[0].length; // Function Call boundaryTraversal(arr, N, M); </script>
1 2 3 6 9 8 7 4
Time Complexity: O(N + M)Auxiliary Space: O(1)
divyeshrabadiya07
29AjayKumar
dharanendralv23
nidhi_biet
souravmahato348
spiral
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flood fill Algorithm - how to implement fill() in paint?
Multiplication of Matrix using threads
Program to find the Sum of each Row and each Column of a Matrix
Mathematics | L U Decomposition of a System of Linear Equations
Python program to add two Matrices
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
|
[
{
"code": null,
"e": 24841,
"s": 24813,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 24963,
"s": 24841,
"text": "Given a matrix arr[][] of size N * M, the task is to print the boundary elements of the given matrix in a clockwise form."
},
{
"code": null,
"e": 24973,
"s": 24963,
"text": "Examples:"
},
{
"code": null,
"e": 25216,
"s": 24973,
"text": "Input: arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9} }Output: 1 2 3 6 9 8 7 4Explanation:Boundary elements of the matrix are: 1 2 3 4 5 6 7 8 <strong>9 Therefore, the sequence of boundary elements in clockwise form is {1, 2, 3, 6, 9, 8, 7, 4}. "
},
{
"code": null,
"e": 25307,
"s": 25216,
"text": "Input: arr[][] = {{11, 12, 33}, {64, 57, 61}, {74, 88, 39}}Output: 11 12 33 61 39 88 74 64"
},
{
"code": null,
"e": 25510,
"s": 25307,
"text": "Naive Approach: The simplest approach to solve this problem is to traverse the given matrix and check if the current element is the boundary element or not. If found to be true, then print the element. "
},
{
"code": null,
"e": 25554,
"s": 25510,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 25750,
"s": 25554,
"text": "Efficient Approach: To optimize the above approach, the idea is to traverse only the first and last rows and the first and last columns of the matrix. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25785,
"s": 25750,
"text": "Print the first row of the matrix."
},
{
"code": null,
"e": 25843,
"s": 25785,
"text": "Print the last column of the matrix except the first row."
},
{
"code": null,
"e": 25900,
"s": 25843,
"text": "Print the last row of the matrix except the last column."
},
{
"code": null,
"e": 25968,
"s": 25900,
"text": "Print the first column of the matrix except the first and last row."
},
{
"code": null,
"e": 26019,
"s": 25968,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26023,
"s": 26019,
"text": "C++"
},
{
"code": null,
"e": 26028,
"s": 26023,
"text": "Java"
},
{
"code": null,
"e": 26036,
"s": 26028,
"text": "Python3"
},
{
"code": null,
"e": 26039,
"s": 26036,
"text": "C#"
},
{
"code": null,
"e": 26050,
"s": 26039,
"text": "Javascript"
},
{
"code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function to print the boundary elements// of the matrix in clockwisevoid boundaryTraversal(vector<vector<int> > arr, int N, int M){ // Print the first row for (int i = 0; i < M; i++) { cout << arr[0][i] << \" \"; } // Print the last column // except the first row for (int i = 1; i < N; i++) { cout << arr[i][M - 1] << \" \"; } // Print the last row // except the last column if (N > 1) { // Print the last row for (int i = M - 2; i >= 0; i--) { cout << arr[N - 1][i] << \" \"; } } // Print the first column except // the first and last row if (M > 1) { // Print the first column for (int i = N - 2; i > 0; i--) { cout << arr[i][0] << \" \"; } }} // Driver Codeint main(){ vector<vector<int> > arr{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int N = arr.size(); int M = arr[0].size(); // Function Call boundaryTraversal(arr, N, M); return 0;} // This code is contributed by Dharanendra L V",
"e": 27156,
"s": 26050,
"text": null
},
{
"code": "// Java program of the above approachimport java.util.*; class GFG { // Function to print the boundary elements // of the matrix in clockwise public static void boundaryTraversal( int arr[][], int N, int M) { // Print the first row for (int i = 0; i < M; i++) { System.out.print(arr[0][i] + \" \"); } // Print the last column // except the first row for (int i = 1; i < N; i++) { System.out.print(arr[i][M - 1] + \" \"); } // Print the last row // except the last column if (N > 1) { // Print the last row for (int i = M - 2; i >= 0; i--) { System.out.print(arr[N - 1][i] + \" \"); } } // Print the first column except // the first and last row if (M > 1) { // Print the first column for (int i = N - 2; i > 0; i--) { System.out.print(arr[i][0] + \" \"); } } } // Driver Code public static void main(String[] args) { int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int N = arr.length; int M = arr[0].length; // Function Call boundaryTraversal(arr, N, M); }}",
"e": 28457,
"s": 27156,
"text": null
},
{
"code": "# Python program of the above approach # Function to print the boundary elements# of the matrix in clockwisedef boundaryTraversal(arr, N, M): # Print the first row for i in range(M): print(arr[0][i], end = \" \"); # Print the last column # except the first row for i in range(1, N): print(arr[i][M - 1], end = \" \"); # Print the last row # except the last column if (N > 1): # Print the last row for i in range(M - 2, -1, -1): print(arr[N - 1][i], end = \" \"); # Print the first column except # the first and last row if (M > 1): # Print the first column for i in range(N - 2, 0, -1): print(arr[i][0], end = \" \"); # Driver Codeif __name__ == '__main__': arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; N = len(arr); M = len(arr[0]); # Function Call boundaryTraversal(arr, N, M); # This code is contributed by 29AjayKumar",
"e": 29412,
"s": 28457,
"text": null
},
{
"code": "// C# program of the above approachusing System; class GFG{ // Function to print the boundary elements// of the matrix in clockwisestatic void boundaryTraversal(int[,] arr, int N, int M){ // Print the first row for(int i = 0; i < M; i++) { Console.Write(arr[0, i] + \" \"); } // Print the last column // except the first row for(int i = 1; i < N; i++) { Console.Write(arr[i, M - 1] + \" \"); } // Print the last row // except the last column if (N > 1) { // Print the last row for(int i = M - 2; i >= 0; i--) { Console.Write(arr[N - 1, i] + \" \"); } } // Print the first column except // the first and last row if (M > 1) { // Print the first column for(int i = N - 2; i > 0; i--) { Console.Write(arr[i, 0] + \" \"); } }} // Driver code static void Main(){ int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int N = 3; int M = 3; // Function Call boundaryTraversal(arr, N, M);}} // This code is contributed by divyeshrabadiya07",
"e": 30612,
"s": 29412,
"text": null
},
{
"code": "<script> // Javascript program of the above approach // Function to print the boundary elements// of the matrix in clockwisefunction boundaryTraversal(arr, N, M){ // Print the first row for (let i = 0; i < M; i++) { document.write(arr[0][i] + \" \"); } // Print the last column // except the first row for (let i = 1; i < N; i++) { document.write(arr[i][M - 1] + \" \"); } // Print the last row // except the last column if (N > 1) { // Print the last row for (let i = M - 2; i >= 0; i--) { document.write(arr[N - 1][i] + \" \"); } } // Print the first column except // the first and last row if (M > 1) { // Print the first column for (let i = N - 2; i > 0; i--) { document.write(arr[i][0] + \" \"); } }} // Driver Code let arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; let N = arr.length; let M = arr[0].length; // Function Call boundaryTraversal(arr, N, M); </script>",
"e": 31599,
"s": 30612,
"text": null
},
{
"code": null,
"e": 31615,
"s": 31599,
"text": "1 2 3 6 9 8 7 4"
},
{
"code": null,
"e": 31664,
"s": 31617,
"text": "Time Complexity: O(N + M)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31682,
"s": 31664,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 31694,
"s": 31682,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31710,
"s": 31694,
"text": "dharanendralv23"
},
{
"code": null,
"e": 31721,
"s": 31710,
"text": "nidhi_biet"
},
{
"code": null,
"e": 31737,
"s": 31721,
"text": "souravmahato348"
},
{
"code": null,
"e": 31744,
"s": 31737,
"text": "spiral"
},
{
"code": null,
"e": 31751,
"s": 31744,
"text": "Matrix"
},
{
"code": null,
"e": 31770,
"s": 31751,
"text": "School Programming"
},
{
"code": null,
"e": 31777,
"s": 31770,
"text": "Matrix"
},
{
"code": null,
"e": 31875,
"s": 31777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31884,
"s": 31875,
"text": "Comments"
},
{
"code": null,
"e": 31897,
"s": 31884,
"text": "Old Comments"
},
{
"code": null,
"e": 31954,
"s": 31897,
"text": "Flood fill Algorithm - how to implement fill() in paint?"
},
{
"code": null,
"e": 31993,
"s": 31954,
"text": "Multiplication of Matrix using threads"
},
{
"code": null,
"e": 32057,
"s": 31993,
"text": "Program to find the Sum of each Row and each Column of a Matrix"
},
{
"code": null,
"e": 32121,
"s": 32057,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
},
{
"code": null,
"e": 32156,
"s": 32121,
"text": "Python program to add two Matrices"
},
{
"code": null,
"e": 32174,
"s": 32156,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32190,
"s": 32174,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32209,
"s": 32190,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 32234,
"s": 32209,
"text": "Reverse a string in Java"
}
] |
Getting a syntax error unknown fields in SAP ABAP
|
You need to add spaces after or before braces as follows −
SELECT *
FROM CNTRB
WHERE AGE > 30
AND CNTRB > 10000
AND NOT ( FUND1 = 'value' AND FUND2 = '0' )
|
[
{
"code": null,
"e": 1121,
"s": 1062,
"text": "You need to add spaces after or before braces as follows −"
},
{
"code": null,
"e": 1221,
"s": 1121,
"text": "SELECT *\nFROM CNTRB\nWHERE AGE > 30\nAND CNTRB > 10000\nAND NOT ( FUND1 = 'value' AND FUND2 = '0' )"
}
] |
Style input type submit with CSS
|
The input type button can be a submit button or reset button. With CSS, we can style any button on a web page.
You can try to run the following code to style input type submit:
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
input[type = submit] {
background-color: orange;
border: none;
text-decoration: none;
color: white;
padding: 20px 20px;
margin: 20px 20px;
cursor: pointer;
}
</style>
</head>
<body>
<p>Fill the below form,</p>
<form>
<label for = "subject">Subject</label>
<input type = "text" id="subject" name ="sub"><br><br>
<label for = "student">Student</label>
<input type = "text" id = "student" name = "stu"><br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "The input type button can be a submit button or reset button. With CSS, we can style any button on a web page."
},
{
"code": null,
"e": 1239,
"s": 1173,
"text": "You can try to run the following code to style input type submit:"
},
{
"code": null,
"e": 1249,
"s": 1239,
"text": "Live Demo"
},
{
"code": null,
"e": 1946,
"s": 1249,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n input[type = submit] {\n background-color: orange;\n border: none;\n text-decoration: none;\n color: white;\n padding: 20px 20px;\n margin: 20px 20px;\n cursor: pointer;\n }\n </style>\n </head>\n <body>\n <p>Fill the below form,</p>\n <form>\n <label for = \"subject\">Subject</label>\n <input type = \"text\" id=\"subject\" name =\"sub\"><br><br>\n <label for = \"student\">Student</label>\n <input type = \"text\" id = \"student\" name = \"stu\"><br>\n <input type = \"submit\" value = \"Submit\">\n </form>\n </body>\n</html>"
}
] |
How to hide status bar in Android using Kotlin?
|
This example demonstrates how to hide status bar in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
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" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello World!"
android:textColor="@android:color/holo_blue_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Window
import android.view.WindowManager
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN)
setContentView(R.layout.activity_main)
title = "KotlinApp"
}
}
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": 1136,
"s": 1062,
"text": "This example demonstrates how to hide status bar in Android using Kotlin."
},
{
"code": null,
"e": 1265,
"s": 1136,
"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": 1330,
"s": 1265,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2383,
"s": 1330,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\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 <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Hello World!\"\n android:textColor=\"@android:color/holo_blue_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2438,
"s": 2383,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2958,
"s": 2438,
"text": "import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.view.Window\nimport android.view.WindowManager\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n requestWindowFeature(Window.FEATURE_NO_TITLE)\n window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,\n WindowManager.LayoutParams.FLAG_FULLSCREEN)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n }\n}"
},
{
"code": null,
"e": 3013,
"s": 2958,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3687,
"s": 3013,
"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": 4036,
"s": 3687,
"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"
}
] |
ASP.NET Core - DBContext
|
The Entity Framework enables you to query, insert, update, and delete data, using Common Language Runtime (CLR) objects known as entities. The Entity Framework maps the entities and relationships that are defined in your model to a database. It also provides facilities to −
Materialize data returned from the database as entity objects.
Materialize data returned from the database as entity objects.
Track changes that were made to the objects.
Track changes that were made to the objects.
Handle concurrency.
Handle concurrency.
Propagate object changes back to the database.
Propagate object changes back to the database.
Bind objects to controls.
Bind objects to controls.
The primary class that is responsible for interacting with data as objects is the DbContext. The recommended way to work with context is to define a class that derives from the DbContext and exposes the DbSet properties that represent collections of the specified entities in the context.
Logically, a DBContext maps to a specific database that has a schema that the DBContext understands. And on that DBContext class, you can create properties that are type DbSet<T>. The generic type parameter T will be a type of entity like Employee is an entity in the FirstAppDemo application.
Let us take a simple example, wherein we will create a DbContext class. Here, we need to add a new class in Models folder and call it FirstAppDempDbContext. Even though this class is not a model in itself, it does put together all our Models so that we can use them with the database.
Inherit your context class from the DbContext class which is in Miscrosoft.Data.Entity namespace. Now implement a DbSet of Employee on that class.
Each DbSet will map to a table in the database. If you have a property DbSet of employee, and the name of that property is Employees, the Entity Framework will by default look for an Employees table inside your database.
using FirstAppDemo.Models;
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OdeToFood.Models {
public class FirstAppDemoDbContext : DbContext {
public DbSet<Employee> Employees { get; set; }
}
}
The implementation is very simple because we only have a single model to work with. We need only one property, the DbSet of Employee and we can name this property Employees.
Let us now insert this class directly into controllers, and the controllers could then use FirstAppDemoDbContext to query the database. We will simplify all these by adding a new class to the HomeController class in which we implement methods to Add employee and Get employee as shown in the following program.
using Microsoft.AspNet.Mvc;
using FirstAppDemo.ViewModels;
using FirstAppDemo.Services;
using FirstAppDemo.Entities;
using FirstAppDemo.Models;
using System.Collections.Generic;
using System.Linq;
namespace FirstAppDemo.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
var model = new HomePageViewModel();
using (var context = new FirstAppDemoDbContext()) {
SQLEmployeeData sqlData = new SQLEmployeeData(context);
model.Employees = sqlData.GetAll();
}
return View(model);
}
}
public class SQLEmployeeData {
private FirstAppDemoDbContext _context { get; set; }
public SQLEmployeeData(FirstAppDemoDbContext context) {
_context = context;
}
public void Add(Employee emp) {
_context.Add(emp);
_context.SaveChanges();
}
public Employee Get(int ID) {
return _context.Employees.FirstOrDefault(e => e.Id == ID);
}
public IEnumerable<Employee> GetAll() {
return _context.Employees.ToList<Employee>();
}
}
public class HomePageViewModel {
public IEnumerable<Employee> Employees { get; set; }
}
}
In the above SQLEmployeeData class, you can see that we have defined the Add method which will add a new employee object to the context and then it will save the changes. In the Get method, it will return an employee based on the ID. Whereas, in the GetAll method it will return the list of all the employees in the database.
To have a usable Entity Framework DBContext, we need to change the configuration of the application. We will need to add a connection string so that our DBContext knows which server to go to and which database to query.
We will put the connection string in a JSON configuration file.
We will put the connection string in a JSON configuration file.
We also need to add some more services during the ConfigureServices method of the Startup class.
We also need to add some more services during the ConfigureServices method of the Startup class.
The Entity Framework, just like ASP.NET and the MVC framework, the Entity Framework relies on dependency injection, and for injection to work, the runtime needs to know about the various services that the Entity Framework uses.
The Entity Framework, just like ASP.NET and the MVC framework, the Entity Framework relies on dependency injection, and for injection to work, the runtime needs to know about the various services that the Entity Framework uses.
There is an easy configuration API that will add all the default services that we need.
There is an easy configuration API that will add all the default services that we need.
Let us go to the AppSettings.json file and add the connections string as shown in the following program.
{
"message": "Hello, World! this message is from configuration file...",
"database": {
"connection": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=FirstAppDemo"
}
}
Let us now go to the Startup class where we need to add some additional services for the Entity Framework to work properly. Specifically, there are three things that we need to do that are related to the Entity Framework −
We need to add the core Entity Framework services.
We need to add the core Entity Framework services.
We also need to add the SQL Server-related Entity Framework services.
We also need to add the SQL Server-related Entity Framework services.
We need to tell the Entity Framework about our DBContext.
We need to tell the Entity Framework about our DBContext.
All this can be done through methods that are available as extension methods on IServiceCollection as shown in the following program.
public void ConfigureServices(IServiceCollection services) {
services.AddMvc();
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<FirstAppDemoDbContext>
(option => option.UseSqlServer(Configuration["database:connection"]));
}
The first method is the AddEntityFramework. This will add the core Entity Framework services, the default services.
The first method is the AddEntityFramework. This will add the core Entity Framework services, the default services.
But since the Entity Framework is now designed to work with different sorts of databases, including non-relational databases, we need to make a second call to tell the Entity Framework to add its default SQL Server-related services.
But since the Entity Framework is now designed to work with different sorts of databases, including non-relational databases, we need to make a second call to tell the Entity Framework to add its default SQL Server-related services.
Then we also need to tell the Entity Framework about my DBContext class so it can construct instances of that class appropriately and we can do that through a third method, the AddDbContext method.
Then we also need to tell the Entity Framework about my DBContext class so it can construct instances of that class appropriately and we can do that through a third method, the AddDbContext method.
This one takes a generic type parameter where we specify the type of the DBContext derived class, the FirstAppDemoDbContext.
This one takes a generic type parameter where we specify the type of the DBContext derived class, the FirstAppDemoDbContext.
Inside the AddDbContext, we need to describe the options for our DBContext.
Inside the AddDbContext, we need to describe the options for our DBContext.
This can be done by a lambda expression; it is an action where we receive an option parameter and the Entity Framework can support the different databases. All we need to do is, tell the Entity Framework that this particular DBContext is going to UseSqlServer.
This can be done by a lambda expression; it is an action where we receive an option parameter and the Entity Framework can support the different databases. All we need to do is, tell the Entity Framework that this particular DBContext is going to UseSqlServer.
This method requires a parameter which is the connectionString to use.
This method requires a parameter which is the connectionString to use.
The following is the complete implementation of the Startup.cs file.
using Microsoft.AspNet.Mvc;
using FirstAppDemo.ViewModels;
using FirstAppDemo.Services;
using FirstAppDemo.Entities;
using FirstAppDemo.Models;
using System.Collections.Generic;
using System.Linq;
namespace FirstAppDemo.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
var employee = new Employee { Id = 1, Name = "Mark Upston1" };
using (var context = new
FirstAppDemoDbContext()) {
SQLEmployeeData sqlData = new SQLEmployeeData(context);
sqlData.Add(employee);
}
//var employee = new Employee { ID = 1, Name = "Mark Upston" };
return View(employee);
}
}
public class SQLEmployeeData {
private FirstAppDemoDbContext _context { get; set; }
public SQLEmployeeData(FirstAppDemoDbContext context) {
_context = context;
}
public void Add(Employee emp) {
_context.Add(emp);
_context.SaveChanges();
}
public Employee Get(int ID) {
return _context.Employees.FirstOrDefault(e => e.Id == ID);
}
public IEnumerable<Employee> GetAll() {
return _context.Employees.ToList<Employee>();
}
}
}
Now we need to set up the database. One way to get a database set up is to use the Entity Framework to create the database and this is a two-step process −
This involves the following −
Adding migration code to our project.
Adding migration code to our project.
The migration code is C# code. This can be executed to create a database in a database schema.
The migration code is C# code. This can be executed to create a database in a database schema.
The Entity Framework can generate this migration code for us.
The Entity Framework can generate this migration code for us.
The Entity Framework looks at the database and at our models and figures out what the schema changes are required to make the application work.
The Entity Framework looks at the database and at our models and figures out what the schema changes are required to make the application work.
So when we add additional models or make changes to the existing models, like the Employee class, we can continue to add migrations to our project and keep our database schema in sync.
So when we add additional models or make changes to the existing models, like the Employee class, we can continue to add migrations to our project and keep our database schema in sync.
This involves the following −
Here, we need to explicitly apply those migrations to update a database.
Here, we need to explicitly apply those migrations to update a database.
Both of these tasks can be achieved by using some easy commands from a console window.
Both of these tasks can be achieved by using some easy commands from a console window.
We have made project.json.
We have made project.json.
That is why we have made project.json to add a command where “ef” maps to EntityFramework.Commands.
That is why we have made project.json to add a command where “ef” maps to EntityFramework.Commands.
Let us open the Developer Command Prompt for Visual Studio to run the commands that we need to add the migrations and apply the migrations. The easiest way to do this is to go to the application root directory.
If you are in the folder that has the project.json file, then you are in the correct folder. Here, we need to execute a command known as dnvm. This is the .NET version manager which will tell the system what runtime we want to use.
Let us now use the following command.
dnvm list
You will see the following output when you press Enter.
We need to tell the dnvm that we want to use the specific runtimes. This will give us access to the dotnet command or the dnx command that we want to execute.
Execute the following command.
dnvm use1.0.0-rc1-update1 -p
Press Enter.
dnvm will set up our path and the environment variables to include a bin directory that will give us access to this dnx utility. Let us execute the dnx ef command.
This is the .NET execution environment, using dnx, we can call the commands that we have listed in our project.json file. Executing these commands is generally very easy. When you type dnx ef, you will get a help screen. You don't have to remember all the options. You can see the available commands from the Entity Framework Commands and there are three of them.
First, we need to add migration to execute the following command.
dnx ef migrations add v1
Press Enter.
The Entity Framework will find that context and look at the models that are inside. It will know that there is no previous migration and so it is going to generate the first migration. Here, v1 is the version 1 of the database. It will create a new folder in Solution Explorer and generate code.
A migration is essentially a C# code that is used to generate SQL commands to modify the schema in a SQL database.
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
using Microsoft.Data.Entity.Metadata;
namespace FirstAppDemo.Migrations {
public partial class v1 : Migration {
protected override void Up(MigrationBuilder migrationBuilder) {
migrationBuilder.CreateTable(name: "Employee", columns: table => new {
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy",
SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(nullable: true)
},
constraints: table => {
table.PrimaryKey("PK_Employee", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder) {
migrationBuilder.DropTable("Employee");
}
}
}
You can see it will create a table called Employees.
This table should have two columns — an ID, and a Name column.
This table should have two columns — an ID, and a Name column.
By convention, when the Entity Framework sees that you have a property called Id, it will make that property or, rather, make that column a primary key in the database.
By convention, when the Entity Framework sees that you have a property called Id, it will make that property or, rather, make that column a primary key in the database.
Here, we will use the SQL Server. By default, the Entity Framework will make that an IdentityColumn, which means the SQL Server will generate the IDs for us.
Here, we will use the SQL Server. By default, the Entity Framework will make that an IdentityColumn, which means the SQL Server will generate the IDs for us.
Let us apply these IDs to a database by typing the “dnx ef database update” command.
You can see that the command has applied migration.
Let us now go to the SQL Server Object Explorer, and refresh the databases, you can now see we have a FirstAppDemo database.
You can also see our Employee table and we can even look at the columns for that table in which the ID column is the primary key.
Let us right-click on the dbo.Employee table and select View Data.
Before we run the application, let us add some data. When we launch the application, we should see some data from the database.
Let us just add a couple of rows of data here.
Let us now update the index.cshtml file. It shows all the data in tabular form.
@model FirstAppDemo.Controllers.HomePageViewModel
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome!</h1>
<table>
@foreach (var employee in Model.Employees) {
<tr>
<td>
@Html.ActionLink(employee.Id.ToString(), "Details", new
{ id = employee.Id })
</td>
<td>@employee.Name</td>
</tr>
}
</table>
</body>
</html>
Once you run the application, it should produce the following output.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2736,
"s": 2461,
"text": "The Entity Framework enables you to query, insert, update, and delete data, using Common Language Runtime (CLR) objects known as entities. The Entity Framework maps the entities and relationships that are defined in your model to a database. It also provides facilities to −"
},
{
"code": null,
"e": 2799,
"s": 2736,
"text": "Materialize data returned from the database as entity objects."
},
{
"code": null,
"e": 2862,
"s": 2799,
"text": "Materialize data returned from the database as entity objects."
},
{
"code": null,
"e": 2907,
"s": 2862,
"text": "Track changes that were made to the objects."
},
{
"code": null,
"e": 2952,
"s": 2907,
"text": "Track changes that were made to the objects."
},
{
"code": null,
"e": 2972,
"s": 2952,
"text": "Handle concurrency."
},
{
"code": null,
"e": 2992,
"s": 2972,
"text": "Handle concurrency."
},
{
"code": null,
"e": 3039,
"s": 2992,
"text": "Propagate object changes back to the database."
},
{
"code": null,
"e": 3086,
"s": 3039,
"text": "Propagate object changes back to the database."
},
{
"code": null,
"e": 3112,
"s": 3086,
"text": "Bind objects to controls."
},
{
"code": null,
"e": 3138,
"s": 3112,
"text": "Bind objects to controls."
},
{
"code": null,
"e": 3427,
"s": 3138,
"text": "The primary class that is responsible for interacting with data as objects is the DbContext. The recommended way to work with context is to define a class that derives from the DbContext and exposes the DbSet properties that represent collections of the specified entities in the context."
},
{
"code": null,
"e": 3721,
"s": 3427,
"text": "Logically, a DBContext maps to a specific database that has a schema that the DBContext understands. And on that DBContext class, you can create properties that are type DbSet<T>. The generic type parameter T will be a type of entity like Employee is an entity in the FirstAppDemo application."
},
{
"code": null,
"e": 4006,
"s": 3721,
"text": "Let us take a simple example, wherein we will create a DbContext class. Here, we need to add a new class in Models folder and call it FirstAppDempDbContext. Even though this class is not a model in itself, it does put together all our Models so that we can use them with the database."
},
{
"code": null,
"e": 4153,
"s": 4006,
"text": "Inherit your context class from the DbContext class which is in Miscrosoft.Data.Entity namespace. Now implement a DbSet of Employee on that class."
},
{
"code": null,
"e": 4374,
"s": 4153,
"text": "Each DbSet will map to a table in the database. If you have a property DbSet of employee, and the name of that property is Employees, the Entity Framework will by default look for an Employees table inside your database."
},
{
"code": null,
"e": 4682,
"s": 4374,
"text": "using FirstAppDemo.Models; \nusing Microsoft.Data.Entity; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nnamespace OdeToFood.Models { \n public class FirstAppDemoDbContext : DbContext { \n public DbSet<Employee> Employees { get; set; } \n } \n} "
},
{
"code": null,
"e": 4856,
"s": 4682,
"text": "The implementation is very simple because we only have a single model to work with. We need only one property, the DbSet of Employee and we can name this property Employees."
},
{
"code": null,
"e": 5167,
"s": 4856,
"text": "Let us now insert this class directly into controllers, and the controllers could then use FirstAppDemoDbContext to query the database. We will simplify all these by adding a new class to the HomeController class in which we implement methods to Add employee and Get employee as shown in the following program."
},
{
"code": null,
"e": 6442,
"s": 5167,
"text": "using Microsoft.AspNet.Mvc; \n\nusing FirstAppDemo.ViewModels; \nusing FirstAppDemo.Services; \nusing FirstAppDemo.Entities; \nusing FirstAppDemo.Models; \n\nusing System.Collections.Generic; \nusing System.Linq; \n\nnamespace FirstAppDemo.Controllers { \n public class HomeController : Controller { \n public ViewResult Index() { \n var model = new HomePageViewModel(); \n \n using (var context = new FirstAppDemoDbContext()) { \n SQLEmployeeData sqlData = new SQLEmployeeData(context); \n model.Employees = sqlData.GetAll(); \n } \n return View(model); \n } \n } \n public class SQLEmployeeData { \n private FirstAppDemoDbContext _context { get; set; } \n public SQLEmployeeData(FirstAppDemoDbContext context) { \n _context = context;\n } \n public void Add(Employee emp) { \n _context.Add(emp); \n _context.SaveChanges(); \n } \n public Employee Get(int ID) { \n return _context.Employees.FirstOrDefault(e => e.Id == ID); \n } \n public IEnumerable<Employee> GetAll() { \n return _context.Employees.ToList<Employee>(); \n } \n } \n public class HomePageViewModel { \n public IEnumerable<Employee> Employees { get; set; } \n } \n} "
},
{
"code": null,
"e": 6768,
"s": 6442,
"text": "In the above SQLEmployeeData class, you can see that we have defined the Add method which will add a new employee object to the context and then it will save the changes. In the Get method, it will return an employee based on the ID. Whereas, in the GetAll method it will return the list of all the employees in the database."
},
{
"code": null,
"e": 6988,
"s": 6768,
"text": "To have a usable Entity Framework DBContext, we need to change the configuration of the application. We will need to add a connection string so that our DBContext knows which server to go to and which database to query."
},
{
"code": null,
"e": 7052,
"s": 6988,
"text": "We will put the connection string in a JSON configuration file."
},
{
"code": null,
"e": 7116,
"s": 7052,
"text": "We will put the connection string in a JSON configuration file."
},
{
"code": null,
"e": 7213,
"s": 7116,
"text": "We also need to add some more services during the ConfigureServices method of the Startup class."
},
{
"code": null,
"e": 7310,
"s": 7213,
"text": "We also need to add some more services during the ConfigureServices method of the Startup class."
},
{
"code": null,
"e": 7538,
"s": 7310,
"text": "The Entity Framework, just like ASP.NET and the MVC framework, the Entity Framework relies on dependency injection, and for injection to work, the runtime needs to know about the various services that the Entity Framework uses."
},
{
"code": null,
"e": 7766,
"s": 7538,
"text": "The Entity Framework, just like ASP.NET and the MVC framework, the Entity Framework relies on dependency injection, and for injection to work, the runtime needs to know about the various services that the Entity Framework uses."
},
{
"code": null,
"e": 7854,
"s": 7766,
"text": "There is an easy configuration API that will add all the default services that we need."
},
{
"code": null,
"e": 7942,
"s": 7854,
"text": "There is an easy configuration API that will add all the default services that we need."
},
{
"code": null,
"e": 8047,
"s": 7942,
"text": "Let us go to the AppSettings.json file and add the connections string as shown in the following program."
},
{
"code": null,
"e": 8239,
"s": 8047,
"text": "{ \n \"message\": \"Hello, World! this message is from configuration file...\", \n \"database\": { \n \"connection\": \"Data Source=(localdb)\\\\mssqllocaldb;Initial Catalog=FirstAppDemo\" \n } \n}"
},
{
"code": null,
"e": 8462,
"s": 8239,
"text": "Let us now go to the Startup class where we need to add some additional services for the Entity Framework to work properly. Specifically, there are three things that we need to do that are related to the Entity Framework −"
},
{
"code": null,
"e": 8513,
"s": 8462,
"text": "We need to add the core Entity Framework services."
},
{
"code": null,
"e": 8564,
"s": 8513,
"text": "We need to add the core Entity Framework services."
},
{
"code": null,
"e": 8634,
"s": 8564,
"text": "We also need to add the SQL Server-related Entity Framework services."
},
{
"code": null,
"e": 8704,
"s": 8634,
"text": "We also need to add the SQL Server-related Entity Framework services."
},
{
"code": null,
"e": 8762,
"s": 8704,
"text": "We need to tell the Entity Framework about our DBContext."
},
{
"code": null,
"e": 8820,
"s": 8762,
"text": "We need to tell the Entity Framework about our DBContext."
},
{
"code": null,
"e": 8954,
"s": 8820,
"text": "All this can be done through methods that are available as extension methods on IServiceCollection as shown in the following program."
},
{
"code": null,
"e": 9221,
"s": 8954,
"text": "public void ConfigureServices(IServiceCollection services) { \n services.AddMvc(); \n services.AddEntityFramework() \n .AddSqlServer() \n .AddDbContext<FirstAppDemoDbContext>\n \n (option => option.UseSqlServer(Configuration[\"database:connection\"])); \n} "
},
{
"code": null,
"e": 9337,
"s": 9221,
"text": "The first method is the AddEntityFramework. This will add the core Entity Framework services, the default services."
},
{
"code": null,
"e": 9453,
"s": 9337,
"text": "The first method is the AddEntityFramework. This will add the core Entity Framework services, the default services."
},
{
"code": null,
"e": 9686,
"s": 9453,
"text": "But since the Entity Framework is now designed to work with different sorts of databases, including non-relational databases, we need to make a second call to tell the Entity Framework to add its default SQL Server-related services."
},
{
"code": null,
"e": 9919,
"s": 9686,
"text": "But since the Entity Framework is now designed to work with different sorts of databases, including non-relational databases, we need to make a second call to tell the Entity Framework to add its default SQL Server-related services."
},
{
"code": null,
"e": 10117,
"s": 9919,
"text": "Then we also need to tell the Entity Framework about my DBContext class so it can construct instances of that class appropriately and we can do that through a third method, the AddDbContext method."
},
{
"code": null,
"e": 10315,
"s": 10117,
"text": "Then we also need to tell the Entity Framework about my DBContext class so it can construct instances of that class appropriately and we can do that through a third method, the AddDbContext method."
},
{
"code": null,
"e": 10440,
"s": 10315,
"text": "This one takes a generic type parameter where we specify the type of the DBContext derived class, the FirstAppDemoDbContext."
},
{
"code": null,
"e": 10565,
"s": 10440,
"text": "This one takes a generic type parameter where we specify the type of the DBContext derived class, the FirstAppDemoDbContext."
},
{
"code": null,
"e": 10641,
"s": 10565,
"text": "Inside the AddDbContext, we need to describe the options for our DBContext."
},
{
"code": null,
"e": 10717,
"s": 10641,
"text": "Inside the AddDbContext, we need to describe the options for our DBContext."
},
{
"code": null,
"e": 10978,
"s": 10717,
"text": "This can be done by a lambda expression; it is an action where we receive an option parameter and the Entity Framework can support the different databases. All we need to do is, tell the Entity Framework that this particular DBContext is going to UseSqlServer."
},
{
"code": null,
"e": 11239,
"s": 10978,
"text": "This can be done by a lambda expression; it is an action where we receive an option parameter and the Entity Framework can support the different databases. All we need to do is, tell the Entity Framework that this particular DBContext is going to UseSqlServer."
},
{
"code": null,
"e": 11310,
"s": 11239,
"text": "This method requires a parameter which is the connectionString to use."
},
{
"code": null,
"e": 11381,
"s": 11310,
"text": "This method requires a parameter which is the connectionString to use."
},
{
"code": null,
"e": 11450,
"s": 11381,
"text": "The following is the complete implementation of the Startup.cs file."
},
{
"code": null,
"e": 12729,
"s": 11450,
"text": "using Microsoft.AspNet.Mvc; \n\nusing FirstAppDemo.ViewModels; \nusing FirstAppDemo.Services; \nusing FirstAppDemo.Entities; \nusing FirstAppDemo.Models; \n\nusing System.Collections.Generic; \nusing System.Linq; \n\nnamespace FirstAppDemo.Controllers { \n public class HomeController : Controller { \n public ViewResult Index() { \n var employee = new Employee { Id = 1, Name = \"Mark Upston1\" }; \n using (var context = new \n \n FirstAppDemoDbContext()) { \n SQLEmployeeData sqlData = new SQLEmployeeData(context); \n sqlData.Add(employee); \n } \n \n //var employee = new Employee { ID = 1, Name = \"Mark Upston\" }; \n return View(employee); \n } \n } \n public class SQLEmployeeData { \n private FirstAppDemoDbContext _context { get; set; } \n public SQLEmployeeData(FirstAppDemoDbContext context) { \n _context = context; \n } \n public void Add(Employee emp) { \n _context.Add(emp); \n _context.SaveChanges(); \n } \n public Employee Get(int ID) { \n return _context.Employees.FirstOrDefault(e => e.Id == ID); \n } \n public IEnumerable<Employee> GetAll() { \n return _context.Employees.ToList<Employee>(); \n } \n } \n} "
},
{
"code": null,
"e": 12885,
"s": 12729,
"text": "Now we need to set up the database. One way to get a database set up is to use the Entity Framework to create the database and this is a two-step process −"
},
{
"code": null,
"e": 12915,
"s": 12885,
"text": "This involves the following −"
},
{
"code": null,
"e": 12953,
"s": 12915,
"text": "Adding migration code to our project."
},
{
"code": null,
"e": 12991,
"s": 12953,
"text": "Adding migration code to our project."
},
{
"code": null,
"e": 13086,
"s": 12991,
"text": "The migration code is C# code. This can be executed to create a database in a database schema."
},
{
"code": null,
"e": 13181,
"s": 13086,
"text": "The migration code is C# code. This can be executed to create a database in a database schema."
},
{
"code": null,
"e": 13243,
"s": 13181,
"text": "The Entity Framework can generate this migration code for us."
},
{
"code": null,
"e": 13305,
"s": 13243,
"text": "The Entity Framework can generate this migration code for us."
},
{
"code": null,
"e": 13449,
"s": 13305,
"text": "The Entity Framework looks at the database and at our models and figures out what the schema changes are required to make the application work."
},
{
"code": null,
"e": 13593,
"s": 13449,
"text": "The Entity Framework looks at the database and at our models and figures out what the schema changes are required to make the application work."
},
{
"code": null,
"e": 13778,
"s": 13593,
"text": "So when we add additional models or make changes to the existing models, like the Employee class, we can continue to add migrations to our project and keep our database schema in sync."
},
{
"code": null,
"e": 13963,
"s": 13778,
"text": "So when we add additional models or make changes to the existing models, like the Employee class, we can continue to add migrations to our project and keep our database schema in sync."
},
{
"code": null,
"e": 13993,
"s": 13963,
"text": "This involves the following −"
},
{
"code": null,
"e": 14066,
"s": 13993,
"text": "Here, we need to explicitly apply those migrations to update a database."
},
{
"code": null,
"e": 14139,
"s": 14066,
"text": "Here, we need to explicitly apply those migrations to update a database."
},
{
"code": null,
"e": 14226,
"s": 14139,
"text": "Both of these tasks can be achieved by using some easy commands from a console window."
},
{
"code": null,
"e": 14313,
"s": 14226,
"text": "Both of these tasks can be achieved by using some easy commands from a console window."
},
{
"code": null,
"e": 14340,
"s": 14313,
"text": "We have made project.json."
},
{
"code": null,
"e": 14367,
"s": 14340,
"text": "We have made project.json."
},
{
"code": null,
"e": 14467,
"s": 14367,
"text": "That is why we have made project.json to add a command where “ef” maps to EntityFramework.Commands."
},
{
"code": null,
"e": 14567,
"s": 14467,
"text": "That is why we have made project.json to add a command where “ef” maps to EntityFramework.Commands."
},
{
"code": null,
"e": 14778,
"s": 14567,
"text": "Let us open the Developer Command Prompt for Visual Studio to run the commands that we need to add the migrations and apply the migrations. The easiest way to do this is to go to the application root directory."
},
{
"code": null,
"e": 15010,
"s": 14778,
"text": "If you are in the folder that has the project.json file, then you are in the correct folder. Here, we need to execute a command known as dnvm. This is the .NET version manager which will tell the system what runtime we want to use."
},
{
"code": null,
"e": 15048,
"s": 15010,
"text": "Let us now use the following command."
},
{
"code": null,
"e": 15060,
"s": 15048,
"text": "dnvm list \n"
},
{
"code": null,
"e": 15116,
"s": 15060,
"text": "You will see the following output when you press Enter."
},
{
"code": null,
"e": 15275,
"s": 15116,
"text": "We need to tell the dnvm that we want to use the specific runtimes. This will give us access to the dotnet command or the dnx command that we want to execute."
},
{
"code": null,
"e": 15306,
"s": 15275,
"text": "Execute the following command."
},
{
"code": null,
"e": 15336,
"s": 15306,
"text": "dnvm use1.0.0-rc1-update1 -p\n"
},
{
"code": null,
"e": 15349,
"s": 15336,
"text": "Press Enter."
},
{
"code": null,
"e": 15513,
"s": 15349,
"text": "dnvm will set up our path and the environment variables to include a bin directory that will give us access to this dnx utility. Let us execute the dnx ef command."
},
{
"code": null,
"e": 15877,
"s": 15513,
"text": "This is the .NET execution environment, using dnx, we can call the commands that we have listed in our project.json file. Executing these commands is generally very easy. When you type dnx ef, you will get a help screen. You don't have to remember all the options. You can see the available commands from the Entity Framework Commands and there are three of them."
},
{
"code": null,
"e": 15943,
"s": 15877,
"text": "First, we need to add migration to execute the following command."
},
{
"code": null,
"e": 15969,
"s": 15943,
"text": "dnx ef migrations add v1\n"
},
{
"code": null,
"e": 15982,
"s": 15969,
"text": "Press Enter."
},
{
"code": null,
"e": 16278,
"s": 15982,
"text": "The Entity Framework will find that context and look at the models that are inside. It will know that there is no previous migration and so it is going to generate the first migration. Here, v1 is the version 1 of the database. It will create a new folder in Solution Explorer and generate code."
},
{
"code": null,
"e": 16393,
"s": 16278,
"text": "A migration is essentially a C# code that is used to generate SQL commands to modify the schema in a SQL database."
},
{
"code": null,
"e": 17304,
"s": 16393,
"text": "using System; \nusing System.Collections.Generic; \n\nusing Microsoft.Data.Entity.Migrations; \nusing Microsoft.Data.Entity.Metadata; \n\nnamespace FirstAppDemo.Migrations { \n public partial class v1 : Migration { \n protected override void Up(MigrationBuilder migrationBuilder) { \n \n migrationBuilder.CreateTable(name: \"Employee\", columns: table => new { \n Id = table.Column<int>(nullable: false) \n .Annotation(\"SqlServer:ValueGenerationStrategy\",\n SqlServerValueGenerationStrategy.IdentityColumn), \n Name = table.Column<string>(nullable: true) \n }, \n constraints: table => { \n table.PrimaryKey(\"PK_Employee\", x => x.Id); \n }); \n } \n protected override void Down(MigrationBuilder migrationBuilder) { \n migrationBuilder.DropTable(\"Employee\"); \n } \n } \n}"
},
{
"code": null,
"e": 17357,
"s": 17304,
"text": "You can see it will create a table called Employees."
},
{
"code": null,
"e": 17420,
"s": 17357,
"text": "This table should have two columns — an ID, and a Name column."
},
{
"code": null,
"e": 17483,
"s": 17420,
"text": "This table should have two columns — an ID, and a Name column."
},
{
"code": null,
"e": 17652,
"s": 17483,
"text": "By convention, when the Entity Framework sees that you have a property called Id, it will make that property or, rather, make that column a primary key in the database."
},
{
"code": null,
"e": 17821,
"s": 17652,
"text": "By convention, when the Entity Framework sees that you have a property called Id, it will make that property or, rather, make that column a primary key in the database."
},
{
"code": null,
"e": 17979,
"s": 17821,
"text": "Here, we will use the SQL Server. By default, the Entity Framework will make that an IdentityColumn, which means the SQL Server will generate the IDs for us."
},
{
"code": null,
"e": 18137,
"s": 17979,
"text": "Here, we will use the SQL Server. By default, the Entity Framework will make that an IdentityColumn, which means the SQL Server will generate the IDs for us."
},
{
"code": null,
"e": 18222,
"s": 18137,
"text": "Let us apply these IDs to a database by typing the “dnx ef database update” command."
},
{
"code": null,
"e": 18274,
"s": 18222,
"text": "You can see that the command has applied migration."
},
{
"code": null,
"e": 18399,
"s": 18274,
"text": "Let us now go to the SQL Server Object Explorer, and refresh the databases, you can now see we have a FirstAppDemo database."
},
{
"code": null,
"e": 18529,
"s": 18399,
"text": "You can also see our Employee table and we can even look at the columns for that table in which the ID column is the primary key."
},
{
"code": null,
"e": 18596,
"s": 18529,
"text": "Let us right-click on the dbo.Employee table and select View Data."
},
{
"code": null,
"e": 18724,
"s": 18596,
"text": "Before we run the application, let us add some data. When we launch the application, we should see some data from the database."
},
{
"code": null,
"e": 18771,
"s": 18724,
"text": "Let us just add a couple of rows of data here."
},
{
"code": null,
"e": 18851,
"s": 18771,
"text": "Let us now update the index.cshtml file. It shows all the data in tabular form."
},
{
"code": null,
"e": 19401,
"s": 18851,
"text": "@model FirstAppDemo.Controllers.HomePageViewModel \n<html xmlns=\"http://www.w3.org/1999/xhtml\"> \n <head> \n <title>Home</title> \n </head> \n\n <body> \n <h1>Welcome!</h1> \n \n <table> \n @foreach (var employee in Model.Employees) { \n <tr> \n <td> \n @Html.ActionLink(employee.Id.ToString(), \"Details\", new \n { id = employee.Id }) \n </td> \n <td>@employee.Name</td> \n </tr> \n } \n </table> \n </body> \n</html>"
},
{
"code": null,
"e": 19471,
"s": 19401,
"text": "Once you run the application, it should produce the following output."
},
{
"code": null,
"e": 19506,
"s": 19471,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 19520,
"s": 19506,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 19555,
"s": 19520,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 19578,
"s": 19555,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 19612,
"s": 19578,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 19632,
"s": 19612,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 19667,
"s": 19632,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 19684,
"s": 19667,
"text": " University Code"
},
{
"code": null,
"e": 19719,
"s": 19684,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 19736,
"s": 19719,
"text": " University Code"
},
{
"code": null,
"e": 19770,
"s": 19736,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 19785,
"s": 19770,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 19792,
"s": 19785,
"text": " Print"
},
{
"code": null,
"e": 19803,
"s": 19792,
"text": " Add Notes"
}
] |
MongoDB Interview Questions
|
Dear readers, these MongoDB Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of MongoDB. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:
A NoSQL database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases (like SQL, Oracle, etc.).
Types of NoSQL databases:
Document Oriented
Key Value
Graph
Column Oriented
MongoDB is a document oriented database. It stores data in the form of BSON structure based documents. These documents are stored in a collection.
Flexible data model in form of documents
Agile and highly scalable database
Faster than traditional databases
Expressive query language
A Namespace is the concatenation of the database name and collection name.
For e.g. school.students with school as the database and students as the collection
Currently, MonggoDB provides official driver support for C, C++, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go and Erlang. MongoDB can easily be used with any of these languages. There are some other community supported drivers too but the above mentioned ones are officially provided by MongoDB.
SQL databases store data in form of tables, rows, columns and records. This data is stored in a pre-defined data model which is not very much flexible for today's real-world highly growing applications. MongoDB in contrast uses a flexible structure which can be easily modified and extended.
MongoDB allows a highly flexible and scalable document structure. For e.g. one data document in MongoDB can have five columns and the other one in the same collection can have ten columns. Also, MongoDB database are faster as compared to SQL databases due to efficient indexing and storage techniques.
Although both of these databases are document oriented, MongoDB is a better choice for applications which need dynamic queries and good performance on a very big database. On the other side, CouchDB is better used for applications with occasionally changing queries and pre-defined queries.
No. MongoDB does not support such relationships.
No. MongoDB does not support default multi-document ACID transactions. However, MongoDB provides atomic operation on a single document.
By default MongoDB does not support such primary key - foreign key relationships. However, we can achieve this concept by embedding one document inside another. Foe e.g. an address document can be embedded inside customer document.
No. MongoDB can be run even on a small amount of RAM. MongoDB dynamically allocates and de-allocates RAM based on the requirements of other processes.
MongoDB pushes the data to disk lazily. It updates the immediately written to the journal but writing the data from journal to disk happens lazily.
ObjectID is a 12-byte BSON type with:
4 bytes value representing seconds
3 byte machine identifier
2 byte process id
3 byte counter
True
Yes. Removing a document from database removes it from disk too.
use school;
db.persons.insert( { name: "kadhir", dept: "CSE" } )
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.
By default, MongoDB created the _id collection for every collection.
Yes. An array field can be indexed in MongoDB. In this case, MongoDB would index each value of the array.
A covered query is the one in which:
fields used in the query are part of an index used in the query, and
the fields returned in the results are in the same index
Since all the fields are covered in the index itself, MongoDB can match the query condition as well as return the result fields using the same index without looking inside the documents. Since indexes are stored in RAM or sequentially located on disk, such access is a lot faster.
Yes. MongoDB supports creating text indexes to support text search inside string content. This was a new feature which can introduced in version 2.6.
If the indexes do not fit into RAM, MongoDB reads data from disk which is relatively very much slower than reading from RAM.
db.collection.getIndexes()
By default configuration, MongoDB writes updates to the disk every 60 seconds. However, this is configurable with the commitIntervalMs and syncPeriodSecs options.
To achieve concepts of transaction and locking in MongoDB, we can use the nesting of documents, also called embedded documents. MongoDB supports atomic operations within a single document.
Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. MongoDB provides three ways to perform aggregation: the aggregation pipeline, the map-reduce function, and single purpose aggregation methods and commands.
Sharding is a method for storing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations.
Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability. With multiple copies of data on different database servers, replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions.
Primary and master nodes are the nodes that can accept writes. MongoDB's replication is 'single-master:' only one node can accept write operations at a time.
Secondary and slave nodes are read-only nodes that replicate from the primary.
False. MongoDB writes data only to the primary replica set.
MongoDB preallocates data files to reserve space and avoid file system fragmentation when you setup the server.
You should consider embedding documents for:
'contains' relationships between entities
One-to-many relationships
Performance reasons
When running a 32-bit build of MongoDB, the total storage size for the server, including data and indexes, is 2 gigabytes. For this reason, do not deploy MongoDB to production on 32-bit machines.
If you're running a 64-bit build of MongoDB, there's virtually no limit to storage size.
A storage engine is the part of a database that is responsible for managing how data is stored on disk. For example, one storage engine might offer better performance for read-heavy workloads, and another might support a higher-throughput for write operations.
MongoDB uses MMAPv1 and WiredTiger.
The database profiler collects fine grained data about MongoDB write operations, cursors, database commands on a running mongod instance. You can enable profiling on a per-database or per-instance basis.
The database profiler writes all the data it collects to the system.profile collection, which is a capped collection.
When running with journaling, MongoDB stores and applies write operations in memory and in the on-disk journal before the changes are present in the data files on disk. Writes to the journal are atomic, ensuring the consistency of the on-disk journal files. With journaling enabled, MongoDB creates a journal subdirectory within the directory defined by dbPath, which is /data/db by default.
db.isMaster()
No. MMAPv1 does not allow configuring the cache size.
For the WiredTiger storage engine, you can specify the maximum size of the cache that WiredTiger will use for all data. This can be done using storage.wiredTiger.engineConfig.cacheSizeGB option.
MongoDB uses reader-writer locks that allow concurrent readers shared access to a resource, such as a database or collection, but give exclusive access to a single write operation.
You can use the snapshot() method on a cursor to isolate the operation for a very specific case.
snapshot() traverses the index on the _id field and guarantees that the query will return each document no more than once.
Yes. Operations like copyDatabase(), repairDatabase(), etc. can lock more than onne databases involved.
In replication, when MongoDB writes to a collection on the primary, MongoDB also writes to the primary's oplog, which is a special collection in the local database. Therefore, MongoDB must lock both the collection's database and the local database.
GridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16MB. Instead of storing a file in a single document, GridFS divides a file into parts, or chunks, and stores each of those chunks as a separate document.
Yes. The V8 JavaScript engine added in 2.4 allows multiple JavaScript operations to run at the same time.
The explain() command can be used for this information. The possible modes are: 'queryPlanner', 'executionStats', and 'allPlansExecution'.
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
44 Lectures
3 hours
Arnab Chakraborty
54 Lectures
5.5 hours
Eduonix Learning Solutions
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
40 Lectures
2.5 hours
University Code
26 Lectures
8 hours
Bassir Jafarzadeh
70 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2991,
"s": 2553,
"text": "Dear readers, these MongoDB Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of MongoDB. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:"
},
{
"code": null,
"e": 3176,
"s": 2991,
"text": "A NoSQL database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases (like SQL, Oracle, etc.)."
},
{
"code": null,
"e": 3204,
"s": 3176,
"text": "\nTypes of NoSQL databases:\n"
},
{
"code": null,
"e": 3222,
"s": 3204,
"text": "Document Oriented"
},
{
"code": null,
"e": 3233,
"s": 3222,
"text": "Key Value "
},
{
"code": null,
"e": 3240,
"s": 3233,
"text": "Graph "
},
{
"code": null,
"e": 3256,
"s": 3240,
"text": "Column Oriented"
},
{
"code": null,
"e": 3403,
"s": 3256,
"text": "MongoDB is a document oriented database. It stores data in the form of BSON structure based documents. These documents are stored in a collection."
},
{
"code": null,
"e": 3447,
"s": 3405,
"text": "Flexible data model in form of documents "
},
{
"code": null,
"e": 3483,
"s": 3447,
"text": "Agile and highly scalable database "
},
{
"code": null,
"e": 3518,
"s": 3483,
"text": "Faster than traditional databases "
},
{
"code": null,
"e": 3546,
"s": 3518,
"text": "Expressive query language "
},
{
"code": null,
"e": 3706,
"s": 3546,
"text": "A Namespace is the concatenation of the database name and collection name.\nFor e.g. school.students with school as the database and students as the collection\n"
},
{
"code": null,
"e": 4011,
"s": 3706,
"text": "Currently, MonggoDB provides official driver support for C, C++, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go and Erlang. MongoDB can easily be used with any of these languages. There are some other community supported drivers too but the above mentioned ones are officially provided by MongoDB."
},
{
"code": null,
"e": 4304,
"s": 4011,
"text": "SQL databases store data in form of tables, rows, columns and records. This data is stored in a pre-defined data model which is not very much flexible for today's real-world highly growing applications. MongoDB in contrast uses a flexible structure which can be easily modified and extended. "
},
{
"code": null,
"e": 4606,
"s": 4304,
"text": "MongoDB allows a highly flexible and scalable document structure. For e.g. one data document in MongoDB can have five columns and the other one in the same collection can have ten columns. Also, MongoDB database are faster as compared to SQL databases due to efficient indexing and storage techniques."
},
{
"code": null,
"e": 4898,
"s": 4606,
"text": "Although both of these databases are document oriented, MongoDB is a better choice for applications which need dynamic queries and good performance on a very big database. On the other side, CouchDB is better used for applications with occasionally changing queries and pre-defined queries. "
},
{
"code": null,
"e": 4947,
"s": 4898,
"text": "No. MongoDB does not support such relationships."
},
{
"code": null,
"e": 5083,
"s": 4947,
"text": "No. MongoDB does not support default multi-document ACID transactions. However, MongoDB provides atomic operation on a single document."
},
{
"code": null,
"e": 5315,
"s": 5083,
"text": "By default MongoDB does not support such primary key - foreign key relationships. However, we can achieve this concept by embedding one document inside another. Foe e.g. an address document can be embedded inside customer document."
},
{
"code": null,
"e": 5466,
"s": 5315,
"text": "No. MongoDB can be run even on a small amount of RAM. MongoDB dynamically allocates and de-allocates RAM based on the requirements of other processes."
},
{
"code": null,
"e": 5614,
"s": 5466,
"text": "MongoDB pushes the data to disk lazily. It updates the immediately written to the journal but writing the data from journal to disk happens lazily."
},
{
"code": null,
"e": 5654,
"s": 5614,
"text": "\nObjectID is a 12-byte BSON type with:\n"
},
{
"code": null,
"e": 5690,
"s": 5654,
"text": "4 bytes value representing seconds "
},
{
"code": null,
"e": 5716,
"s": 5690,
"text": "3 byte machine identifier"
},
{
"code": null,
"e": 5735,
"s": 5716,
"text": "2 byte process id "
},
{
"code": null,
"e": 5750,
"s": 5735,
"text": "3 byte counter"
},
{
"code": null,
"e": 5755,
"s": 5750,
"text": "True"
},
{
"code": null,
"e": 5820,
"s": 5755,
"text": "Yes. Removing a document from database removes it from disk too."
},
{
"code": null,
"e": 5885,
"s": 5820,
"text": "use school;\ndb.persons.insert( { name: \"kadhir\", dept: \"CSE\" } )"
},
{
"code": null,
"e": 6225,
"s": 5885,
"text": "Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect."
},
{
"code": null,
"e": 6295,
"s": 6225,
"text": "By default, MongoDB created the _id collection for every collection. "
},
{
"code": null,
"e": 6402,
"s": 6295,
"text": "Yes. An array field can be indexed in MongoDB. In this case, MongoDB would index each value of the array. "
},
{
"code": null,
"e": 6445,
"s": 6402,
"text": "\nA covered query is the one in which: \n"
},
{
"code": null,
"e": 6516,
"s": 6445,
"text": " fields used in the query are part of an index used in the query, and "
},
{
"code": null,
"e": 6575,
"s": 6516,
"text": " the fields returned in the results are in the same index "
},
{
"code": null,
"e": 6856,
"s": 6575,
"text": "Since all the fields are covered in the index itself, MongoDB can match the query condition as well as return the result fields using the same index without looking inside the documents. Since indexes are stored in RAM or sequentially located on disk, such access is a lot faster."
},
{
"code": null,
"e": 7007,
"s": 6856,
"text": "Yes. MongoDB supports creating text indexes to support text search inside string content. This was a new feature which can introduced in version 2.6. "
},
{
"code": null,
"e": 7132,
"s": 7007,
"text": "If the indexes do not fit into RAM, MongoDB reads data from disk which is relatively very much slower than reading from RAM."
},
{
"code": null,
"e": 7159,
"s": 7132,
"text": "db.collection.getIndexes()"
},
{
"code": null,
"e": 7322,
"s": 7159,
"text": "By default configuration, MongoDB writes updates to the disk every 60 seconds. However, this is configurable with the commitIntervalMs and syncPeriodSecs options."
},
{
"code": null,
"e": 7514,
"s": 7322,
"text": "\nTo achieve concepts of transaction and locking in MongoDB, we can use the nesting of documents, also called embedded documents. MongoDB supports atomic operations within a single document. \n"
},
{
"code": null,
"e": 7901,
"s": 7514,
"text": "Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. MongoDB provides three ways to perform aggregation: the aggregation pipeline, the map-reduce function, and single purpose aggregation methods and commands."
},
{
"code": null,
"e": 8068,
"s": 7901,
"text": "Sharding is a method for storing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations."
},
{
"code": null,
"e": 8421,
"s": 8068,
"text": "Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability. With multiple copies of data on different database servers, replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions."
},
{
"code": null,
"e": 8579,
"s": 8421,
"text": "Primary and master nodes are the nodes that can accept writes. MongoDB's replication is 'single-master:' only one node can accept write operations at a time."
},
{
"code": null,
"e": 8658,
"s": 8579,
"text": "Secondary and slave nodes are read-only nodes that replicate from the primary."
},
{
"code": null,
"e": 8718,
"s": 8658,
"text": "False. MongoDB writes data only to the primary replica set."
},
{
"code": null,
"e": 8831,
"s": 8718,
"text": "MongoDB preallocates data files to reserve space and avoid file system fragmentation when you setup the server. "
},
{
"code": null,
"e": 8878,
"s": 8831,
"text": "\nYou should consider embedding documents for:\n"
},
{
"code": null,
"e": 8920,
"s": 8878,
"text": "'contains' relationships between entities"
},
{
"code": null,
"e": 8947,
"s": 8920,
"text": "One-to-many relationships "
},
{
"code": null,
"e": 8967,
"s": 8947,
"text": "Performance reasons"
},
{
"code": null,
"e": 9165,
"s": 8967,
"text": "\nWhen running a 32-bit build of MongoDB, the total storage size for the server, including data and indexes, is 2 gigabytes. For this reason, do not deploy MongoDB to production on 32-bit machines.\n"
},
{
"code": null,
"e": 9256,
"s": 9165,
"text": "\nIf you're running a 64-bit build of MongoDB, there's virtually no limit to storage size.\n"
},
{
"code": null,
"e": 9517,
"s": 9256,
"text": "A storage engine is the part of a database that is responsible for managing how data is stored on disk. For example, one storage engine might offer better performance for read-heavy workloads, and another might support a higher-throughput for write operations."
},
{
"code": null,
"e": 9553,
"s": 9517,
"text": "MongoDB uses MMAPv1 and WiredTiger."
},
{
"code": null,
"e": 9759,
"s": 9553,
"text": "\nThe database profiler collects fine grained data about MongoDB write operations, cursors, database commands on a running mongod instance. You can enable profiling on a per-database or per-instance basis.\n"
},
{
"code": null,
"e": 9879,
"s": 9759,
"text": "\nThe database profiler writes all the data it collects to the system.profile collection, which is a capped collection.\n"
},
{
"code": null,
"e": 10271,
"s": 9879,
"text": "When running with journaling, MongoDB stores and applies write operations in memory and in the on-disk journal before the changes are present in the data files on disk. Writes to the journal are atomic, ensuring the consistency of the on-disk journal files. With journaling enabled, MongoDB creates a journal subdirectory within the directory defined by dbPath, which is /data/db by default."
},
{
"code": null,
"e": 10285,
"s": 10271,
"text": "db.isMaster()"
},
{
"code": null,
"e": 10339,
"s": 10285,
"text": "No. MMAPv1 does not allow configuring the cache size."
},
{
"code": null,
"e": 10534,
"s": 10339,
"text": "For the WiredTiger storage engine, you can specify the maximum size of the cache that WiredTiger will use for all data. This can be done using storage.wiredTiger.engineConfig.cacheSizeGB option."
},
{
"code": null,
"e": 10715,
"s": 10534,
"text": "MongoDB uses reader-writer locks that allow concurrent readers shared access to a resource, such as a database or collection, but give exclusive access to a single write operation."
},
{
"code": null,
"e": 10936,
"s": 10715,
"text": "You can use the snapshot() method on a cursor to isolate the operation for a very specific case.\nsnapshot() traverses the index on the _id field and guarantees that the query will return each document no more than once.\n"
},
{
"code": null,
"e": 11040,
"s": 10936,
"text": "Yes. Operations like copyDatabase(), repairDatabase(), etc. can lock more than onne databases involved."
},
{
"code": null,
"e": 11289,
"s": 11040,
"text": "In replication, when MongoDB writes to a collection on the primary, MongoDB also writes to the primary's oplog, which is a special collection in the local database. Therefore, MongoDB must lock both the collection's database and the local database."
},
{
"code": null,
"e": 11547,
"s": 11289,
"text": "GridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16MB. Instead of storing a file in a single document, GridFS divides a file into parts, or chunks, and stores each of those chunks as a separate document."
},
{
"code": null,
"e": 11653,
"s": 11547,
"text": "Yes. The V8 JavaScript engine added in 2.4 allows multiple JavaScript operations to run at the same time."
},
{
"code": null,
"e": 11792,
"s": 11653,
"text": "The explain() command can be used for this information. The possible modes are: 'queryPlanner', 'executionStats', and 'allPlansExecution'."
},
{
"code": null,
"e": 12079,
"s": 11792,
"text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong."
},
{
"code": null,
"e": 12409,
"s": 12079,
"text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)"
},
{
"code": null,
"e": 12442,
"s": 12409,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 12461,
"s": 12442,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 12496,
"s": 12461,
"text": "\n 54 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 12524,
"s": 12496,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12559,
"s": 12524,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12582,
"s": 12559,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 12617,
"s": 12582,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12634,
"s": 12617,
"text": " University Code"
},
{
"code": null,
"e": 12667,
"s": 12634,
"text": "\n 26 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 12686,
"s": 12667,
"text": " Bassir Jafarzadeh"
},
{
"code": null,
"e": 12721,
"s": 12686,
"text": "\n 70 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12741,
"s": 12721,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 12748,
"s": 12741,
"text": " Print"
},
{
"code": null,
"e": 12759,
"s": 12748,
"text": " Add Notes"
}
] |
Moore - Penrose Pseudoinverse | Mathematics - GeeksforGeeks
|
03 Oct, 2019
In linear algebra pseudoinverse () of a matrix A is a generalization of the inverse matrix. The most common use of pseudoinverse is to compute the best fit solution to a system of linear equations which lacks a unique solution. Moore – Penrose inverse is the most widely known type of matrix pseudoinverse. The term generalized inverse is sometimes used as a synonym of pseudoinverse.
Let the system is given as:
We know A and , and we want to find .Where: and are vectors,A is a matrix
If A is a square matrix, we proceed as below:
But if A is not a square matrix, we cannot compute the usual . Nevertheless, we can form the pseudoinverse.
If we go in detail at the system i.e. , then it represents the following set of equations:
. .. .. .
which can also be written in matrix form as below:
Where m > n which means the number of rows is greater than the number of columns or the number of rows is greater than the number of variables.
Solution to the above problem:There are multiple ways to solve the above problem. One solution involves Moore – Penrose Pseudoinverse. We write the Moore – Penrose pseudoinverse as .We have but unless A has the usual inverse.So, to solve the problem we proceed as follow:
This is how simply we solve the linear equations using the Moore – Penrose pseudoinverse. The derivation for Moore – Penrose pseudoinverse is beyond the scope of this article. You can go through this link in case you want to know more about it. Here, it is simply presented the method for computing it. The Moore – Penrose pseudoinverse is computed as
Example:
Consider below 3 linear equations:
Equivalently we can write above equations in matrix form as shown below:
After we compute the Moore - Penrose pseudoinverse using , we will get:
Check the matrix product you will get identity matrix I.
We have,
Then,
After you compute above computation, you will get the final answer as
Note: Moore – Penrose pseudoinverse solves the problem in least squared error sense. In general, there is no exact solution to overdetermined problems. So if you cross check the solution you will not get the exact required y but an approx value of y.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Intuition of Adam Optimizer
ML | Logistic Regression using Python
CNN | Introduction to Pooling Layer
Principal Component Analysis with Python
Python | Decision Tree Regression using sklearn
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
|
[
{
"code": null,
"e": 24368,
"s": 24340,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 24753,
"s": 24368,
"text": "In linear algebra pseudoinverse () of a matrix A is a generalization of the inverse matrix. The most common use of pseudoinverse is to compute the best fit solution to a system of linear equations which lacks a unique solution. Moore – Penrose inverse is the most widely known type of matrix pseudoinverse. The term generalized inverse is sometimes used as a synonym of pseudoinverse."
},
{
"code": null,
"e": 24781,
"s": 24753,
"text": "Let the system is given as:"
},
{
"code": null,
"e": 24856,
"s": 24781,
"text": "We know A and , and we want to find .Where: and are vectors,A is a matrix"
},
{
"code": null,
"e": 24902,
"s": 24856,
"text": "If A is a square matrix, we proceed as below:"
},
{
"code": null,
"e": 25010,
"s": 24902,
"text": "But if A is not a square matrix, we cannot compute the usual . Nevertheless, we can form the pseudoinverse."
},
{
"code": null,
"e": 25101,
"s": 25010,
"text": "If we go in detail at the system i.e. , then it represents the following set of equations:"
},
{
"code": null,
"e": 25111,
"s": 25101,
"text": ". .. .. ."
},
{
"code": null,
"e": 25162,
"s": 25111,
"text": "which can also be written in matrix form as below:"
},
{
"code": null,
"e": 25306,
"s": 25162,
"text": "Where m > n which means the number of rows is greater than the number of columns or the number of rows is greater than the number of variables."
},
{
"code": null,
"e": 25580,
"s": 25306,
"text": "Solution to the above problem:There are multiple ways to solve the above problem. One solution involves Moore – Penrose Pseudoinverse. We write the Moore – Penrose pseudoinverse as .We have but unless A has the usual inverse.So, to solve the problem we proceed as follow:"
},
{
"code": null,
"e": 25932,
"s": 25580,
"text": "This is how simply we solve the linear equations using the Moore – Penrose pseudoinverse. The derivation for Moore – Penrose pseudoinverse is beyond the scope of this article. You can go through this link in case you want to know more about it. Here, it is simply presented the method for computing it. The Moore – Penrose pseudoinverse is computed as"
},
{
"code": null,
"e": 25941,
"s": 25932,
"text": "Example:"
},
{
"code": null,
"e": 26289,
"s": 25941,
"text": "Consider below 3 linear equations:\n\n\n\n\n\n\nEquivalently we can write above equations in matrix form as shown below:\n\n\n\n\n\nAfter we compute the Moore - Penrose pseudoinverse using , we will get:\n\n\n\nCheck the matrix product you will get identity matrix I.\n\n\nWe have,\n\n\nThen,\n\n\n\n\n\nAfter you compute above computation, you will get the final answer as\n\n"
},
{
"code": null,
"e": 26540,
"s": 26289,
"text": "Note: Moore – Penrose pseudoinverse solves the problem in least squared error sense. In general, there is no exact solution to overdetermined problems. So if you cross check the solution you will not get the exact required y but an approx value of y."
},
{
"code": null,
"e": 26557,
"s": 26540,
"text": "Machine Learning"
},
{
"code": null,
"e": 26574,
"s": 26557,
"text": "Machine Learning"
},
{
"code": null,
"e": 26672,
"s": 26574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26705,
"s": 26672,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 26744,
"s": 26705,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 26779,
"s": 26744,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 26807,
"s": 26779,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 26845,
"s": 26807,
"text": "ML | Logistic Regression using Python"
},
{
"code": null,
"e": 26881,
"s": 26845,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 26922,
"s": 26881,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 26970,
"s": 26922,
"text": "Python | Decision Tree Regression using sklearn"
},
{
"code": null,
"e": 27021,
"s": 26970,
"text": "DBSCAN Clustering in ML | Density based clustering"
}
] |
Transfer learning using pytorch — Part 1 | by Vishnu Subramanian | Towards Data Science
|
Ever wondered why ML models have to learn every time from scratch . What if the models can use knowledge learnt from recognising cats, dogs ,fish ,cars , bus and many more to identify a distracted car driver or to identify plant disease .In transfer learning we use a pre trained neural network in extracting features and training a new model for a particular use case. Not sure what it is.. just wait till the end of the blog.
There are many frameworks like Keras , Tensoflow , Theano ,Torch, Deeplearning.4J , etc which can be used for deep learning . Out all these my favourite is Keras on top of Tensorflow. Keras works great for a lot of mature architectures like CNN, feed forward neural network , Lstm for time series but it becomes bit tricky when you try to implement new architectures which are complex in nature. Since Keras was built in a nice modular fashion it lacks flexibility . Pytorch which is a new entrant ,provides us tools to build various deep learning models in object oriented fashion thus providing a lot of flexibility . A lot of the difficult architectures are being implemented in PyTorch recently. So I started exploring PyTorch and in this blog we will go through how easy it is to build a state of art of classifier with a very small dataset and in a few lines of code.
We will build a classifier for detecting ants and bees using the following steps.
Download the dataset from here.
Download the dataset from here.
2. Data augmentation.
3. Downloading pre trained resnet model (Transfer learning).
4. Training the model on the dataset .
5. How to decay the learning rate for every nth epoch.
Download the dataset from the above link . It contains 224 images in the training dataset and 153 images in the validation dataset.
Data augmentation is a process where you make changes to existing photos like adjusting the colors , flipping it horizontally or vertically , scaling , cropping and many more. Pytorch provides a very useful library called torchvision.transforms which provides a lot of methods which helps to apply data augmentation. transforms comes with a compose method which takes a list of transformation.
data_transforms = { 'train': transforms.Compose([ transforms.RandomSizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]),}
We will use a model called ResNet from Microsoft which won the ImageNet competition in 2015. It showed how deep networks can be made possible. Lets not get into the complexity of the ResNet. We will download the model and most of the modern deep learning frameworks makes loading a model easier. The ResNet model compromises of a bunch of ResNet blocks(Combination of convolution and identity block) and a fully connected layer. The model is trained on Imagenet dataset on 1000 categories , we will remove the last fully connected layer and add a new fully connected layer which outputs 2 categories which tells the probability of the image being Ant or Bee.
model_conv = torchvision.models.resnet18(pretrained=True)for param in model_conv.parameters(): ----> 1 param.requires_grad = False# Parameters of newly constructed modules have requires_grad=True by defaultnum_ftrs = model_conv.fc.in_featuresmodel_conv.fc = nn.Linear(num_ftrs, 2) ----> 2if use_gpu: model_conv = model_conv.cuda() ----> 3
We tell the model not to learn or modify the weights / parameters of the model.Then we add a new fully connected layer to the existing model to train our model to classify 2 categories.If you have a gpu .cuda() executes the model in GPU.
We tell the model not to learn or modify the weights / parameters of the model.
Then we add a new fully connected layer to the existing model to train our model to classify 2 categories.
If you have a gpu .cuda() executes the model in GPU.
Our model is ready and we need to pass the data to train.
For training model we need a couple of more things apart from the model like:
PyTorch Variable : A variable wraps pytorch tensor .It contains data and the gradient associated with the data.Loss Function : It helps in calculating how good is our model. We will be using categorical cross entropy here.Optimizer : We will use SGD to optimise our weights with the gradients. In our case we update the weights of only the last layer.Forward propagation : This is the simplest part where we pass our data through the model.Backward propagation : This is the key for modern deep learning networks where all the magic happens. Where the optimizer starts calculating how much the weights need to be updated in order to reduce the loss or improve the accuracy. In most modern frameworks this is automated , so we can focus on building cool applications backed by deep learning.
PyTorch Variable : A variable wraps pytorch tensor .It contains data and the gradient associated with the data.
Loss Function : It helps in calculating how good is our model. We will be using categorical cross entropy here.
Optimizer : We will use SGD to optimise our weights with the gradients. In our case we update the weights of only the last layer.
Forward propagation : This is the simplest part where we pass our data through the model.
Backward propagation : This is the key for modern deep learning networks where all the magic happens. Where the optimizer starts calculating how much the weights need to be updated in order to reduce the loss or improve the accuracy. In most modern frameworks this is automated , so we can focus on building cool applications backed by deep learning.
if use_gpu: inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda()) --> 1else: inputs, labels = Variable(inputs), Variable(labels)criterion = nn.CrossEntropyLoss() --> 2# Observe that all parameters are being optimizedoptimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9) -->3# zero the parameter gradientsoptimizer.zero_grad()# forward outputs = model(inputs) --> 4loss = criterion(outputs, labels)# backward + optimize only if in training phaseif phase == 'train': --> 5 loss.backward() optimizer.step()
Most of the times we start with a higher learning rate so that we can reduce the loss faster and then after a few epochs you would like to reduce it so that the learning becoming slower. I found this function from pytorch tutorials very useful.
def lr_scheduler(optimizer, epoch, init_lr=0.001, lr_decay_epoch=7): """Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr * (0.1**(epoch // lr_decay_epoch)) if epoch % lr_decay_epoch == 0: print('LR is set to {}'.format(lr)) for param_group in optimizer.param_groups: param_group['lr'] = lr return optimizer
We are reducing the learning rate for every nth epoch , in the above example 7 with 0.1 . decay_rate is configurable. Even on a smaller dataset we can achieve state of art results using this approach.
Wanted to try transfer learning on your dataset using pytorch , the code resides here.
Interested in learning Deep learning do not forget to checkout the amazing MOOC Deep learning for coders by Jeremy Howard .
In the next part we will discuss different tricks how to make transfer learning much faster using VGG . And compare how it performs in PyTorch and Tensorflow.
|
[
{
"code": null,
"e": 600,
"s": 172,
"text": "Ever wondered why ML models have to learn every time from scratch . What if the models can use knowledge learnt from recognising cats, dogs ,fish ,cars , bus and many more to identify a distracted car driver or to identify plant disease .In transfer learning we use a pre trained neural network in extracting features and training a new model for a particular use case. Not sure what it is.. just wait till the end of the blog."
},
{
"code": null,
"e": 1474,
"s": 600,
"text": "There are many frameworks like Keras , Tensoflow , Theano ,Torch, Deeplearning.4J , etc which can be used for deep learning . Out all these my favourite is Keras on top of Tensorflow. Keras works great for a lot of mature architectures like CNN, feed forward neural network , Lstm for time series but it becomes bit tricky when you try to implement new architectures which are complex in nature. Since Keras was built in a nice modular fashion it lacks flexibility . Pytorch which is a new entrant ,provides us tools to build various deep learning models in object oriented fashion thus providing a lot of flexibility . A lot of the difficult architectures are being implemented in PyTorch recently. So I started exploring PyTorch and in this blog we will go through how easy it is to build a state of art of classifier with a very small dataset and in a few lines of code."
},
{
"code": null,
"e": 1556,
"s": 1474,
"text": "We will build a classifier for detecting ants and bees using the following steps."
},
{
"code": null,
"e": 1588,
"s": 1556,
"text": "Download the dataset from here."
},
{
"code": null,
"e": 1620,
"s": 1588,
"text": "Download the dataset from here."
},
{
"code": null,
"e": 1642,
"s": 1620,
"text": "2. Data augmentation."
},
{
"code": null,
"e": 1703,
"s": 1642,
"text": "3. Downloading pre trained resnet model (Transfer learning)."
},
{
"code": null,
"e": 1742,
"s": 1703,
"text": "4. Training the model on the dataset ."
},
{
"code": null,
"e": 1797,
"s": 1742,
"text": "5. How to decay the learning rate for every nth epoch."
},
{
"code": null,
"e": 1929,
"s": 1797,
"text": "Download the dataset from the above link . It contains 224 images in the training dataset and 153 images in the validation dataset."
},
{
"code": null,
"e": 2323,
"s": 1929,
"text": "Data augmentation is a process where you make changes to existing photos like adjusting the colors , flipping it horizontally or vertically , scaling , cropping and many more. Pytorch provides a very useful library called torchvision.transforms which provides a lot of methods which helps to apply data augmentation. transforms comes with a compose method which takes a list of transformation."
},
{
"code": null,
"e": 2777,
"s": 2323,
"text": "data_transforms = { 'train': transforms.Compose([ transforms.RandomSizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]),}"
},
{
"code": null,
"e": 3436,
"s": 2777,
"text": "We will use a model called ResNet from Microsoft which won the ImageNet competition in 2015. It showed how deep networks can be made possible. Lets not get into the complexity of the ResNet. We will download the model and most of the modern deep learning frameworks makes loading a model easier. The ResNet model compromises of a bunch of ResNet blocks(Combination of convolution and identity block) and a fully connected layer. The model is trained on Imagenet dataset on 1000 categories , we will remove the last fully connected layer and add a new fully connected layer which outputs 2 categories which tells the probability of the image being Ant or Bee."
},
{
"code": null,
"e": 3792,
"s": 3436,
"text": "model_conv = torchvision.models.resnet18(pretrained=True)for param in model_conv.parameters(): ----> 1 param.requires_grad = False# Parameters of newly constructed modules have requires_grad=True by defaultnum_ftrs = model_conv.fc.in_featuresmodel_conv.fc = nn.Linear(num_ftrs, 2) ----> 2if use_gpu: model_conv = model_conv.cuda() ----> 3"
},
{
"code": null,
"e": 4030,
"s": 3792,
"text": "We tell the model not to learn or modify the weights / parameters of the model.Then we add a new fully connected layer to the existing model to train our model to classify 2 categories.If you have a gpu .cuda() executes the model in GPU."
},
{
"code": null,
"e": 4110,
"s": 4030,
"text": "We tell the model not to learn or modify the weights / parameters of the model."
},
{
"code": null,
"e": 4217,
"s": 4110,
"text": "Then we add a new fully connected layer to the existing model to train our model to classify 2 categories."
},
{
"code": null,
"e": 4270,
"s": 4217,
"text": "If you have a gpu .cuda() executes the model in GPU."
},
{
"code": null,
"e": 4328,
"s": 4270,
"text": "Our model is ready and we need to pass the data to train."
},
{
"code": null,
"e": 4406,
"s": 4328,
"text": "For training model we need a couple of more things apart from the model like:"
},
{
"code": null,
"e": 5197,
"s": 4406,
"text": "PyTorch Variable : A variable wraps pytorch tensor .It contains data and the gradient associated with the data.Loss Function : It helps in calculating how good is our model. We will be using categorical cross entropy here.Optimizer : We will use SGD to optimise our weights with the gradients. In our case we update the weights of only the last layer.Forward propagation : This is the simplest part where we pass our data through the model.Backward propagation : This is the key for modern deep learning networks where all the magic happens. Where the optimizer starts calculating how much the weights need to be updated in order to reduce the loss or improve the accuracy. In most modern frameworks this is automated , so we can focus on building cool applications backed by deep learning."
},
{
"code": null,
"e": 5309,
"s": 5197,
"text": "PyTorch Variable : A variable wraps pytorch tensor .It contains data and the gradient associated with the data."
},
{
"code": null,
"e": 5421,
"s": 5309,
"text": "Loss Function : It helps in calculating how good is our model. We will be using categorical cross entropy here."
},
{
"code": null,
"e": 5551,
"s": 5421,
"text": "Optimizer : We will use SGD to optimise our weights with the gradients. In our case we update the weights of only the last layer."
},
{
"code": null,
"e": 5641,
"s": 5551,
"text": "Forward propagation : This is the simplest part where we pass our data through the model."
},
{
"code": null,
"e": 5992,
"s": 5641,
"text": "Backward propagation : This is the key for modern deep learning networks where all the magic happens. Where the optimizer starts calculating how much the weights need to be updated in order to reduce the loss or improve the accuracy. In most modern frameworks this is automated , so we can focus on building cool applications backed by deep learning."
},
{
"code": null,
"e": 6538,
"s": 5992,
"text": "if use_gpu: inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda()) --> 1else: inputs, labels = Variable(inputs), Variable(labels)criterion = nn.CrossEntropyLoss() --> 2# Observe that all parameters are being optimizedoptimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9) -->3# zero the parameter gradientsoptimizer.zero_grad()# forward outputs = model(inputs) --> 4loss = criterion(outputs, labels)# backward + optimize only if in training phaseif phase == 'train': --> 5 loss.backward() optimizer.step()"
},
{
"code": null,
"e": 6783,
"s": 6538,
"text": "Most of the times we start with a higher learning rate so that we can reduce the loss faster and then after a few epochs you would like to reduce it so that the learning becoming slower. I found this function from pytorch tutorials very useful."
},
{
"code": null,
"e": 7154,
"s": 6783,
"text": "def lr_scheduler(optimizer, epoch, init_lr=0.001, lr_decay_epoch=7): \"\"\"Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.\"\"\" lr = init_lr * (0.1**(epoch // lr_decay_epoch)) if epoch % lr_decay_epoch == 0: print('LR is set to {}'.format(lr)) for param_group in optimizer.param_groups: param_group['lr'] = lr return optimizer"
},
{
"code": null,
"e": 7355,
"s": 7154,
"text": "We are reducing the learning rate for every nth epoch , in the above example 7 with 0.1 . decay_rate is configurable. Even on a smaller dataset we can achieve state of art results using this approach."
},
{
"code": null,
"e": 7442,
"s": 7355,
"text": "Wanted to try transfer learning on your dataset using pytorch , the code resides here."
},
{
"code": null,
"e": 7566,
"s": 7442,
"text": "Interested in learning Deep learning do not forget to checkout the amazing MOOC Deep learning for coders by Jeremy Howard ."
}
] |
Python String min() Method
|
Python string method min() returns the min alphabetical character from the string str.
Following is the syntax for min() method −
min(str)
str − This is the string from which min alphabetical character needs to be returned.
str − This is the string from which min alphabetical character needs to be returned.
This method returns the min alphabetical character from the string str.
The following example shows the usage of min() method.
#!/usr/bin/python
str = "this-is-real-string-example....wow!!!";
print "Min character: " + min(str)
str = "this-is-a-string-example....wow!!!";
print "Min character: " + min(str)
When we run above program, it produces following result −
Min character: !
Min character: !
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": 2332,
"s": 2244,
"text": "Python string method min() returns the min alphabetical character from the string str."
},
{
"code": null,
"e": 2375,
"s": 2332,
"text": "Following is the syntax for min() method −"
},
{
"code": null,
"e": 2385,
"s": 2375,
"text": "min(str)\n"
},
{
"code": null,
"e": 2470,
"s": 2385,
"text": "str − This is the string from which min alphabetical character needs to be returned."
},
{
"code": null,
"e": 2555,
"s": 2470,
"text": "str − This is the string from which min alphabetical character needs to be returned."
},
{
"code": null,
"e": 2627,
"s": 2555,
"text": "This method returns the min alphabetical character from the string str."
},
{
"code": null,
"e": 2682,
"s": 2627,
"text": "The following example shows the usage of min() method."
},
{
"code": null,
"e": 2863,
"s": 2682,
"text": "#!/usr/bin/python\n\nstr = \"this-is-real-string-example....wow!!!\";\nprint \"Min character: \" + min(str)\n\nstr = \"this-is-a-string-example....wow!!!\";\nprint \"Min character: \" + min(str)"
},
{
"code": null,
"e": 2921,
"s": 2863,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2956,
"s": 2921,
"text": "Min character: !\nMin character: !\n"
},
{
"code": null,
"e": 2993,
"s": 2956,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3009,
"s": 2993,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3042,
"s": 3009,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3061,
"s": 3042,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3096,
"s": 3061,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3118,
"s": 3096,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3152,
"s": 3118,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3180,
"s": 3152,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3215,
"s": 3180,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3229,
"s": 3215,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3262,
"s": 3229,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3279,
"s": 3262,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3286,
"s": 3279,
"text": " Print"
},
{
"code": null,
"e": 3297,
"s": 3286,
"text": " Add Notes"
}
] |
Find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n - GeeksforGeeks
|
07 Apr, 2021
You are given a function f(n) = (n1 + n2 + n3 + n4), you have to find the value of f(n) mod 5 for any given value of positive integer n. Note: n may be large enough, such that f(n) > 1018. Examples :
Input : n = 4
Output : 0
Explanation : f(4) = 4 + 16 + 64 + 256 = 330,
f(4) mod 5 = 330 mod 5 = 0.
Input : n = 1
Output : 4
Explanation : f(1) = 1 + 1 + 1 + 1 = 4,
f(1) mod 5 = 4.
First of all for solving this approach you may find the value of (n1 + n2 + n3 + n4) mod 5 directly with the help of anypower function and modulo operator. But For the larger value of n, your result will be wrong because for large n value of f(n) may go out of range from long long int in that case you have to opt some other efficient way. To solve this question lets do some small mathematical derivation for f(n).
f(n) = (n1 + n2 + n3 + n4)
= (n) (n+1) (n2+1)
Now, for finding f(n) mod 5 we must take care of unit digit of f(n) only,
also as f(n) mod 5 is dependent on n%5, (n+1)%5 & (n2+1)%5,
if any of these three result in zero then our whole result is 0.
So, if n = 5, 10, .. 5k then n mod 5 = 0 hence f(n) mod 5 = 0.
if n = 4, 9, .., (5k-1) then (n+1) mod 5 = 0 hence f(n) mod 5 = 0.
if n = 3, 8, 13..., (5k-2) f(n) mod 5 = (3 * 4 * 10) mod 5 = 0
if n = 2, 7, 12..., (5k-3) f(n) mod 5 = (2 * 3 * 5) mod 5 = 0.
if n = 1, 6, 11..., (5k-4) f(n) mod 5 = (1 * 2 * 2) mod 5 = 4.
After above analysis we can see that if n is of form 5k+1 or say 5k-4 then f(n) mod 5 = 4, other wise f(n) = 0. I.E. if(n%5 == 1 ) result = 4, else result = 0.
C++
Java
Python3
C#
PHP
Javascript
// finding the value of f(n) mod 5 for given n.#include <bits/stdc++.h>using namespace std; // function for f(n) mod 5int fnMod(int n){ // if n % 5 == 1 return 4 if (n % 5 == 1) return 4; // else return 0 else return 0;} // driver programint main(){ int n = 10; cout << fnMod(n) << endl; n = 11; cout << fnMod(n) << endl; return 0;}
// Java code to finding the value// of f(n) mod 5 for given n.import java.io.*; class GFG{ // function for f(n) mod 5 static int fnMod(int n) { // if n % 5 == 1 return 4 if (n % 5 == 1) return 4; // else return 0 else return 0; } // Driver program public static void main (String[] args) { int n = 10; System.out.println(fnMod(n)); n = 11; System.out.println(fnMod(n)); }} // This code is contributed by vt_m.
# Python3 program to find the value# of f(n) mod 5 for given n. # Function for f(n) mod 5def fnMod(n): # if n % 5 == 1 return 4 if (n % 5 == 1): return 4 # else return 0 else: return 0 # Driver Coden = 10print(fnMod(n)) n = 11print(fnMod(n)) # This code is contributed by Smitha Dinesh Semwal
// Code for finding the value// of f(n) mod 5 for given n.using System; class GFG { // function for f(n) mod 5 static int fnMod(int n) { // if n % 5 == 1 return 4 if (n % 5 == 1) return 4; // else return 0 else return 0; } // Driver program public static void Main() { int n = 10; Console.WriteLine(fnMod(n)); n = 11; Console.WriteLine(fnMod(n)); }} // This code is contributed by vt_m.
<?php// PHP program for finding the// value of f(n) mod 5 for given n. // function for f(n) mod 5function fnMod($n){ // if n % 5 == 1 return 4 if ($n % 5 == 1) return 4; // else return 0 else return 0;} // Driver Code$n = 10;echo fnMod($n),"\n";$n = 11;echo fnMod($n) ; // This code is contributed by anuj_67.?>
<script>// JavaScript program to finding the value// of f(n) mod 5 for given n. // function for f(n) mod 5 function fnMod(n) { // if n % 5 == 1 return 4 if (n % 5 == 1) return 4; // else return 0 else return 0; } // Driver Code let n = 10; document.write(fnMod(n) + "<br/>"); n = 11; document.write(fnMod(n) + "<br/>"); // This code is contributed by chinmoy1997pal. </script>
Output :
0
4
vt_m
chinmoy1997pal
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
Program for Decimal to Binary Conversion
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
|
[
{
"code": null,
"e": 25214,
"s": 25186,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 25416,
"s": 25214,
"text": "You are given a function f(n) = (n1 + n2 + n3 + n4), you have to find the value of f(n) mod 5 for any given value of positive integer n. Note: n may be large enough, such that f(n) > 1018. Examples : "
},
{
"code": null,
"e": 25600,
"s": 25416,
"text": "Input : n = 4\nOutput : 0\nExplanation : f(4) = 4 + 16 + 64 + 256 = 330, \nf(4) mod 5 = 330 mod 5 = 0.\n\nInput : n = 1 \nOutput : 4\nExplanation : f(1) = 1 + 1 + 1 + 1 = 4, \nf(1) mod 5 = 4."
},
{
"code": null,
"e": 26021,
"s": 25602,
"text": "First of all for solving this approach you may find the value of (n1 + n2 + n3 + n4) mod 5 directly with the help of anypower function and modulo operator. But For the larger value of n, your result will be wrong because for large n value of f(n) may go out of range from long long int in that case you have to opt some other efficient way. To solve this question lets do some small mathematical derivation for f(n). "
},
{
"code": null,
"e": 26590,
"s": 26021,
"text": "f(n) = (n1 + n2 + n3 + n4)\n = (n) (n+1) (n2+1)\nNow, for finding f(n) mod 5 we must take care of unit digit of f(n) only,\nalso as f(n) mod 5 is dependent on n%5, (n+1)%5 & (n2+1)%5,\nif any of these three result in zero then our whole result is 0.\nSo, if n = 5, 10, .. 5k then n mod 5 = 0 hence f(n) mod 5 = 0.\nif n = 4, 9, .., (5k-1) then (n+1) mod 5 = 0 hence f(n) mod 5 = 0.\nif n = 3, 8, 13..., (5k-2) f(n) mod 5 = (3 * 4 * 10) mod 5 = 0\nif n = 2, 7, 12..., (5k-3) f(n) mod 5 = (2 * 3 * 5) mod 5 = 0.\nif n = 1, 6, 11..., (5k-4) f(n) mod 5 = (1 * 2 * 2) mod 5 = 4."
},
{
"code": null,
"e": 26751,
"s": 26590,
"text": "After above analysis we can see that if n is of form 5k+1 or say 5k-4 then f(n) mod 5 = 4, other wise f(n) = 0. I.E. if(n%5 == 1 ) result = 4, else result = 0. "
},
{
"code": null,
"e": 26755,
"s": 26751,
"text": "C++"
},
{
"code": null,
"e": 26760,
"s": 26755,
"text": "Java"
},
{
"code": null,
"e": 26768,
"s": 26760,
"text": "Python3"
},
{
"code": null,
"e": 26771,
"s": 26768,
"text": "C#"
},
{
"code": null,
"e": 26775,
"s": 26771,
"text": "PHP"
},
{
"code": null,
"e": 26786,
"s": 26775,
"text": "Javascript"
},
{
"code": "// finding the value of f(n) mod 5 for given n.#include <bits/stdc++.h>using namespace std; // function for f(n) mod 5int fnMod(int n){ // if n % 5 == 1 return 4 if (n % 5 == 1) return 4; // else return 0 else return 0;} // driver programint main(){ int n = 10; cout << fnMod(n) << endl; n = 11; cout << fnMod(n) << endl; return 0;}",
"e": 27161,
"s": 26786,
"text": null
},
{
"code": "// Java code to finding the value// of f(n) mod 5 for given n.import java.io.*; class GFG{ // function for f(n) mod 5 static int fnMod(int n) { // if n % 5 == 1 return 4 if (n % 5 == 1) return 4; // else return 0 else return 0; } // Driver program public static void main (String[] args) { int n = 10; System.out.println(fnMod(n)); n = 11; System.out.println(fnMod(n)); }} // This code is contributed by vt_m.",
"e": 27684,
"s": 27161,
"text": null
},
{
"code": "# Python3 program to find the value# of f(n) mod 5 for given n. # Function for f(n) mod 5def fnMod(n): # if n % 5 == 1 return 4 if (n % 5 == 1): return 4 # else return 0 else: return 0 # Driver Coden = 10print(fnMod(n)) n = 11print(fnMod(n)) # This code is contributed by Smitha Dinesh Semwal",
"e": 28005,
"s": 27684,
"text": null
},
{
"code": "// Code for finding the value// of f(n) mod 5 for given n.using System; class GFG { // function for f(n) mod 5 static int fnMod(int n) { // if n % 5 == 1 return 4 if (n % 5 == 1) return 4; // else return 0 else return 0; } // Driver program public static void Main() { int n = 10; Console.WriteLine(fnMod(n)); n = 11; Console.WriteLine(fnMod(n)); }} // This code is contributed by vt_m.",
"e": 28496,
"s": 28005,
"text": null
},
{
"code": "<?php// PHP program for finding the// value of f(n) mod 5 for given n. // function for f(n) mod 5function fnMod($n){ // if n % 5 == 1 return 4 if ($n % 5 == 1) return 4; // else return 0 else return 0;} // Driver Code$n = 10;echo fnMod($n),\"\\n\";$n = 11;echo fnMod($n) ; // This code is contributed by anuj_67.?>",
"e": 28835,
"s": 28496,
"text": null
},
{
"code": "<script>// JavaScript program to finding the value// of f(n) mod 5 for given n. // function for f(n) mod 5 function fnMod(n) { // if n % 5 == 1 return 4 if (n % 5 == 1) return 4; // else return 0 else return 0; } // Driver Code let n = 10; document.write(fnMod(n) + \"<br/>\"); n = 11; document.write(fnMod(n) + \"<br/>\"); // This code is contributed by chinmoy1997pal. </script>",
"e": 29340,
"s": 28835,
"text": null
},
{
"code": null,
"e": 29351,
"s": 29340,
"text": "Output : "
},
{
"code": null,
"e": 29355,
"s": 29351,
"text": "0\n4"
},
{
"code": null,
"e": 29362,
"s": 29357,
"text": "vt_m"
},
{
"code": null,
"e": 29377,
"s": 29362,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 29396,
"s": 29377,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 29409,
"s": 29396,
"text": "Mathematical"
},
{
"code": null,
"e": 29422,
"s": 29409,
"text": "Mathematical"
},
{
"code": null,
"e": 29441,
"s": 29422,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 29539,
"s": 29441,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29548,
"s": 29539,
"text": "Comments"
},
{
"code": null,
"e": 29561,
"s": 29548,
"text": "Old Comments"
},
{
"code": null,
"e": 29604,
"s": 29561,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 29628,
"s": 29604,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 29642,
"s": 29628,
"text": "Prime Numbers"
},
{
"code": null,
"e": 29691,
"s": 29642,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 29725,
"s": 29691,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 29746,
"s": 29725,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 29788,
"s": 29746,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 29829,
"s": 29788,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 29861,
"s": 29829,
"text": "Algorithm to solve Rubik's Cube"
}
] |
Spice Up Your Python Visualizations with Matplotlib Animations | by Tony Yiu | Towards Data Science
|
If you are interested in my code, you can find it here on my GitHub. The code throws an error (that I could not get rid of for the life of me) the first time you run it. But if you just execute the same cell again, it will run fine.
This post is not an obviously data science post but it does have data science and business intelligence applications. Python’s Matplotlib is the go to library for plotting and visualizing data. We are all familiar with line plots, bar plots, and heat maps. But did you know you can also make simple animations using Matplotlib?
Below is an example of an animation created in Matplotlib. It shows John Conway’s The Game of Life — a coding challenge from Metis that gave me an excuse to create my first Python animation. Check out the gif of the finished result:
If you are interested in how I coded up The Game of Life, please refer to my code (and comments) on my GitHub. This blog will primarily focus on how to add animations in python using Matplotlib.
But for those of you that are unfamiliar with the simulation (it’s more a simulation that you watch rather than a game that you play), here are the rules:
We start with a N by N sized board (50 by 50 in my animations).
We populate a random number of cells on our board with organisms (I started the simulation by randomly filling 1,500 of the 2,500 cells on the board with an organism).
Each occupied cell with one or fewer neighbors dies.
Each occupied cell with four or more neighbors dies.
Each occupied cell with two or three neighbors survives.
Each empty cell with exactly three neighbors develops a new organism.
We start by importing the libraries we need.
import timefrom IPython import displayimport matplotlib.pyplot as pltimport matplotlib.animation as animation
We will take advantage of the FuncAnimation() function from matplotlib’s animation module. FuncAnimation() animates an image by calling a function repeatedly, updating the image on each call. We will walk through this process step by step.
But first, we need to initialize our board. The following few lines of code collect our inputs:
We want a 50 by 50 sized board.
The pad variable makes it easier to calculate neighbors. By padding the edges with extra cells that are always empty, we make it so that we don’t need to write extra logic to handle the edges of the board. So our 50 by 50 board is surrounded by a border of empty cells, making the actual numpy array have a size of 52 by 52.
The initial_cells variable is how many organisms we want to start the board off with. They will be placed randomly on the board.
# Input variables for the boardboardsize = 50 # board will be X by X where X = boardsizepad = 2 # padded border, do not change this!initial_cells = 1500 # this number of initial cells will be placed # in randomly generated positions
Next we randomly generate a bunch of coordinates (we chose 1,500 above) where our initial organisms will live. These coordinates are stored in the variable pos_list.
# Get a list of random coordinates so that we can initialize # board with randomly placed organismspos_list = []for i in range(initial_cells): pos_list.append([random.randint(1, boardsize), random.randint(1, boardsize)])
Then it’s time to instantiate the board. We will use a numpy array named my_board to represent our board — we start off with a 52 by 52 array of zeros (it is bigger than 50 by 50 because of the padding) and then call the function init_board() to fill it with organisms according to the coordinates in pos_list. I won’t go into detail on the helper functions here, but they are documented on my GitHub.
# Initialize the boardmy_board = np.zeros((boardsize+pad, boardsize+pad))my_board = init_board(pos_list, my_board)
The part that we’ve been waiting for — animation! First, we need to get some formalities out of the way. The following lines of code create the matplotlib figure that will display our animation.
# Required line for plotting the animation%matplotlib notebook# Initialize the plot of the board that will be used for animationfig = plt.gcf()
Time to make our first frame. The function imshow() from matplotlib takes in a numpy matrix and renders it as an image. Pretty cool!
# Show first image - which is the initial boardim = plt.imshow(my_board)plt.show()
The variable we pass imshow() is our initial board, which is stored in my_board. The image created looks like this:
Now we need to make a helper function that FuncAnimation() can call. The function animate() takes in frame, which is just a counter. The frame counter is how FuncAnimation() communicates with the animate() function — for each step in time (a.k.a. frame), it will call animate() once. And animate() will in turn use the helper function update_board() to iterate the board by one turn. Finally, the function set_data() updates our image with the iterated board and we are good to go.
# Helper function that updates the board and returns a new image of# the updated board animate is the function that FuncAnimation callsdef animate(frame): im.set_data(update_board(my_board)) return im,
Hurray! We are ready to call FuncAnimation(). Notice the inputs:
fig is the plot variable we created earlier to house our animation.
animate is our function that FuncAnimation() communicates with using the frame counter (it is automatically passed and doesn’t need to be explicitly specified).
frames is how many frames we want the animation to last for, in this case we want our animation to be 200 frames long.
interval is the delay between frames in milliseconds. So we want 50 milliseconds between frames here.
# This line creates the animationanim = animation.FuncAnimation(fig, animate, frames=200, interval=50)
And that’s it! Not too bad right? To celebrate our successful animation, here is another gif:
I hope you find this useful. Before I go, let me help brainstorm some more data science-like applications of the animation functionality we learned today:
Drawing out Monte Carlo simulations one by one so you can observe how the outcome distribution is gradually formed.
Walking forward through time series data in order to depict how your model or data reacts as new observations arrive.
Highlighting how the clusters identified by your algorithm shift as you change the inputs such as number of clusters.
Correlation heatmaps over time or across different subsamples of your data to visualize how different samples might affect your model’s estimated parameters.
Cheers!
More from me:
Thoughts on data science.
The random forest algorithm.
How neural networks work.
Logistic regression explained.
|
[
{
"code": null,
"e": 405,
"s": 172,
"text": "If you are interested in my code, you can find it here on my GitHub. The code throws an error (that I could not get rid of for the life of me) the first time you run it. But if you just execute the same cell again, it will run fine."
},
{
"code": null,
"e": 733,
"s": 405,
"text": "This post is not an obviously data science post but it does have data science and business intelligence applications. Python’s Matplotlib is the go to library for plotting and visualizing data. We are all familiar with line plots, bar plots, and heat maps. But did you know you can also make simple animations using Matplotlib?"
},
{
"code": null,
"e": 966,
"s": 733,
"text": "Below is an example of an animation created in Matplotlib. It shows John Conway’s The Game of Life — a coding challenge from Metis that gave me an excuse to create my first Python animation. Check out the gif of the finished result:"
},
{
"code": null,
"e": 1161,
"s": 966,
"text": "If you are interested in how I coded up The Game of Life, please refer to my code (and comments) on my GitHub. This blog will primarily focus on how to add animations in python using Matplotlib."
},
{
"code": null,
"e": 1316,
"s": 1161,
"text": "But for those of you that are unfamiliar with the simulation (it’s more a simulation that you watch rather than a game that you play), here are the rules:"
},
{
"code": null,
"e": 1380,
"s": 1316,
"text": "We start with a N by N sized board (50 by 50 in my animations)."
},
{
"code": null,
"e": 1548,
"s": 1380,
"text": "We populate a random number of cells on our board with organisms (I started the simulation by randomly filling 1,500 of the 2,500 cells on the board with an organism)."
},
{
"code": null,
"e": 1601,
"s": 1548,
"text": "Each occupied cell with one or fewer neighbors dies."
},
{
"code": null,
"e": 1654,
"s": 1601,
"text": "Each occupied cell with four or more neighbors dies."
},
{
"code": null,
"e": 1711,
"s": 1654,
"text": "Each occupied cell with two or three neighbors survives."
},
{
"code": null,
"e": 1781,
"s": 1711,
"text": "Each empty cell with exactly three neighbors develops a new organism."
},
{
"code": null,
"e": 1826,
"s": 1781,
"text": "We start by importing the libraries we need."
},
{
"code": null,
"e": 1936,
"s": 1826,
"text": "import timefrom IPython import displayimport matplotlib.pyplot as pltimport matplotlib.animation as animation"
},
{
"code": null,
"e": 2176,
"s": 1936,
"text": "We will take advantage of the FuncAnimation() function from matplotlib’s animation module. FuncAnimation() animates an image by calling a function repeatedly, updating the image on each call. We will walk through this process step by step."
},
{
"code": null,
"e": 2272,
"s": 2176,
"text": "But first, we need to initialize our board. The following few lines of code collect our inputs:"
},
{
"code": null,
"e": 2304,
"s": 2272,
"text": "We want a 50 by 50 sized board."
},
{
"code": null,
"e": 2629,
"s": 2304,
"text": "The pad variable makes it easier to calculate neighbors. By padding the edges with extra cells that are always empty, we make it so that we don’t need to write extra logic to handle the edges of the board. So our 50 by 50 board is surrounded by a border of empty cells, making the actual numpy array have a size of 52 by 52."
},
{
"code": null,
"e": 2758,
"s": 2629,
"text": "The initial_cells variable is how many organisms we want to start the board off with. They will be placed randomly on the board."
},
{
"code": null,
"e": 3035,
"s": 2758,
"text": "# Input variables for the boardboardsize = 50 # board will be X by X where X = boardsizepad = 2 # padded border, do not change this!initial_cells = 1500 # this number of initial cells will be placed # in randomly generated positions"
},
{
"code": null,
"e": 3201,
"s": 3035,
"text": "Next we randomly generate a bunch of coordinates (we chose 1,500 above) where our initial organisms will live. These coordinates are stored in the variable pos_list."
},
{
"code": null,
"e": 3446,
"s": 3201,
"text": "# Get a list of random coordinates so that we can initialize # board with randomly placed organismspos_list = []for i in range(initial_cells): pos_list.append([random.randint(1, boardsize), random.randint(1, boardsize)])"
},
{
"code": null,
"e": 3848,
"s": 3446,
"text": "Then it’s time to instantiate the board. We will use a numpy array named my_board to represent our board — we start off with a 52 by 52 array of zeros (it is bigger than 50 by 50 because of the padding) and then call the function init_board() to fill it with organisms according to the coordinates in pos_list. I won’t go into detail on the helper functions here, but they are documented on my GitHub."
},
{
"code": null,
"e": 3963,
"s": 3848,
"text": "# Initialize the boardmy_board = np.zeros((boardsize+pad, boardsize+pad))my_board = init_board(pos_list, my_board)"
},
{
"code": null,
"e": 4158,
"s": 3963,
"text": "The part that we’ve been waiting for — animation! First, we need to get some formalities out of the way. The following lines of code create the matplotlib figure that will display our animation."
},
{
"code": null,
"e": 4302,
"s": 4158,
"text": "# Required line for plotting the animation%matplotlib notebook# Initialize the plot of the board that will be used for animationfig = plt.gcf()"
},
{
"code": null,
"e": 4435,
"s": 4302,
"text": "Time to make our first frame. The function imshow() from matplotlib takes in a numpy matrix and renders it as an image. Pretty cool!"
},
{
"code": null,
"e": 4518,
"s": 4435,
"text": "# Show first image - which is the initial boardim = plt.imshow(my_board)plt.show()"
},
{
"code": null,
"e": 4634,
"s": 4518,
"text": "The variable we pass imshow() is our initial board, which is stored in my_board. The image created looks like this:"
},
{
"code": null,
"e": 5116,
"s": 4634,
"text": "Now we need to make a helper function that FuncAnimation() can call. The function animate() takes in frame, which is just a counter. The frame counter is how FuncAnimation() communicates with the animate() function — for each step in time (a.k.a. frame), it will call animate() once. And animate() will in turn use the helper function update_board() to iterate the board by one turn. Finally, the function set_data() updates our image with the iterated board and we are good to go."
},
{
"code": null,
"e": 5324,
"s": 5116,
"text": "# Helper function that updates the board and returns a new image of# the updated board animate is the function that FuncAnimation callsdef animate(frame): im.set_data(update_board(my_board)) return im,"
},
{
"code": null,
"e": 5389,
"s": 5324,
"text": "Hurray! We are ready to call FuncAnimation(). Notice the inputs:"
},
{
"code": null,
"e": 5457,
"s": 5389,
"text": "fig is the plot variable we created earlier to house our animation."
},
{
"code": null,
"e": 5618,
"s": 5457,
"text": "animate is our function that FuncAnimation() communicates with using the frame counter (it is automatically passed and doesn’t need to be explicitly specified)."
},
{
"code": null,
"e": 5737,
"s": 5618,
"text": "frames is how many frames we want the animation to last for, in this case we want our animation to be 200 frames long."
},
{
"code": null,
"e": 5839,
"s": 5737,
"text": "interval is the delay between frames in milliseconds. So we want 50 milliseconds between frames here."
},
{
"code": null,
"e": 5973,
"s": 5839,
"text": "# This line creates the animationanim = animation.FuncAnimation(fig, animate, frames=200, interval=50)"
},
{
"code": null,
"e": 6067,
"s": 5973,
"text": "And that’s it! Not too bad right? To celebrate our successful animation, here is another gif:"
},
{
"code": null,
"e": 6222,
"s": 6067,
"text": "I hope you find this useful. Before I go, let me help brainstorm some more data science-like applications of the animation functionality we learned today:"
},
{
"code": null,
"e": 6338,
"s": 6222,
"text": "Drawing out Monte Carlo simulations one by one so you can observe how the outcome distribution is gradually formed."
},
{
"code": null,
"e": 6456,
"s": 6338,
"text": "Walking forward through time series data in order to depict how your model or data reacts as new observations arrive."
},
{
"code": null,
"e": 6574,
"s": 6456,
"text": "Highlighting how the clusters identified by your algorithm shift as you change the inputs such as number of clusters."
},
{
"code": null,
"e": 6732,
"s": 6574,
"text": "Correlation heatmaps over time or across different subsamples of your data to visualize how different samples might affect your model’s estimated parameters."
},
{
"code": null,
"e": 6740,
"s": 6732,
"text": "Cheers!"
},
{
"code": null,
"e": 6754,
"s": 6740,
"text": "More from me:"
},
{
"code": null,
"e": 6780,
"s": 6754,
"text": "Thoughts on data science."
},
{
"code": null,
"e": 6809,
"s": 6780,
"text": "The random forest algorithm."
},
{
"code": null,
"e": 6835,
"s": 6809,
"text": "How neural networks work."
}
] |
R - Lists
|
Lists are the R objects which contain elements of different types like − numbers, strings, vectors and another list inside it. A list can also contain a matrix or a function as its elements. List is created using list() function.
Following is an example to create a list containing strings, numbers, vectors and a logical values.
# Create a list containing strings, numbers, vectors and a logical
# values.
list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1)
print(list_data)
When we execute the above code, it produces the following result −
[[1]]
[1] "Red"
[[2]]
[1] "Green"
[[3]]
[1] 21 32 11
[[4]]
[1] TRUE
[[5]]
[1] 51.23
[[6]]
[1] 119.1
The list elements can be given names and they can be accessed using these names.
# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
# Show the list.
print(list_data)
When we execute the above code, it produces the following result −
$`1st_Quarter`
[1] "Jan" "Feb" "Mar"
$A_Matrix
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8
$A_Inner_list
$A_Inner_list[[1]]
[1] "green"
$A_Inner_list[[2]]
[1] 12.3
Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names.
We continue to use the list in the above example −
# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
# Access the first element of the list.
print(list_data[1])
# Access the thrid element. As it is also a list, all its elements will be printed.
print(list_data[3])
# Access the list element using the name of the element.
print(list_data$A_Matrix)
When we execute the above code, it produces the following result −
$`1st_Quarter`
[1] "Jan" "Feb" "Mar"
$A_Inner_list
$A_Inner_list[[1]]
[1] "green"
$A_Inner_list[[2]]
[1] 12.3
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8
We can add, delete and update list elements as shown below. We can add and delete elements only at the end of a list. But we can update any element.
# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
# Add element at the end of the list.
list_data[4] <- "New element"
print(list_data[4])
# Remove the last element.
list_data[4] <- NULL
# Print the 4th Element.
print(list_data[4])
# Update the 3rd Element.
list_data[3] <- "updated element"
print(list_data[3])
When we execute the above code, it produces the following result −
[[1]]
[1] "New element"
$<NA>
NULL
$`A Inner list`
[1] "updated element"
You can merge many lists into one list by placing all the lists inside one list() function.
# Create two lists.
list1 <- list(1,2,3)
list2 <- list("Sun","Mon","Tue")
# Merge the two lists.
merged.list <- c(list1,list2)
# Print the merged list.
print(merged.list)
When we execute the above code, it produces the following result −
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] "Sun"
[[5]]
[1] "Mon"
[[6]]
[1] "Tue"
A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All the arithmetic operations on vectors can be applied after the list is converted into vectors. To do this conversion, we use the unlist() function. It takes the list as input and produces a vector.
# Create lists.
list1 <- list(1:5)
print(list1)
list2 <-list(10:14)
print(list2)
# Convert the lists to vectors.
v1 <- unlist(list1)
v2 <- unlist(list2)
print(v1)
print(v2)
# Now add the vectors
result <- v1+v2
print(result)
When we execute the above code, it produces the following result −
[[1]]
[1] 1 2 3 4 5
[[1]]
[1] 10 11 12 13 14
[1] 1 2 3 4 5
[1] 10 11 12 13 14
[1] 11 13 15 17 19
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2632,
"s": 2402,
"text": "Lists are the R objects which contain elements of different types like − numbers, strings, vectors and another list inside it. A list can also contain a matrix or a function as its elements. List is created using list() function."
},
{
"code": null,
"e": 2732,
"s": 2632,
"text": "Following is an example to create a list containing strings, numbers, vectors and a logical values."
},
{
"code": null,
"e": 2893,
"s": 2732,
"text": "# Create a list containing strings, numbers, vectors and a logical\n# values.\nlist_data <- list(\"Red\", \"Green\", c(21,32,11), TRUE, 51.23, 119.1)\nprint(list_data)"
},
{
"code": null,
"e": 2960,
"s": 2893,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 3066,
"s": 2960,
"text": "[[1]]\n[1] \"Red\"\n\n[[2]]\n[1] \"Green\"\n\n[[3]]\n[1] 21 32 11\n\n[[4]]\n[1] TRUE\n\n[[5]]\n[1] 51.23\n\n[[6]]\n[1] 119.1\n"
},
{
"code": null,
"e": 3147,
"s": 3066,
"text": "The list elements can be given names and they can be accessed using these names."
},
{
"code": null,
"e": 3446,
"s": 3147,
"text": "# Create a list containing a vector, a matrix and a list.\nlist_data <- list(c(\"Jan\",\"Feb\",\"Mar\"), matrix(c(3,9,5,1,-2,8), nrow = 2),\n list(\"green\",12.3))\n\n# Give names to the elements in the list.\nnames(list_data) <- c(\"1st Quarter\", \"A_Matrix\", \"A Inner list\")\n\n# Show the list.\nprint(list_data)"
},
{
"code": null,
"e": 3513,
"s": 3446,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 3697,
"s": 3513,
"text": "$`1st_Quarter`\n[1] \"Jan\" \"Feb\" \"Mar\"\n\n$A_Matrix\n [,1] [,2] [,3]\n[1,] 3 5 -2\n[2,] 9 1 8\n\n$A_Inner_list\n$A_Inner_list[[1]]\n[1] \"green\"\n\n$A_Inner_list[[2]]\n[1] 12.3\n"
},
{
"code": null,
"e": 3839,
"s": 3697,
"text": "Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names."
},
{
"code": null,
"e": 3890,
"s": 3839,
"text": "We continue to use the list in the above example −"
},
{
"code": null,
"e": 4404,
"s": 3890,
"text": "# Create a list containing a vector, a matrix and a list.\nlist_data <- list(c(\"Jan\",\"Feb\",\"Mar\"), matrix(c(3,9,5,1,-2,8), nrow = 2),\n list(\"green\",12.3))\n\n# Give names to the elements in the list.\nnames(list_data) <- c(\"1st Quarter\", \"A_Matrix\", \"A Inner list\")\n\n# Access the first element of the list.\nprint(list_data[1])\n\n# Access the thrid element. As it is also a list, all its elements will be printed.\nprint(list_data[3])\n\n# Access the list element using the name of the element.\nprint(list_data$A_Matrix)"
},
{
"code": null,
"e": 4471,
"s": 4404,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 4645,
"s": 4471,
"text": "$`1st_Quarter`\n[1] \"Jan\" \"Feb\" \"Mar\"\n\n$A_Inner_list\n$A_Inner_list[[1]]\n[1] \"green\"\n\n$A_Inner_list[[2]]\n[1] 12.3\n\n [,1] [,2] [,3]\n[1,] 3 5 -2\n[2,] 9 1 8\n"
},
{
"code": null,
"e": 4794,
"s": 4645,
"text": "We can add, delete and update list elements as shown below. We can add and delete elements only at the end of a list. But we can update any element."
},
{
"code": null,
"e": 5323,
"s": 4794,
"text": "# Create a list containing a vector, a matrix and a list.\nlist_data <- list(c(\"Jan\",\"Feb\",\"Mar\"), matrix(c(3,9,5,1,-2,8), nrow = 2),\n list(\"green\",12.3))\n\n# Give names to the elements in the list.\nnames(list_data) <- c(\"1st Quarter\", \"A_Matrix\", \"A Inner list\")\n\n# Add element at the end of the list.\nlist_data[4] <- \"New element\"\nprint(list_data[4])\n\n# Remove the last element.\nlist_data[4] <- NULL\n\n# Print the 4th Element.\nprint(list_data[4])\n\n# Update the 3rd Element.\nlist_data[3] <- \"updated element\"\nprint(list_data[3])"
},
{
"code": null,
"e": 5390,
"s": 5323,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 5466,
"s": 5390,
"text": "[[1]]\n[1] \"New element\"\n\n$<NA>\nNULL\n\n$`A Inner list`\n[1] \"updated element\"\n"
},
{
"code": null,
"e": 5558,
"s": 5466,
"text": "You can merge many lists into one list by placing all the lists inside one list() function."
},
{
"code": null,
"e": 5731,
"s": 5558,
"text": "# Create two lists.\nlist1 <- list(1,2,3)\nlist2 <- list(\"Sun\",\"Mon\",\"Tue\")\n\n# Merge the two lists.\nmerged.list <- c(list1,list2)\n\n# Print the merged list.\nprint(merged.list)"
},
{
"code": null,
"e": 5798,
"s": 5731,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 5888,
"s": 5798,
"text": "[[1]]\n[1] 1\n\n[[2]]\n[1] 2\n\n[[3]]\n[1] 3\n\n[[4]]\n[1] \"Sun\"\n\n[[5]]\n[1] \"Mon\"\n\n[[6]]\n[1] \"Tue\"\n"
},
{
"code": null,
"e": 6198,
"s": 5888,
"text": "A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All the arithmetic operations on vectors can be applied after the list is converted into vectors. To do this conversion, we use the unlist() function. It takes the list as input and produces a vector."
},
{
"code": null,
"e": 6427,
"s": 6198,
"text": "# Create lists.\nlist1 <- list(1:5)\nprint(list1)\n\nlist2 <-list(10:14)\nprint(list2)\n\n# Convert the lists to vectors.\nv1 <- unlist(list1)\nv2 <- unlist(list2)\n\nprint(v1)\nprint(v2)\n\n# Now add the vectors\nresult <- v1+v2\nprint(result)"
},
{
"code": null,
"e": 6494,
"s": 6427,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 6594,
"s": 6494,
"text": "[[1]]\n[1] 1 2 3 4 5\n\n[[1]]\n[1] 10 11 12 13 14\n\n[1] 1 2 3 4 5\n[1] 10 11 12 13 14\n[1] 11 13 15 17 19\n"
},
{
"code": null,
"e": 6627,
"s": 6594,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6642,
"s": 6627,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6677,
"s": 6642,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6692,
"s": 6677,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6727,
"s": 6692,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6742,
"s": 6727,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6775,
"s": 6742,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6789,
"s": 6775,
"text": " Asif Hussain"
},
{
"code": null,
"e": 6824,
"s": 6789,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6839,
"s": 6824,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6874,
"s": 6839,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6888,
"s": 6874,
"text": " Asif Hussain"
},
{
"code": null,
"e": 6895,
"s": 6888,
"text": " Print"
},
{
"code": null,
"e": 6906,
"s": 6895,
"text": " Add Notes"
}
] |
Contingency Tables, Chi-Squared and Cramer’s V | by Jeffrey Hanif Watson | Towards Data Science
|
Introduction
During the course of a recent project, I had to check a feature for associations (the lack of independence) with multiple other features. For convenience, I wrote a couple of functions to perform, and help interpret, tests for association between these categorical features. In this post, I will demonstrate this process and provide code examples that readers can use with their own data.
The Data
The dataset for this demonstration is the Open University Learning Analytics dataset1. The dataset consists of 7 csv files of student demographic, assessment, and registration data; and course, course assessment, and learning environment data in tabular form. We will be looking at two of the categorical features, final_result and highest_education, from the studentInfo.csv file. This demo assumes that this data has already been loaded into a data frame df.
Features Tested
The final_result feature is the final grade awarded for the course (out of Fail, Withdraw, Pass, Distinction), and highest_education is the highest education level completed by the student. The ranking of these (UK) education qualification categories is as follows (from lowest to highest): No Formal Qualifications, Lower Than A Level, A Level, HE Qualification, Post Graduate Qualification.
From the graph it appears that lower education levels correspond positively with the Withdrawn and Fail outcomes, and higher education level correspond positively to Pass and Distinction. We want to test and quantify these notions, if possible, using statistical methods.
Contingency Tables
We will start our investigation by creating a contingency table for our data using pandas.crosstab, and instantiating a statsmodels.stats.Table object to provide us with convenient methods to find and display any associations. The Table class employs a Pearson’s chi-squared test to assess any associations.
# creating crosstab data frametabs = pd.crosstab(df.highest_education, df.final_result)# creating a statsmodels table objecttable = sm.stats.Table(tabs)
The table_orig method will return a contingency table of the origin data. Numeric cells in the contingency table represent the number of observations for the corresponding row and column pair.
table.table_orig
The fittedvalues method will return a contingency table of values from the best fitting independent distribution for the data.
table.fittedvalues
The resid_pearson method returns a table of residuals which will reveal any associations present in the data. Positive values indicate more observations than expected if the features were independent, and negative values indicate fewer.
table.resid_pearson
From the contingency tables it appears that, in general, Distinction and Pass vary directly with education level. The higher the student’s education level, the more likely the student is to pass or pass with distinction. Conversely, Withdrawn and Fail vary inversely with education level. In general, the lower the student’s education level the more likely the student is to fail or withdraw.
Next, we will perform a hypothesis test to verify our results.
Hypothesis Test
We will test for independence using scipy.stats.chi2_contingency. Similar to the Table class, chi2_contingency uses a Pearson’s chi-squared test to assess any associations in the data.
Let’s start by defining the null and alternative hypotheses for the test and specifying the significance level.
Ho = highest_education and final_result are independent.
Ha = highest_education and final_result are not independent.
The significance level alpha = .05.
Now that we have the preliminaries out of the way, we will run the test. I wrote a little function that will print the results in a nice format.
def chi_sq_test(cross_tabs): """ Prints the Chi-Squared Statistic, p-value, and degress of freedom from a Chi-Squared test. Args: cross_tabs: A crosstab dataframe. """ chi2, p, dof, con_table = stats.chi2_contingency(cross_tabs) print(f'chi-squared = {chi2}\np value= {p}\ndegrees of freedom = {dof}')
Applying the function to our crosstab data frame returns:
chi-squared = 962.2117100356752p value= 2.4827414817328365e-198degrees of freedom = 12
Since the p value returned is less than our alpha, we reject the null hypothesis and conclude that highest_education and final_result are not independent, confirming our findings above.
Lastly, we will check the effect sizes of our features.
Effect Size
Effect size is a measure of the power of the association between the two features. We will measure the effect sizes using a function I wrote to calculate and display the Cramer’s V value, Cramer’s V degrees of freedom, and the effect size thresholds for the data.
def cramers_v(cross_tabs): """ Prints the degrees of freedom, effect size thresholds, and Cramer's V value. Args: cross_tabs: A crosstab dataframe. """ # effect size data frame for cramer's v function data = np.array([[1, .1, .3, .5], [2, .07, .21, .35], [3, .06, .17, .29], [4, .05,.15,.25], [5, .04, .13, .22]]) sizes = pd.DataFrame(data, columns=['Degrees of Freedom', 'Small Effect', 'Medium Effect', 'Large Effect']) # getting the chi sq. stat chi2 = stats.chi2_contingency(cross_tabs)[0] # calculating the total number of observations n = cross_tabs.sum().sum() # getting the degrees of freedom dof = min(cross_tabs.shape)-1 # calculating cramer's v v = np.sqrt(chi2/(n*dof)) # printing results print(f'V = {v}') print(f'Cramer\'s V Degrees of Freedom = {dof}') print(f'\nEffect Size Thresholds\n{sizes}\n')
Applying the function to our crosstab data returns:
V = 0.10148164448653103Cramer's V Degrees of Freedom = 3Effect Size Thresholds Degrees of Freedom Small Effect Medium Effect Large Effect0 1.0 0.10 0.30 0.501 2.0 0.07 0.21 0.352 3.0 0.06 0.17 0.293 4.0 0.05 0.15 0.254 5.0 0.04 0.13 0.22
Adjusted for degrees of freedom, the Cramer’s V result indicates that highest_education has a small, statistically significant effect on final_result.
Conclusion
Hopefully, this demo has shed some light on a simple, yet powerful, routine to check categorical features for associations. Feel free to use and modify the functions above for your convenience. Special thanks to Sgr Folge for pointing out an omission in the Cramer’s V code block in my original post.
Source
1Kuzilek, J., Hlosta, M. & Zdrahal, Z. Open University Learning Analytics dataset. Sci Data 4, 170171 (2017) https://doi.org/10.1038/sdata.2017.171.
The dataset is freely available at: https://analyse.kmi.open.ac.uk/open_dataset under a CC-BY 4.0 license.
|
[
{
"code": null,
"e": 184,
"s": 171,
"text": "Introduction"
},
{
"code": null,
"e": 573,
"s": 184,
"text": "During the course of a recent project, I had to check a feature for associations (the lack of independence) with multiple other features. For convenience, I wrote a couple of functions to perform, and help interpret, tests for association between these categorical features. In this post, I will demonstrate this process and provide code examples that readers can use with their own data."
},
{
"code": null,
"e": 582,
"s": 573,
"text": "The Data"
},
{
"code": null,
"e": 1043,
"s": 582,
"text": "The dataset for this demonstration is the Open University Learning Analytics dataset1. The dataset consists of 7 csv files of student demographic, assessment, and registration data; and course, course assessment, and learning environment data in tabular form. We will be looking at two of the categorical features, final_result and highest_education, from the studentInfo.csv file. This demo assumes that this data has already been loaded into a data frame df."
},
{
"code": null,
"e": 1059,
"s": 1043,
"text": "Features Tested"
},
{
"code": null,
"e": 1452,
"s": 1059,
"text": "The final_result feature is the final grade awarded for the course (out of Fail, Withdraw, Pass, Distinction), and highest_education is the highest education level completed by the student. The ranking of these (UK) education qualification categories is as follows (from lowest to highest): No Formal Qualifications, Lower Than A Level, A Level, HE Qualification, Post Graduate Qualification."
},
{
"code": null,
"e": 1724,
"s": 1452,
"text": "From the graph it appears that lower education levels correspond positively with the Withdrawn and Fail outcomes, and higher education level correspond positively to Pass and Distinction. We want to test and quantify these notions, if possible, using statistical methods."
},
{
"code": null,
"e": 1743,
"s": 1724,
"text": "Contingency Tables"
},
{
"code": null,
"e": 2051,
"s": 1743,
"text": "We will start our investigation by creating a contingency table for our data using pandas.crosstab, and instantiating a statsmodels.stats.Table object to provide us with convenient methods to find and display any associations. The Table class employs a Pearson’s chi-squared test to assess any associations."
},
{
"code": null,
"e": 2204,
"s": 2051,
"text": "# creating crosstab data frametabs = pd.crosstab(df.highest_education, df.final_result)# creating a statsmodels table objecttable = sm.stats.Table(tabs)"
},
{
"code": null,
"e": 2397,
"s": 2204,
"text": "The table_orig method will return a contingency table of the origin data. Numeric cells in the contingency table represent the number of observations for the corresponding row and column pair."
},
{
"code": null,
"e": 2414,
"s": 2397,
"text": "table.table_orig"
},
{
"code": null,
"e": 2541,
"s": 2414,
"text": "The fittedvalues method will return a contingency table of values from the best fitting independent distribution for the data."
},
{
"code": null,
"e": 2560,
"s": 2541,
"text": "table.fittedvalues"
},
{
"code": null,
"e": 2797,
"s": 2560,
"text": "The resid_pearson method returns a table of residuals which will reveal any associations present in the data. Positive values indicate more observations than expected if the features were independent, and negative values indicate fewer."
},
{
"code": null,
"e": 2817,
"s": 2797,
"text": "table.resid_pearson"
},
{
"code": null,
"e": 3210,
"s": 2817,
"text": "From the contingency tables it appears that, in general, Distinction and Pass vary directly with education level. The higher the student’s education level, the more likely the student is to pass or pass with distinction. Conversely, Withdrawn and Fail vary inversely with education level. In general, the lower the student’s education level the more likely the student is to fail or withdraw."
},
{
"code": null,
"e": 3273,
"s": 3210,
"text": "Next, we will perform a hypothesis test to verify our results."
},
{
"code": null,
"e": 3289,
"s": 3273,
"text": "Hypothesis Test"
},
{
"code": null,
"e": 3474,
"s": 3289,
"text": "We will test for independence using scipy.stats.chi2_contingency. Similar to the Table class, chi2_contingency uses a Pearson’s chi-squared test to assess any associations in the data."
},
{
"code": null,
"e": 3586,
"s": 3474,
"text": "Let’s start by defining the null and alternative hypotheses for the test and specifying the significance level."
},
{
"code": null,
"e": 3643,
"s": 3586,
"text": "Ho = highest_education and final_result are independent."
},
{
"code": null,
"e": 3704,
"s": 3643,
"text": "Ha = highest_education and final_result are not independent."
},
{
"code": null,
"e": 3740,
"s": 3704,
"text": "The significance level alpha = .05."
},
{
"code": null,
"e": 3885,
"s": 3740,
"text": "Now that we have the preliminaries out of the way, we will run the test. I wrote a little function that will print the results in a nice format."
},
{
"code": null,
"e": 4216,
"s": 3885,
"text": "def chi_sq_test(cross_tabs): \"\"\" Prints the Chi-Squared Statistic, p-value, and degress of freedom from a Chi-Squared test. Args: cross_tabs: A crosstab dataframe. \"\"\" chi2, p, dof, con_table = stats.chi2_contingency(cross_tabs) print(f'chi-squared = {chi2}\\np value= {p}\\ndegrees of freedom = {dof}')"
},
{
"code": null,
"e": 4274,
"s": 4216,
"text": "Applying the function to our crosstab data frame returns:"
},
{
"code": null,
"e": 4361,
"s": 4274,
"text": "chi-squared = 962.2117100356752p value= 2.4827414817328365e-198degrees of freedom = 12"
},
{
"code": null,
"e": 4547,
"s": 4361,
"text": "Since the p value returned is less than our alpha, we reject the null hypothesis and conclude that highest_education and final_result are not independent, confirming our findings above."
},
{
"code": null,
"e": 4603,
"s": 4547,
"text": "Lastly, we will check the effect sizes of our features."
},
{
"code": null,
"e": 4615,
"s": 4603,
"text": "Effect Size"
},
{
"code": null,
"e": 4879,
"s": 4615,
"text": "Effect size is a measure of the power of the association between the two features. We will measure the effect sizes using a function I wrote to calculate and display the Cramer’s V value, Cramer’s V degrees of freedom, and the effect size thresholds for the data."
},
{
"code": null,
"e": 5794,
"s": 4879,
"text": "def cramers_v(cross_tabs): \"\"\" Prints the degrees of freedom, effect size thresholds, and Cramer's V value. Args: cross_tabs: A crosstab dataframe. \"\"\" # effect size data frame for cramer's v function data = np.array([[1, .1, .3, .5], [2, .07, .21, .35], [3, .06, .17, .29], [4, .05,.15,.25], [5, .04, .13, .22]]) sizes = pd.DataFrame(data, columns=['Degrees of Freedom', 'Small Effect', 'Medium Effect', 'Large Effect']) # getting the chi sq. stat chi2 = stats.chi2_contingency(cross_tabs)[0] # calculating the total number of observations n = cross_tabs.sum().sum() # getting the degrees of freedom dof = min(cross_tabs.shape)-1 # calculating cramer's v v = np.sqrt(chi2/(n*dof)) # printing results print(f'V = {v}') print(f'Cramer\\'s V Degrees of Freedom = {dof}') print(f'\\nEffect Size Thresholds\\n{sizes}\\n')"
},
{
"code": null,
"e": 5846,
"s": 5794,
"text": "Applying the function to our crosstab data returns:"
},
{
"code": null,
"e": 6309,
"s": 5846,
"text": "V = 0.10148164448653103Cramer's V Degrees of Freedom = 3Effect Size Thresholds Degrees of Freedom Small Effect Medium Effect Large Effect0 1.0 0.10 0.30 0.501 2.0 0.07 0.21 0.352 3.0 0.06 0.17 0.293 4.0 0.05 0.15 0.254 5.0 0.04 0.13 0.22"
},
{
"code": null,
"e": 6460,
"s": 6309,
"text": "Adjusted for degrees of freedom, the Cramer’s V result indicates that highest_education has a small, statistically significant effect on final_result."
},
{
"code": null,
"e": 6471,
"s": 6460,
"text": "Conclusion"
},
{
"code": null,
"e": 6772,
"s": 6471,
"text": "Hopefully, this demo has shed some light on a simple, yet powerful, routine to check categorical features for associations. Feel free to use and modify the functions above for your convenience. Special thanks to Sgr Folge for pointing out an omission in the Cramer’s V code block in my original post."
},
{
"code": null,
"e": 6779,
"s": 6772,
"text": "Source"
},
{
"code": null,
"e": 6928,
"s": 6779,
"text": "1Kuzilek, J., Hlosta, M. & Zdrahal, Z. Open University Learning Analytics dataset. Sci Data 4, 170171 (2017) https://doi.org/10.1038/sdata.2017.171."
}
] |
Print Bracket Number in C++
|
In this problem, we are given expression. And we have to print the bracket number sequence. Let’s look at an example to understand the problem better.
Example,
Input : ((()())())
Output : 1233442551
Explanation − Here we have encountered 5 bracket pairs and we have printed them in a sequence of their[ occurrence.
Now since we know about the problem, let’s create a solution to this solution.
The solution to this problem requires a stack data structure. We will use one variable that keeps the count of the number of left brackets and stack keeps track of right brackets. We will count left brackets and push them into the stack and pop when the right bracket is encountered.
Step 1 : Initialise leftBrackets = 1. stack rightBrackets, empty.
Step 2 : traverse the expression using variable i = 0 to n-1.
Step 3 : if expression[i] == ‘(’ i.e. left bracket is encountered. Then,
Step 3.1 : PRINT ‘leftBracket ‘.
Step 3.2 : push the value of leftBracket in stack.
Step 3.3 : leftBracket++.
Step 4 : if expression[i] == ‘)’ i.e. right bracket is encountered. Then,
Step 4.1 : PRINT top of stack.
Step 4.2 : pop top element of the stack.
Step 5 : EXIT.
Now let’s create programming to illustrate the implementation of the above algorithm.
Live Demo
#include <bits/stdc++.h>
using namespace std;
void bracketCount(string expression, int n){
int leftBracket = 1;
stack<int> rightBracket;
for (int i = 0; i < n; i++) {
if (expression[i] == '(') {
cout<<leftBracket<<" ";
rightBracket.push(leftBracket);
leftBracket++;
}
else if(expression[i] == ')') {
cout<<rightBracket.top() << " ";
rightBracket.pop();
}
}
}
int main(){
string expression = "()((())()())";
int n = expression.size();
bracketCount(expression, n);
return 0;
}
1 1 2 3 4 4 3 5 5 6 6 2
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "In this problem, we are given expression. And we have to print the bracket number sequence. Let’s look at an example to understand the problem better."
},
{
"code": null,
"e": 1222,
"s": 1213,
"text": "Example,"
},
{
"code": null,
"e": 1261,
"s": 1222,
"text": "Input : ((()())())\nOutput : 1233442551"
},
{
"code": null,
"e": 1377,
"s": 1261,
"text": "Explanation − Here we have encountered 5 bracket pairs and we have printed them in a sequence of their[ occurrence."
},
{
"code": null,
"e": 1456,
"s": 1377,
"text": "Now since we know about the problem, let’s create a solution to this solution."
},
{
"code": null,
"e": 1740,
"s": 1456,
"text": "The solution to this problem requires a stack data structure. We will use one variable that keeps the count of the number of left brackets and stack keeps track of right brackets. We will count left brackets and push them into the stack and pop when the right bracket is encountered."
},
{
"code": null,
"e": 2227,
"s": 1740,
"text": "Step 1 : Initialise leftBrackets = 1. stack rightBrackets, empty.\nStep 2 : traverse the expression using variable i = 0 to n-1.\nStep 3 : if expression[i] == ‘(’ i.e. left bracket is encountered. Then,\n Step 3.1 : PRINT ‘leftBracket ‘.\n Step 3.2 : push the value of leftBracket in stack.\n Step 3.3 : leftBracket++.\nStep 4 : if expression[i] == ‘)’ i.e. right bracket is encountered. Then,\n Step 4.1 : PRINT top of stack.\n Step 4.2 : pop top element of the stack.\nStep 5 : EXIT."
},
{
"code": null,
"e": 2313,
"s": 2227,
"text": "Now let’s create programming to illustrate the implementation of the above algorithm."
},
{
"code": null,
"e": 2324,
"s": 2313,
"text": " Live Demo"
},
{
"code": null,
"e": 2892,
"s": 2324,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid bracketCount(string expression, int n){\n int leftBracket = 1;\n stack<int> rightBracket;\n for (int i = 0; i < n; i++) {\n if (expression[i] == '(') {\n cout<<leftBracket<<\" \";\n rightBracket.push(leftBracket);\n leftBracket++;\n }\n else if(expression[i] == ')') {\n cout<<rightBracket.top() << \" \";\n rightBracket.pop();\n }\n }\n}\nint main(){\n string expression = \"()((())()())\";\n int n = expression.size();\n bracketCount(expression, n);\n return 0;\n}"
},
{
"code": null,
"e": 2916,
"s": 2892,
"text": "1 1 2 3 4 4 3 5 5 6 6 2"
}
] |
EDA: Feature Engineering and Encoding Categorical Data | by Wesley Neill | Towards Data Science
|
Last week, we began our series on regression techniques with some exploration of the Ames, Iowa real-estate dataset, using scatterplots and bar plots. These techniques are meant to build basic intuition about patterns in our data. Plotting our data also allows us to sift through and get to know the variables we are working with. In this dataset, there are 79 different variables used to predict home sale prices. That’s a lot!
Then, we wrapped up with some ways to evaluate and fill in missing data. If you’d like to read the full article, you can find it here.
Now, load up your Jupyter Notebook from last week, and let’s get started! You can find my full notebook here, but like last time, I encourage you to develop your own as we move through this tutorial.
Before we get started, make sure you’ve completed our first exercise:
****************************************************************Exercise 1: If you haven’t already, fill in any missing data in the dataset using the techniques outlined last week. Then you’ll be ready to dive into feature engineering. *****************************************************************
The idea behind feature engineering is to first discover and then bring to the surface patterns in the data that may drive our predictor variable. This two-part process begins with an exploration of our intuition.
What gives a home value?
Here’s my shortlist:
Size. I’m talking total usable interior space.How big is the property the home sits on? I like to garden!Does it have an external structure such as a shed?How about a pool?
Size. I’m talking total usable interior space.
How big is the property the home sits on? I like to garden!
Does it have an external structure such as a shed?
How about a pool?
Notice that some of these questions have “Yes” or “No” answers, and the simple act of answering with “Yes” drives sale price up in your mind. It’s not necessarily any different when it comes to machine learning.
Now imagine a machine learning algorithm that can only answer questions based on the data it has. If we look at our data dictionary, we see only two variables that are associated with a home’s pool:
PoolArea — Area in square feet.PoolQC — Pool quality.
PoolArea — Area in square feet.
PoolQC — Pool quality.
A human can make the jump from a given home having an “Excellent” pool quality to “This home must have a pool”. There is no guarantee that your algorithm or model can, however. Therefore, we must bring this pattern to the surface through feature engineering.
Time for some code! I’m assuming you have your notebook ready to go, and the dataset loaded.
df['HasPool'] = df.PoolArea.apply(lambda x: 1 if x > 0 else 0)
This single line of code adds the feature HasPool to your Pandas data frame.
What if I want to know if a home has a big shed or not? What if I want to know if my potential new house has a tennis court? Okay, I’d never want to know that, but someone would. Let’s again look at our best friend, the data dictionary. I see a variable called MiscFeature which has the following possible values:
Elev Elevator Gar2 2nd Garage (if not described in garage section) Othr Other Shed Shed (over 100 SF) TenC Tennis Court NA None
Well, that was easy. We can now extract several features that may or may not affect the value of a home:
df['HasShed'] = f.MiscFeature.apply(lambda x: 1 if x == 'Shed' else 0)df['HasTennis'] = df.MiscFeature.apply(lambda x: 1 if x == 'TenC' else 0)df['HasGar2'] = df.MiscFeature.apply(lambda x: 1 if x == 'Gar2' else 0)
Keep in mind, that any variables you engineer in the training set also need to be created in the test set.
****************************************************************Exercise 2: Answer the question “How much above ground living area does the house have?” Is there a variable that describes this quantity? If not, figure out how to engineer a variable that does, using the data you do have and the techniques above.*****************************************************************
Another way of tackling feature engineering is to “Try to say the same thing differently”. You can take existing information and break it into smaller parts. Imagine explaining a concept with more detail to someone who doesn’t understand. Alternatively, you can combine existing variables, which would be analogous to explaining a concept in broader strokes.
Before we move away from feature engineering, let me just say this: Don’t trust your intuition. Intuition is typically built by experience and experimentation. When intuition fails due to a lack of experience, research is a great substitute. For example, I didn’t know that a finished basement adds less value per square foot than an above-ground room!
Before we can garner any statistical insights into our data, we need it all to be encoded in numerical format. This will allow us to perform calculations on our data. To get an intuition about how to do this, we need to consider that there are two types of categorical variables: Ordinal and Nominal.
Ordinal: The possible values for an ordinal variable are non-continuous but do have an underlying rank structure. An example of an ordinal variable would be one that classifies college students into one of four categories: Freshman, Sophomore, Junior, or Senior. These discrete categories have an underlying order.
Nominal: A nominal variable is one that has no obvious underlying rank or order. Color is a good example. ‘Red’, ‘Blue’, ‘Green’ might as well be listed ‘Blue’, ‘Green’, ‘Red’, as they have no intrinsic properties that give them rank.
Defining these two categories is important when we want to convert categorical data to numbers. If our categories are ordinal, we must provide a method that preserves the underlying rank structure.
***************************************************************Exercise 3: Sort your categorical data into 2 lists, like so:
ordinal = ['ExterQual', 'BsmtQual', 'GarageQual', 'KitchenQual', 'FireplaceQu', 'PoolQC', 'OverallQual', 'ExterCond', ... ]nominal = ['Neighborhood', 'MSZoning', 'Condition1', 'Condition2', 'RoofStyle', ... ]
***************************************************************
Once we have our ordinal/ranked data separated, we must figure out exactly how it is ranked. Again, we must refer to our data dictionary to do this. If you haven’t noticed, the data dictionary is an essential tool that you should probably have open at all times. For example, let’s take the variable BsmtExposure:
BsmtExposure: Refers to walkout or garden level walls (split levels or foyers typically score average or above) Gd Good Exposure Av Average Exposure Mn Mimimum Exposure No No Exposure NA No Basement
This variable describes how well exposed to the outside a basement is. Many split level homes have a furnished basement with external access and patio or porch. This is considered “good exposure”, and we must account for it when we encode our variables.
There are likely many ways to encode ordinal data to numbers, but I like to use a dictionary or map.
BsmtExposure_map = { 'Gd':4, 'Av':3, 'Mn':2, 'No':1, 'NA':0}df.BsmtExposure = df.BsmtExposure.map(BsmtExposure_map)
Note the use of Pandas.Series.map to transform our variable with rank intact.
Likewise, we can do the same thing with the variable Functional, which describes any major damage or other issues with the house. Values range from Sal to Typ, where Sal means the house has experienced catastrophic damage and is uninhabitable. Typ signifies normal wear and tear.
Functional_map = { 'Sal': 0, 'Sev': 1, 'Maj2': 3, 'Maj1': 4, 'Mod': 5, 'Min2': 6, 'Min1': 7, 'Typ': 8}df.Functional = df.Functional.map(Functional_map)
**************************************************************Exercise 3: Convert all of your ordinal variables in the same manner as the two examples above. Keep in mind, this needs to be done for both your training and test sets. ***************************************************************
Okay, everybody likes heat maps of correlation matrices. I’m as guilty as the next guy or gal, and I am guilty of spending way too much time on choosing the perfect color map to match the rest of my notebook. So here’s a sample of what we are going to do in the next article (after we talk about why we can’t trust a pretty face... or heatmap):
Which will bring us to statistical testing... If the first date is a heatmap, then performing statistical testing is digging deep to find out if your new crush is as pretty on the inside as she is on the outside.
Until then, feel free to leave a comment with any questions, comments, or corrections!
|
[
{
"code": null,
"e": 476,
"s": 47,
"text": "Last week, we began our series on regression techniques with some exploration of the Ames, Iowa real-estate dataset, using scatterplots and bar plots. These techniques are meant to build basic intuition about patterns in our data. Plotting our data also allows us to sift through and get to know the variables we are working with. In this dataset, there are 79 different variables used to predict home sale prices. That’s a lot!"
},
{
"code": null,
"e": 611,
"s": 476,
"text": "Then, we wrapped up with some ways to evaluate and fill in missing data. If you’d like to read the full article, you can find it here."
},
{
"code": null,
"e": 811,
"s": 611,
"text": "Now, load up your Jupyter Notebook from last week, and let’s get started! You can find my full notebook here, but like last time, I encourage you to develop your own as we move through this tutorial."
},
{
"code": null,
"e": 881,
"s": 811,
"text": "Before we get started, make sure you’ve completed our first exercise:"
},
{
"code": null,
"e": 1183,
"s": 881,
"text": "****************************************************************Exercise 1: If you haven’t already, fill in any missing data in the dataset using the techniques outlined last week. Then you’ll be ready to dive into feature engineering. *****************************************************************"
},
{
"code": null,
"e": 1397,
"s": 1183,
"text": "The idea behind feature engineering is to first discover and then bring to the surface patterns in the data that may drive our predictor variable. This two-part process begins with an exploration of our intuition."
},
{
"code": null,
"e": 1422,
"s": 1397,
"text": "What gives a home value?"
},
{
"code": null,
"e": 1443,
"s": 1422,
"text": "Here’s my shortlist:"
},
{
"code": null,
"e": 1616,
"s": 1443,
"text": "Size. I’m talking total usable interior space.How big is the property the home sits on? I like to garden!Does it have an external structure such as a shed?How about a pool?"
},
{
"code": null,
"e": 1663,
"s": 1616,
"text": "Size. I’m talking total usable interior space."
},
{
"code": null,
"e": 1723,
"s": 1663,
"text": "How big is the property the home sits on? I like to garden!"
},
{
"code": null,
"e": 1774,
"s": 1723,
"text": "Does it have an external structure such as a shed?"
},
{
"code": null,
"e": 1792,
"s": 1774,
"text": "How about a pool?"
},
{
"code": null,
"e": 2004,
"s": 1792,
"text": "Notice that some of these questions have “Yes” or “No” answers, and the simple act of answering with “Yes” drives sale price up in your mind. It’s not necessarily any different when it comes to machine learning."
},
{
"code": null,
"e": 2203,
"s": 2004,
"text": "Now imagine a machine learning algorithm that can only answer questions based on the data it has. If we look at our data dictionary, we see only two variables that are associated with a home’s pool:"
},
{
"code": null,
"e": 2257,
"s": 2203,
"text": "PoolArea — Area in square feet.PoolQC — Pool quality."
},
{
"code": null,
"e": 2289,
"s": 2257,
"text": "PoolArea — Area in square feet."
},
{
"code": null,
"e": 2312,
"s": 2289,
"text": "PoolQC — Pool quality."
},
{
"code": null,
"e": 2571,
"s": 2312,
"text": "A human can make the jump from a given home having an “Excellent” pool quality to “This home must have a pool”. There is no guarantee that your algorithm or model can, however. Therefore, we must bring this pattern to the surface through feature engineering."
},
{
"code": null,
"e": 2664,
"s": 2571,
"text": "Time for some code! I’m assuming you have your notebook ready to go, and the dataset loaded."
},
{
"code": null,
"e": 2727,
"s": 2664,
"text": "df['HasPool'] = df.PoolArea.apply(lambda x: 1 if x > 0 else 0)"
},
{
"code": null,
"e": 2804,
"s": 2727,
"text": "This single line of code adds the feature HasPool to your Pandas data frame."
},
{
"code": null,
"e": 3118,
"s": 2804,
"text": "What if I want to know if a home has a big shed or not? What if I want to know if my potential new house has a tennis court? Okay, I’d never want to know that, but someone would. Let’s again look at our best friend, the data dictionary. I see a variable called MiscFeature which has the following possible values:"
},
{
"code": null,
"e": 3283,
"s": 3118,
"text": " Elev\tElevator Gar2\t2nd Garage (if not described in garage section) Othr\tOther Shed\tShed (over 100 SF) TenC\tTennis Court NA\tNone"
},
{
"code": null,
"e": 3388,
"s": 3283,
"text": "Well, that was easy. We can now extract several features that may or may not affect the value of a home:"
},
{
"code": null,
"e": 3615,
"s": 3388,
"text": "df['HasShed'] = f.MiscFeature.apply(lambda x: 1 if x == 'Shed' else 0)df['HasTennis'] = df.MiscFeature.apply(lambda x: 1 if x == 'TenC' else 0)df['HasGar2'] = df.MiscFeature.apply(lambda x: 1 if x == 'Gar2' else 0)"
},
{
"code": null,
"e": 3722,
"s": 3615,
"text": "Keep in mind, that any variables you engineer in the training set also need to be created in the test set."
},
{
"code": null,
"e": 4100,
"s": 3722,
"text": "****************************************************************Exercise 2: Answer the question “How much above ground living area does the house have?” Is there a variable that describes this quantity? If not, figure out how to engineer a variable that does, using the data you do have and the techniques above.*****************************************************************"
},
{
"code": null,
"e": 4459,
"s": 4100,
"text": "Another way of tackling feature engineering is to “Try to say the same thing differently”. You can take existing information and break it into smaller parts. Imagine explaining a concept with more detail to someone who doesn’t understand. Alternatively, you can combine existing variables, which would be analogous to explaining a concept in broader strokes."
},
{
"code": null,
"e": 4812,
"s": 4459,
"text": "Before we move away from feature engineering, let me just say this: Don’t trust your intuition. Intuition is typically built by experience and experimentation. When intuition fails due to a lack of experience, research is a great substitute. For example, I didn’t know that a finished basement adds less value per square foot than an above-ground room!"
},
{
"code": null,
"e": 5113,
"s": 4812,
"text": "Before we can garner any statistical insights into our data, we need it all to be encoded in numerical format. This will allow us to perform calculations on our data. To get an intuition about how to do this, we need to consider that there are two types of categorical variables: Ordinal and Nominal."
},
{
"code": null,
"e": 5428,
"s": 5113,
"text": "Ordinal: The possible values for an ordinal variable are non-continuous but do have an underlying rank structure. An example of an ordinal variable would be one that classifies college students into one of four categories: Freshman, Sophomore, Junior, or Senior. These discrete categories have an underlying order."
},
{
"code": null,
"e": 5663,
"s": 5428,
"text": "Nominal: A nominal variable is one that has no obvious underlying rank or order. Color is a good example. ‘Red’, ‘Blue’, ‘Green’ might as well be listed ‘Blue’, ‘Green’, ‘Red’, as they have no intrinsic properties that give them rank."
},
{
"code": null,
"e": 5861,
"s": 5663,
"text": "Defining these two categories is important when we want to convert categorical data to numbers. If our categories are ordinal, we must provide a method that preserves the underlying rank structure."
},
{
"code": null,
"e": 5986,
"s": 5861,
"text": "***************************************************************Exercise 3: Sort your categorical data into 2 lists, like so:"
},
{
"code": null,
"e": 6229,
"s": 5986,
"text": "ordinal = ['ExterQual', 'BsmtQual', 'GarageQual', 'KitchenQual', 'FireplaceQu', 'PoolQC', 'OverallQual', 'ExterCond', ... ]nominal = ['Neighborhood', 'MSZoning', 'Condition1', 'Condition2', 'RoofStyle', ... ]"
},
{
"code": null,
"e": 6293,
"s": 6229,
"text": "***************************************************************"
},
{
"code": null,
"e": 6607,
"s": 6293,
"text": "Once we have our ordinal/ranked data separated, we must figure out exactly how it is ranked. Again, we must refer to our data dictionary to do this. If you haven’t noticed, the data dictionary is an essential tool that you should probably have open at all times. For example, let’s take the variable BsmtExposure:"
},
{
"code": null,
"e": 6838,
"s": 6607,
"text": "BsmtExposure: Refers to walkout or garden level walls (split levels or foyers typically score average or above) Gd\tGood Exposure Av\tAverage Exposure \t Mn\tMimimum Exposure No\tNo Exposure NA\tNo Basement"
},
{
"code": null,
"e": 7092,
"s": 6838,
"text": "This variable describes how well exposed to the outside a basement is. Many split level homes have a furnished basement with external access and patio or porch. This is considered “good exposure”, and we must account for it when we encode our variables."
},
{
"code": null,
"e": 7193,
"s": 7092,
"text": "There are likely many ways to encode ordinal data to numbers, but I like to use a dictionary or map."
},
{
"code": null,
"e": 7324,
"s": 7193,
"text": "BsmtExposure_map = { 'Gd':4, 'Av':3, 'Mn':2, 'No':1, 'NA':0}df.BsmtExposure = df.BsmtExposure.map(BsmtExposure_map)"
},
{
"code": null,
"e": 7402,
"s": 7324,
"text": "Note the use of Pandas.Series.map to transform our variable with rank intact."
},
{
"code": null,
"e": 7682,
"s": 7402,
"text": "Likewise, we can do the same thing with the variable Functional, which describes any major damage or other issues with the house. Values range from Sal to Typ, where Sal means the house has experienced catastrophic damage and is uninhabitable. Typ signifies normal wear and tear."
},
{
"code": null,
"e": 7858,
"s": 7682,
"text": "Functional_map = { 'Sal': 0, 'Sev': 1, 'Maj2': 3, 'Maj1': 4, 'Mod': 5, 'Min2': 6, 'Min1': 7, 'Typ': 8}df.Functional = df.Functional.map(Functional_map)"
},
{
"code": null,
"e": 8154,
"s": 7858,
"text": "**************************************************************Exercise 3: Convert all of your ordinal variables in the same manner as the two examples above. Keep in mind, this needs to be done for both your training and test sets. ***************************************************************"
},
{
"code": null,
"e": 8499,
"s": 8154,
"text": "Okay, everybody likes heat maps of correlation matrices. I’m as guilty as the next guy or gal, and I am guilty of spending way too much time on choosing the perfect color map to match the rest of my notebook. So here’s a sample of what we are going to do in the next article (after we talk about why we can’t trust a pretty face... or heatmap):"
},
{
"code": null,
"e": 8712,
"s": 8499,
"text": "Which will bring us to statistical testing... If the first date is a heatmap, then performing statistical testing is digging deep to find out if your new crush is as pretty on the inside as she is on the outside."
}
] |
Building an ML application using MLlib in Pyspark | by Yashwanth Madaka | Towards Data Science
|
Apache Spark is one of the on-demand big data tools which is being used by many companies around the world. Its ability to do In-Memory computation and Parallel-Processing are the main reasons for the popularity of this tool.
MLlib is a scalable Machine learning library which is present alongside other services like Spark SQL, Spark Streaming and GraphX on top of Spark.
In this article, we are going to concentrate on a dataset called Stroke dataset. Stoke is a condition in which either the blood flow to the brain stops or blood flow is excessive. The risk factors of stroke are
cigarette smoking
high blood pressure
diabetes
high blood cholesterol levels
heavy drinking
a diet high in fat (particularly saturated) and salt, but low in fiber, fruit, and vegetables
lack of regular exercise
obesity
So I got a good dataset here: https://bigml.com/user/francisco/gallery/model/508b2008570c6372100000b1#info
The below is the dataset:
The dataset contains almost all the risk factors of the stroke mentioned above. Hence it is important to choose a dataset with appropriate risk factors.
We are going to change the string values of the columns into a numerical values. The reason for this will be explained later. Using replace function in Excel, I had changed the dataset into the below
Gender column — Male=1, Female=0
Gender column — Male=1, Female=0
2. Smoking history — Never=0, Ever=0.25, Not current = 0.5, former = 0.75, current = 1.0
Google cloud — we will be setting up our spark clusters in Dataproc and code in Jupyter notebookJpmml(pyspark2pmml) — which is used to convert our model into and pmml file.Openscoring — A REST web service for scoring PMML models.VS Code — We will be using React JS to build an interactive website which communicates with the REST server.
Google cloud — we will be setting up our spark clusters in Dataproc and code in Jupyter notebook
Jpmml(pyspark2pmml) — which is used to convert our model into and pmml file.
Openscoring — A REST web service for scoring PMML models.
VS Code — We will be using React JS to build an interactive website which communicates with the REST server.
The below image showcases a brief architecture of our whole project.
Google cloud has a service called Dataproc which is used to create clusters which come preinstalled with Apache Spark. We can resize our clusters anytime we want to. Google cloud provides free $300 credit as an introductory offer. So, we will be using these free credits to set up our cluster.
Click on ‘Activate’ to get the free $300 credit.
Select your country and click on “continue”. In the next page, you will be prompted to enter your billing details and credit or debit card details. Fill them and click the bottom button.
Console page will be opened. On top of the page, type Dataproc in the search bar and the above page will be opened. Click on create a cluster to start creating a cluster.
Make sure you enter the same above settings. Click on Advanced options and follow the above image settings and click on create. It might take 2 to 3 mins to create a cluster.
Navigate to the cluster and click on VM instances. Under the VM instances, we can see that a master node and two worker nodes are created. The role of the master node is it usually requests the resources in the cluster and makes them available to the spark driver. It monitors and tracks the status of worker nodes whose work is to host the executor process which stores output data from tasks and also hosts the JVM. A detailed description can be found here
Now click on the SSH button of the master node.
A new terminal is opened in a new chrome tab. This is the command line interface through which we can interact with our cluster. Type “pyspark” to check the installation on spark and its version. Make sure the version of spark is above 2.2 and python version is 3.6.
Now to setup jupyter notebook, we need to create a firewall rule. Follow the images to setup new firewall rule. Make sure you select “Allow all” in the protocols and ports.
Click on save and navigate to “External IP addresses”.
change the TYPE of ‘spark-cluster-m’ to static. Give any name and click on “RESERVE”.
Now navigate to “SSH” and type the below commands.
sudo nano ~/.jupyter_notebook_config.py
copy the below lines and paste it. Press CTRL+o, Enter, CTRL+x.
c=get_config()c.NotebookApp.ip=’*’c.NotebookApp.open_browser=Falsec.NotebookApp.port=5000
Now we can open jupyter notebook by below command
jupyter-notebook --no-browser — port=5000
type the above command in the SSH and then open a new tab and type “https://localhost:5000” in your google chrome to open Jupyter notebook. In my case, the localhost is 35.230.35.117
Before going into this section, we need to install a few external libraries.
We need Imblearn library to perform SMOTE as our dataset is highly imbalanced. More information about smote can be found in this link.
In SSH, type
sudo -i
and then type the below line
conda install -c glemaitre imbalanced-learn
exit from the root folder and then open Jupyter notebook. Let’s start coding.
Import important libraries
from pyspark.sql import SQLContextfrom pyspark.sql import DataFrameNaFunctionsfrom pyspark.ml import Pipelinefrom pyspark.ml.classification import DecisionTreeClassifierfrom pyspark.ml.classification import LogisticRegressionfrom pyspark.ml.feature import Binarizerfrom pyspark.ml.feature import OneHotEncoder, VectorAssembler, StringIndexer, VectorIndexerfrom pyspark.ml.classification import RandomForestClassifierfrom pyspark.sql.functions import avgimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom pyspark.ml.evaluation import MulticlassClassificationEvaluatorfrom pyspark.mllib.evaluation import MulticlassMetricsfrom pyspark.ml.evaluation import BinaryClassificationEvaluatorfrom imblearn.over_sampling import SMOTEfrom imblearn.combine import SMOTEENNfrom sklearn.model_selection import train_test_splitfrom collections import Counter
Now we need to create a spark session.
from pyspark.context import SparkContextfrom pyspark.sql.session import SparkSessionsc = SparkContext(‘local’)spark = SparkSession(sc)
We need to access our datafile from storage. Navigate to “bucket” in google cloud console and create a new bucket. I had given the name “data-stroke-1” and upload the modified CSV file.
Now we need to load the CSV file which we had uploaded in our bucket.
input_dir = ‘gs://data-stroke-1/’df = spark.read.format(‘com.databricks.spark.csv’).options(header=’true’, inferschema=’true’).load(input_dir+’stroke.csv’)df.columns
We can check our dataframe by printing it using the command shown in the below figure.
Now, we need to create a column in which we have all the features responsible to predict the occurrence of stroke.
featureColumns = [‘gender’,’age’,‘diabetes’,‘hypertension’, ‘heart disease’,‘smoking history’,‘BMI’]
Make sure all the columns are in double values. Next, let's remove all the entries which are under age below 2.
df = df.filter(df.age >2)df.count()
Now let's print a bar graph to check the type of classes present in our data
responses = df.groupBy(‘stroke’).count().collect()categories = [i[0] for i in responses]counts = [i[1] for i in responses] ind = np.array(range(len(categories)))width = 0.35plt.bar(ind, counts, width=width, color=’r’) plt.ylabel(‘counts’)plt.title(‘Stroke’)plt.xticks(ind + width/2., categories)
Step3A. Missing data Management
Now, it's very important to do proper missing data management to get a very good model at the end. It's not always good to use “df.na.drop()” which removes all the rows which have missing data. Filling them with proper reasonable values is one idea which we can implement.
As we can see, we have missing values in BMI column and Smoking history column. One possible way to fill up these BMI values is to use the Age values to fill them up.
For smoking history, it is very difficult to find reasonable values to fill them up. Usually, people below 16 years are not that addicted to smoking and hence we can fill up the values of those age group people with 0. People between age 17 to 24 might have tried smoking at least once in their life and so we can give 0.25 value to those people. Now a few people after a certain age quit and few of them still continue even though they have health problems. We cannot decide which value to give to them and so by default, we will give assign the value 0 to them.
We can either drop all the rows which have missing values in these columns or we can fill in those by the above logic. But for the purpose of this tutorial, I had filled the missing rows by the above logic but practically tampering with the data with no data-driven logic to back it up is usually not a good idea.
We are going to perform a few operations on this dataframe and spark dataframe doesn’t support any operations. So we replicate our dataframe to pandas dataframe and then perform the actions.
imputeDF = dfimputeDF_Pandas = imputeDF.toPandas()
We will be dividing the full dataframe into many dataframes based on the age and fill them with reasonable values and then, later on, combine all the dataframes into one and convert it back to spark dataframe.
df_2_9 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=2 ) & (imputeDF_Pandas[‘age’] <= 9)]values = {‘smoking history’: 0, ‘BMI’:17.125}df_2_9 = df_2_9.fillna(value = values)df_10_13 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=10 ) & (imputeDF_Pandas[‘age’] <= 13)]values = {‘smoking history’: 0, ‘BMI’:19.5}df_10_13 = df_10_13.fillna(value = values)df_14_17 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=14 ) & (imputeDF_Pandas[‘age’] <= 17)]values = {‘smoking history’: 0, ‘BMI’:23.05}df_14_17 = df_14_17.fillna(value = values)df_18_24 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=18 ) & (imputeDF_Pandas[‘age’] <= 24)]values = {‘smoking history’: 0, ‘BMI’:27.1}df_18_24 = df_18_24.fillna(value = values)df_25_29 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=25 ) & (imputeDF_Pandas[‘age’] <= 29)]values = {‘smoking history’: 0, ‘BMI’:27.9}df_25_29 = df_25_29.fillna(value = values)df_30_34 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=30 ) & (imputeDF_Pandas[‘age’] <= 34)]values = {‘smoking history’: 0.25, ‘BMI’:29.6}df_30_34 = df_30_34.fillna(value = values)df_35_44 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=35 ) & (imputeDF_Pandas[‘age’] <= 44)]values = {‘smoking history’: 0.25, ‘BMI’:30.15}df_35_44 = df_35_44.fillna(value = values)df_45_49 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=45 ) & (imputeDF_Pandas[‘age’] <= 49)]values = {‘smoking history’: 0, ‘BMI’:29.7}df_45_49 = df_45_49.fillna(value = values)df_50_59 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=50 ) & (imputeDF_Pandas[‘age’] <= 59)]values = {‘smoking history’: 0, ‘BMI’:29.95}df_50_59 = df_50_59.fillna(value = values)df_60_74 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=60 ) & (imputeDF_Pandas[‘age’] <= 74)]values = {‘smoking history’: 0, ‘BMI’:30.1}df_60_74 = df_60_74.fillna(value = values)df_75_plus = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >75 )]values = {‘smoking history’: 0, ‘BMI’:28.1}df_75_plus = df_75_plus.fillna(value = values)
Combine all dataframes
all_frames = [df_2_9, df_10_13, df_14_17, df_18_24, df_25_29, df_30_34, df_35_44, df_45_49, df_50_59, df_60_74, df_75_plus]df_combined = pd.concat(all_frames)df_combined_converted = spark.createDataFrame(df_combined)imputeDF = df_combined_converted
Step 3B. Dealing with imbalanced data
We will perform SMOTE technique to deal with imbalanced data. SMOTE can be referred from here:
X = imputeDF.toPandas().filter(items=[‘gender’, ‘age’, ‘diabetes’,’hypertension’,’heart disease’,’smoking history’,’BMI’])Y = imputeDF.toPandas().filter(items=[‘stroke’])X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.1, random_state=0)
sm = SMOTE(random_state=12, ratio = ‘auto’, kind = ‘regular’)x_train_res, y_train_res = sm.fit_sample(X_train, Y_train)print(‘Resampled dataset shape {}’.format(Counter(y_train_res)))
Please refer to this link to know about the parameters
X_train contains all the columns of the data except the Stroke column.
Y_train contains the Stroke column data.
Combine the resampled data into one spark dataframe
dataframe_1 = pd.DataFrame(x_train_res,columns=[‘gender’, ‘age’, ‘diabetes’, ‘hypertension’, ‘heart disease’, ‘smoking history’, ‘BMI’])dataframe_2 = pd.DataFrame(y_train_res, columns = [‘stroke’])# frames = [dataframe_1, dataframe_2]result = dataframe_1.combine_first(dataframe_2)
change it back to spark dataframe
imputeDF_1 = spark.createDataFrame(result)
Check the Resampled data. Its the same code we used earlier.
As we can see, we resampled our data successfully. Now we will be getting into the next part.
Below is a common pipeline of a spark ml project except in our case we had not used string indexer and oneHotEncoder.
Now to build an assembler and for this, we need a Binarizer.
binarizer = Binarizer(threshold=0.0, inputCol=”stroke”, outputCol=”label”)binarizedDF = binarizer.transform(imputeDF_1)binarizedDF = binarizedDF.drop(‘stroke’)
What this does is it creates a new column with name “label” and values the same as the values in stroke column.
assembler = VectorAssembler(inputCols = featureColumns, outputCol = “features”)assembled = assembler.transform(binarizedDF)print(assembled)
Assembler assembles all the columns which are required to predict stroke and produces one vector called features.
And now over to Splitting Data
(trainingData, testData) = assembled.randomSplit([0.7, 0.3], seed=0)print(“Distribution of Ones and Zeros in trainingData is: “, trainingData.groupBy(“label”).count().take(3))
Training
dt = DecisionTreeClassifier(labelCol="label", featuresCol="features", maxDepth=25, minInstancesPerNode=30, impurity="gini")pipeline = Pipeline(stages=[dt])model = pipeline.fit(trainingData)
Testing
predictions = model.transform(testData)
AUC-ROC
from pyspark.mllib.evaluation import BinaryClassificationMetrics as metricresults = predictions.select(['probability', 'label']) ## prepare score-label setresults_collect = results.collect()results_list = [(float(i[0][0]), 1.0-float(i[1])) for i in results_collect]scoreAndLabels = sc.parallelize(results_list) metrics = metric(scoreAndLabels)print("Test Data Aread under ROC score is : ", metrics.areaUnderROC)
from sklearn.metrics import roc_curve, auc fpr = dict()tpr = dict()roc_auc = dict() y_test = [i[1] for i in results_list]y_score = [i[0] for i in results_list] fpr, tpr, _ = roc_curve(y_test, y_score)roc_auc = auc(fpr, tpr) %matplotlib inlineplt.figure()plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)plt.plot([0, 1], [0, 1], 'k--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic Graph')plt.legend(loc="lower right")plt.show()
As we can see, we got the score of AUC-ROC around 98 which is very good. The model might be overfitted due to the usage of SMOTE technique. (But Logistic Regression works well for this dataset. But there seem to be some bugs in pyspark2pmml library which doesn’t export the logistic regression model properly.) So for demonstration purpose I am going to use Decision Tree model file.
To do this, we are going to use a library called PySPark2PMML and its details can be found here (https://github.com/jpmml/pyspark2pmml)
Save the jupyter file and exit the jupyter notebook.
Download the jpmml-sparkml-executable-1.5.3.jar file from — https://github.com/jpmml/jpmml-sparkml/releases
Upload it into the SSH
After upload, if we check by running “ls” command we see our file.
Now we need to setup jupyter notebook in such a way that when we type pyspark in the ssh, we need to fire open jupyter notebook. To do so, we need to change the environment variable.
Update PySpark driver environment variables:
add the below lines to your ~/.bashrc (or ~/.zshrc) file. Press “i” to insert the new lines. Copy the below code and paste it using “CTRL+V”.
export PYSPARK_DRIVER_PYTHON=jupyterexport PYSPARK_DRIVER_PYTHON_OPTS='notebook'
To save and exit the vi editor, press “ESC” and “:wq” to save it.
Restart your terminal and then type “pyspark”. You should be able to run jupyter notebook.
You should be able to see the port number in one of the lines.
Now to use the pmml library, open jupyter notebook by calling with the below command.
pyspark --jars /home/yashwanthmadaka_imp24/jpmml-sparkml-executable-1.5.3.jar
After opening the jupyter notebook, run all the cells which we had written earlier. Now, add the below piece of code.
trainingData = trainingData.drop(“features”)from pyspark.ml.feature import RFormulaformula = RFormula(formula = "label ~ .")classifier = DecisionTreeClassifier(maxDepth=25, minInstancesPerNode=30, impurity="gini")pipeline = Pipeline(stages = [formula, classifier])pipelineModel = pipeline.fit(trainingData)from pyspark2pmml import PMMLBuilderpmmlBuilder = PMMLBuilder(sc, trainingData, pipelineModel) \ .putOption(classifier, "compact", True)pmmlBuilder.buildFile("dt-stroke.pmml")
After running the above code, a new file will be created at the location mentioned. Download this file to your local desktop and let’s start building a website to interact with our model file.
The entire jupyter notebook can be found here.
Step 6a. Building a REST server from our model files:
For an application to interact with the model file, we need to expose the application as a REST web service. To do this, we are going to use the help of Openscoring library.
We need to install Openscoring using maven. Make sure you place the model file which we downloaded from our Google clouds VM machine into PATH/openscoring/openscoring-client/target folder.
where PATH = the path where the openscoring files exist.
After installation, we need to start the server by following the below commands.
First, start a server by going into the server folder and type the commands below
cd openscoring-server/targetjava -jar openscoring-server-executable-2.0-SNAPSHOT.jar
Next, start the client side by going to the client folder and type the below commands. Next, open a new cmd and type the below commands.
cd openscoring-client/targetjava -cp openscoring-client-executable-2.0-SNAPSHOT.jar org.openscoring.client.Deployer --model http://localhost:8080/openscoring/model/stroke --file dt-stroke.pmml
When we visit the http://localhost:8080/openscoring/model/stroke we can see the below structure
Step 6b. Downloading the ReactJS Frontend and running it:
Now visit the this Github link and clone this project.
After downloading, open this project folder using the VS Code. Open the terminal inside and type
npm install
Before starting our ReactJS application, we need to enable CORS. To do this, we can add a chrome extension.
After switching on the CORS, type the below command in VS Code terminal.
npm start
A web interface will open as shown below.
We can input any values and test it. We will get the prediction, the probability of occurrence of stroke and the probability of non-occurrence of stroke.
All the methods of interacting with the REST server are coded in the index.js file.
Reality model scores of 98 are impossible to achieve and the main significance of this blog is to show how to interact with ML models made in pyspark.
The better is our data preprocessing, the better will be our model. The quality of the model directly depends on the quality and diversity of the data we use. So, it’s better to spend more time doing proper data cleaning and data filtering techniques.
SMOTE — https://medium.com/coinmonks/smote-and-adasyn-handling-imbalanced-data-set-34f5223e167pyspark2pmml — https://github.com/jpmml/pyspark2pmmlOpenscoring — https://github.com/openscoring/openscoringReactJs Frontend — https://github.com/yashwanthmadaka24/React-Js-Website
SMOTE — https://medium.com/coinmonks/smote-and-adasyn-handling-imbalanced-data-set-34f5223e167
pyspark2pmml — https://github.com/jpmml/pyspark2pmml
Openscoring — https://github.com/openscoring/openscoring
ReactJs Frontend — https://github.com/yashwanthmadaka24/React-Js-Website
And now, its time for a break 😇
|
[
{
"code": null,
"e": 398,
"s": 172,
"text": "Apache Spark is one of the on-demand big data tools which is being used by many companies around the world. Its ability to do In-Memory computation and Parallel-Processing are the main reasons for the popularity of this tool."
},
{
"code": null,
"e": 545,
"s": 398,
"text": "MLlib is a scalable Machine learning library which is present alongside other services like Spark SQL, Spark Streaming and GraphX on top of Spark."
},
{
"code": null,
"e": 756,
"s": 545,
"text": "In this article, we are going to concentrate on a dataset called Stroke dataset. Stoke is a condition in which either the blood flow to the brain stops or blood flow is excessive. The risk factors of stroke are"
},
{
"code": null,
"e": 774,
"s": 756,
"text": "cigarette smoking"
},
{
"code": null,
"e": 794,
"s": 774,
"text": "high blood pressure"
},
{
"code": null,
"e": 803,
"s": 794,
"text": "diabetes"
},
{
"code": null,
"e": 833,
"s": 803,
"text": "high blood cholesterol levels"
},
{
"code": null,
"e": 848,
"s": 833,
"text": "heavy drinking"
},
{
"code": null,
"e": 942,
"s": 848,
"text": "a diet high in fat (particularly saturated) and salt, but low in fiber, fruit, and vegetables"
},
{
"code": null,
"e": 967,
"s": 942,
"text": "lack of regular exercise"
},
{
"code": null,
"e": 975,
"s": 967,
"text": "obesity"
},
{
"code": null,
"e": 1082,
"s": 975,
"text": "So I got a good dataset here: https://bigml.com/user/francisco/gallery/model/508b2008570c6372100000b1#info"
},
{
"code": null,
"e": 1108,
"s": 1082,
"text": "The below is the dataset:"
},
{
"code": null,
"e": 1261,
"s": 1108,
"text": "The dataset contains almost all the risk factors of the stroke mentioned above. Hence it is important to choose a dataset with appropriate risk factors."
},
{
"code": null,
"e": 1461,
"s": 1261,
"text": "We are going to change the string values of the columns into a numerical values. The reason for this will be explained later. Using replace function in Excel, I had changed the dataset into the below"
},
{
"code": null,
"e": 1494,
"s": 1461,
"text": "Gender column — Male=1, Female=0"
},
{
"code": null,
"e": 1527,
"s": 1494,
"text": "Gender column — Male=1, Female=0"
},
{
"code": null,
"e": 1616,
"s": 1527,
"text": "2. Smoking history — Never=0, Ever=0.25, Not current = 0.5, former = 0.75, current = 1.0"
},
{
"code": null,
"e": 1954,
"s": 1616,
"text": "Google cloud — we will be setting up our spark clusters in Dataproc and code in Jupyter notebookJpmml(pyspark2pmml) — which is used to convert our model into and pmml file.Openscoring — A REST web service for scoring PMML models.VS Code — We will be using React JS to build an interactive website which communicates with the REST server."
},
{
"code": null,
"e": 2051,
"s": 1954,
"text": "Google cloud — we will be setting up our spark clusters in Dataproc and code in Jupyter notebook"
},
{
"code": null,
"e": 2128,
"s": 2051,
"text": "Jpmml(pyspark2pmml) — which is used to convert our model into and pmml file."
},
{
"code": null,
"e": 2186,
"s": 2128,
"text": "Openscoring — A REST web service for scoring PMML models."
},
{
"code": null,
"e": 2295,
"s": 2186,
"text": "VS Code — We will be using React JS to build an interactive website which communicates with the REST server."
},
{
"code": null,
"e": 2364,
"s": 2295,
"text": "The below image showcases a brief architecture of our whole project."
},
{
"code": null,
"e": 2658,
"s": 2364,
"text": "Google cloud has a service called Dataproc which is used to create clusters which come preinstalled with Apache Spark. We can resize our clusters anytime we want to. Google cloud provides free $300 credit as an introductory offer. So, we will be using these free credits to set up our cluster."
},
{
"code": null,
"e": 2707,
"s": 2658,
"text": "Click on ‘Activate’ to get the free $300 credit."
},
{
"code": null,
"e": 2894,
"s": 2707,
"text": "Select your country and click on “continue”. In the next page, you will be prompted to enter your billing details and credit or debit card details. Fill them and click the bottom button."
},
{
"code": null,
"e": 3065,
"s": 2894,
"text": "Console page will be opened. On top of the page, type Dataproc in the search bar and the above page will be opened. Click on create a cluster to start creating a cluster."
},
{
"code": null,
"e": 3240,
"s": 3065,
"text": "Make sure you enter the same above settings. Click on Advanced options and follow the above image settings and click on create. It might take 2 to 3 mins to create a cluster."
},
{
"code": null,
"e": 3699,
"s": 3240,
"text": "Navigate to the cluster and click on VM instances. Under the VM instances, we can see that a master node and two worker nodes are created. The role of the master node is it usually requests the resources in the cluster and makes them available to the spark driver. It monitors and tracks the status of worker nodes whose work is to host the executor process which stores output data from tasks and also hosts the JVM. A detailed description can be found here"
},
{
"code": null,
"e": 3747,
"s": 3699,
"text": "Now click on the SSH button of the master node."
},
{
"code": null,
"e": 4014,
"s": 3747,
"text": "A new terminal is opened in a new chrome tab. This is the command line interface through which we can interact with our cluster. Type “pyspark” to check the installation on spark and its version. Make sure the version of spark is above 2.2 and python version is 3.6."
},
{
"code": null,
"e": 4187,
"s": 4014,
"text": "Now to setup jupyter notebook, we need to create a firewall rule. Follow the images to setup new firewall rule. Make sure you select “Allow all” in the protocols and ports."
},
{
"code": null,
"e": 4242,
"s": 4187,
"text": "Click on save and navigate to “External IP addresses”."
},
{
"code": null,
"e": 4328,
"s": 4242,
"text": "change the TYPE of ‘spark-cluster-m’ to static. Give any name and click on “RESERVE”."
},
{
"code": null,
"e": 4379,
"s": 4328,
"text": "Now navigate to “SSH” and type the below commands."
},
{
"code": null,
"e": 4419,
"s": 4379,
"text": "sudo nano ~/.jupyter_notebook_config.py"
},
{
"code": null,
"e": 4483,
"s": 4419,
"text": "copy the below lines and paste it. Press CTRL+o, Enter, CTRL+x."
},
{
"code": null,
"e": 4573,
"s": 4483,
"text": "c=get_config()c.NotebookApp.ip=’*’c.NotebookApp.open_browser=Falsec.NotebookApp.port=5000"
},
{
"code": null,
"e": 4623,
"s": 4573,
"text": "Now we can open jupyter notebook by below command"
},
{
"code": null,
"e": 4665,
"s": 4623,
"text": "jupyter-notebook --no-browser — port=5000"
},
{
"code": null,
"e": 4848,
"s": 4665,
"text": "type the above command in the SSH and then open a new tab and type “https://localhost:5000” in your google chrome to open Jupyter notebook. In my case, the localhost is 35.230.35.117"
},
{
"code": null,
"e": 4925,
"s": 4848,
"text": "Before going into this section, we need to install a few external libraries."
},
{
"code": null,
"e": 5060,
"s": 4925,
"text": "We need Imblearn library to perform SMOTE as our dataset is highly imbalanced. More information about smote can be found in this link."
},
{
"code": null,
"e": 5073,
"s": 5060,
"text": "In SSH, type"
},
{
"code": null,
"e": 5081,
"s": 5073,
"text": "sudo -i"
},
{
"code": null,
"e": 5110,
"s": 5081,
"text": "and then type the below line"
},
{
"code": null,
"e": 5154,
"s": 5110,
"text": "conda install -c glemaitre imbalanced-learn"
},
{
"code": null,
"e": 5232,
"s": 5154,
"text": "exit from the root folder and then open Jupyter notebook. Let’s start coding."
},
{
"code": null,
"e": 5259,
"s": 5232,
"text": "Import important libraries"
},
{
"code": null,
"e": 6143,
"s": 5259,
"text": "from pyspark.sql import SQLContextfrom pyspark.sql import DataFrameNaFunctionsfrom pyspark.ml import Pipelinefrom pyspark.ml.classification import DecisionTreeClassifierfrom pyspark.ml.classification import LogisticRegressionfrom pyspark.ml.feature import Binarizerfrom pyspark.ml.feature import OneHotEncoder, VectorAssembler, StringIndexer, VectorIndexerfrom pyspark.ml.classification import RandomForestClassifierfrom pyspark.sql.functions import avgimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom pyspark.ml.evaluation import MulticlassClassificationEvaluatorfrom pyspark.mllib.evaluation import MulticlassMetricsfrom pyspark.ml.evaluation import BinaryClassificationEvaluatorfrom imblearn.over_sampling import SMOTEfrom imblearn.combine import SMOTEENNfrom sklearn.model_selection import train_test_splitfrom collections import Counter"
},
{
"code": null,
"e": 6182,
"s": 6143,
"text": "Now we need to create a spark session."
},
{
"code": null,
"e": 6317,
"s": 6182,
"text": "from pyspark.context import SparkContextfrom pyspark.sql.session import SparkSessionsc = SparkContext(‘local’)spark = SparkSession(sc)"
},
{
"code": null,
"e": 6503,
"s": 6317,
"text": "We need to access our datafile from storage. Navigate to “bucket” in google cloud console and create a new bucket. I had given the name “data-stroke-1” and upload the modified CSV file."
},
{
"code": null,
"e": 6573,
"s": 6503,
"text": "Now we need to load the CSV file which we had uploaded in our bucket."
},
{
"code": null,
"e": 6739,
"s": 6573,
"text": "input_dir = ‘gs://data-stroke-1/’df = spark.read.format(‘com.databricks.spark.csv’).options(header=’true’, inferschema=’true’).load(input_dir+’stroke.csv’)df.columns"
},
{
"code": null,
"e": 6826,
"s": 6739,
"text": "We can check our dataframe by printing it using the command shown in the below figure."
},
{
"code": null,
"e": 6941,
"s": 6826,
"text": "Now, we need to create a column in which we have all the features responsible to predict the occurrence of stroke."
},
{
"code": null,
"e": 7042,
"s": 6941,
"text": "featureColumns = [‘gender’,’age’,‘diabetes’,‘hypertension’, ‘heart disease’,‘smoking history’,‘BMI’]"
},
{
"code": null,
"e": 7154,
"s": 7042,
"text": "Make sure all the columns are in double values. Next, let's remove all the entries which are under age below 2."
},
{
"code": null,
"e": 7190,
"s": 7154,
"text": "df = df.filter(df.age >2)df.count()"
},
{
"code": null,
"e": 7267,
"s": 7190,
"text": "Now let's print a bar graph to check the type of classes present in our data"
},
{
"code": null,
"e": 7563,
"s": 7267,
"text": "responses = df.groupBy(‘stroke’).count().collect()categories = [i[0] for i in responses]counts = [i[1] for i in responses] ind = np.array(range(len(categories)))width = 0.35plt.bar(ind, counts, width=width, color=’r’) plt.ylabel(‘counts’)plt.title(‘Stroke’)plt.xticks(ind + width/2., categories)"
},
{
"code": null,
"e": 7595,
"s": 7563,
"text": "Step3A. Missing data Management"
},
{
"code": null,
"e": 7868,
"s": 7595,
"text": "Now, it's very important to do proper missing data management to get a very good model at the end. It's not always good to use “df.na.drop()” which removes all the rows which have missing data. Filling them with proper reasonable values is one idea which we can implement."
},
{
"code": null,
"e": 8035,
"s": 7868,
"text": "As we can see, we have missing values in BMI column and Smoking history column. One possible way to fill up these BMI values is to use the Age values to fill them up."
},
{
"code": null,
"e": 8599,
"s": 8035,
"text": "For smoking history, it is very difficult to find reasonable values to fill them up. Usually, people below 16 years are not that addicted to smoking and hence we can fill up the values of those age group people with 0. People between age 17 to 24 might have tried smoking at least once in their life and so we can give 0.25 value to those people. Now a few people after a certain age quit and few of them still continue even though they have health problems. We cannot decide which value to give to them and so by default, we will give assign the value 0 to them."
},
{
"code": null,
"e": 8913,
"s": 8599,
"text": "We can either drop all the rows which have missing values in these columns or we can fill in those by the above logic. But for the purpose of this tutorial, I had filled the missing rows by the above logic but practically tampering with the data with no data-driven logic to back it up is usually not a good idea."
},
{
"code": null,
"e": 9104,
"s": 8913,
"text": "We are going to perform a few operations on this dataframe and spark dataframe doesn’t support any operations. So we replicate our dataframe to pandas dataframe and then perform the actions."
},
{
"code": null,
"e": 9155,
"s": 9104,
"text": "imputeDF = dfimputeDF_Pandas = imputeDF.toPandas()"
},
{
"code": null,
"e": 9365,
"s": 9155,
"text": "We will be dividing the full dataframe into many dataframes based on the age and fill them with reasonable values and then, later on, combine all the dataframes into one and convert it back to spark dataframe."
},
{
"code": null,
"e": 11277,
"s": 9365,
"text": "df_2_9 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=2 ) & (imputeDF_Pandas[‘age’] <= 9)]values = {‘smoking history’: 0, ‘BMI’:17.125}df_2_9 = df_2_9.fillna(value = values)df_10_13 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=10 ) & (imputeDF_Pandas[‘age’] <= 13)]values = {‘smoking history’: 0, ‘BMI’:19.5}df_10_13 = df_10_13.fillna(value = values)df_14_17 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=14 ) & (imputeDF_Pandas[‘age’] <= 17)]values = {‘smoking history’: 0, ‘BMI’:23.05}df_14_17 = df_14_17.fillna(value = values)df_18_24 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=18 ) & (imputeDF_Pandas[‘age’] <= 24)]values = {‘smoking history’: 0, ‘BMI’:27.1}df_18_24 = df_18_24.fillna(value = values)df_25_29 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=25 ) & (imputeDF_Pandas[‘age’] <= 29)]values = {‘smoking history’: 0, ‘BMI’:27.9}df_25_29 = df_25_29.fillna(value = values)df_30_34 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=30 ) & (imputeDF_Pandas[‘age’] <= 34)]values = {‘smoking history’: 0.25, ‘BMI’:29.6}df_30_34 = df_30_34.fillna(value = values)df_35_44 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=35 ) & (imputeDF_Pandas[‘age’] <= 44)]values = {‘smoking history’: 0.25, ‘BMI’:30.15}df_35_44 = df_35_44.fillna(value = values)df_45_49 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=45 ) & (imputeDF_Pandas[‘age’] <= 49)]values = {‘smoking history’: 0, ‘BMI’:29.7}df_45_49 = df_45_49.fillna(value = values)df_50_59 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=50 ) & (imputeDF_Pandas[‘age’] <= 59)]values = {‘smoking history’: 0, ‘BMI’:29.95}df_50_59 = df_50_59.fillna(value = values)df_60_74 = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >=60 ) & (imputeDF_Pandas[‘age’] <= 74)]values = {‘smoking history’: 0, ‘BMI’:30.1}df_60_74 = df_60_74.fillna(value = values)df_75_plus = imputeDF_Pandas[(imputeDF_Pandas[‘age’] >75 )]values = {‘smoking history’: 0, ‘BMI’:28.1}df_75_plus = df_75_plus.fillna(value = values)"
},
{
"code": null,
"e": 11300,
"s": 11277,
"text": "Combine all dataframes"
},
{
"code": null,
"e": 11549,
"s": 11300,
"text": "all_frames = [df_2_9, df_10_13, df_14_17, df_18_24, df_25_29, df_30_34, df_35_44, df_45_49, df_50_59, df_60_74, df_75_plus]df_combined = pd.concat(all_frames)df_combined_converted = spark.createDataFrame(df_combined)imputeDF = df_combined_converted"
},
{
"code": null,
"e": 11587,
"s": 11549,
"text": "Step 3B. Dealing with imbalanced data"
},
{
"code": null,
"e": 11682,
"s": 11587,
"text": "We will perform SMOTE technique to deal with imbalanced data. SMOTE can be referred from here:"
},
{
"code": null,
"e": 11941,
"s": 11682,
"text": "X = imputeDF.toPandas().filter(items=[‘gender’, ‘age’, ‘diabetes’,’hypertension’,’heart disease’,’smoking history’,’BMI’])Y = imputeDF.toPandas().filter(items=[‘stroke’])X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.1, random_state=0)"
},
{
"code": null,
"e": 12125,
"s": 11941,
"text": "sm = SMOTE(random_state=12, ratio = ‘auto’, kind = ‘regular’)x_train_res, y_train_res = sm.fit_sample(X_train, Y_train)print(‘Resampled dataset shape {}’.format(Counter(y_train_res)))"
},
{
"code": null,
"e": 12180,
"s": 12125,
"text": "Please refer to this link to know about the parameters"
},
{
"code": null,
"e": 12251,
"s": 12180,
"text": "X_train contains all the columns of the data except the Stroke column."
},
{
"code": null,
"e": 12292,
"s": 12251,
"text": "Y_train contains the Stroke column data."
},
{
"code": null,
"e": 12344,
"s": 12292,
"text": "Combine the resampled data into one spark dataframe"
},
{
"code": null,
"e": 12626,
"s": 12344,
"text": "dataframe_1 = pd.DataFrame(x_train_res,columns=[‘gender’, ‘age’, ‘diabetes’, ‘hypertension’, ‘heart disease’, ‘smoking history’, ‘BMI’])dataframe_2 = pd.DataFrame(y_train_res, columns = [‘stroke’])# frames = [dataframe_1, dataframe_2]result = dataframe_1.combine_first(dataframe_2)"
},
{
"code": null,
"e": 12660,
"s": 12626,
"text": "change it back to spark dataframe"
},
{
"code": null,
"e": 12703,
"s": 12660,
"text": "imputeDF_1 = spark.createDataFrame(result)"
},
{
"code": null,
"e": 12764,
"s": 12703,
"text": "Check the Resampled data. Its the same code we used earlier."
},
{
"code": null,
"e": 12858,
"s": 12764,
"text": "As we can see, we resampled our data successfully. Now we will be getting into the next part."
},
{
"code": null,
"e": 12976,
"s": 12858,
"text": "Below is a common pipeline of a spark ml project except in our case we had not used string indexer and oneHotEncoder."
},
{
"code": null,
"e": 13037,
"s": 12976,
"text": "Now to build an assembler and for this, we need a Binarizer."
},
{
"code": null,
"e": 13197,
"s": 13037,
"text": "binarizer = Binarizer(threshold=0.0, inputCol=”stroke”, outputCol=”label”)binarizedDF = binarizer.transform(imputeDF_1)binarizedDF = binarizedDF.drop(‘stroke’)"
},
{
"code": null,
"e": 13309,
"s": 13197,
"text": "What this does is it creates a new column with name “label” and values the same as the values in stroke column."
},
{
"code": null,
"e": 13449,
"s": 13309,
"text": "assembler = VectorAssembler(inputCols = featureColumns, outputCol = “features”)assembled = assembler.transform(binarizedDF)print(assembled)"
},
{
"code": null,
"e": 13563,
"s": 13449,
"text": "Assembler assembles all the columns which are required to predict stroke and produces one vector called features."
},
{
"code": null,
"e": 13594,
"s": 13563,
"text": "And now over to Splitting Data"
},
{
"code": null,
"e": 13770,
"s": 13594,
"text": "(trainingData, testData) = assembled.randomSplit([0.7, 0.3], seed=0)print(“Distribution of Ones and Zeros in trainingData is: “, trainingData.groupBy(“label”).count().take(3))"
},
{
"code": null,
"e": 13779,
"s": 13770,
"text": "Training"
},
{
"code": null,
"e": 13969,
"s": 13779,
"text": "dt = DecisionTreeClassifier(labelCol=\"label\", featuresCol=\"features\", maxDepth=25, minInstancesPerNode=30, impurity=\"gini\")pipeline = Pipeline(stages=[dt])model = pipeline.fit(trainingData)"
},
{
"code": null,
"e": 13977,
"s": 13969,
"text": "Testing"
},
{
"code": null,
"e": 14017,
"s": 13977,
"text": "predictions = model.transform(testData)"
},
{
"code": null,
"e": 14025,
"s": 14017,
"text": "AUC-ROC"
},
{
"code": null,
"e": 14437,
"s": 14025,
"text": "from pyspark.mllib.evaluation import BinaryClassificationMetrics as metricresults = predictions.select(['probability', 'label']) ## prepare score-label setresults_collect = results.collect()results_list = [(float(i[0][0]), 1.0-float(i[1])) for i in results_collect]scoreAndLabels = sc.parallelize(results_list) metrics = metric(scoreAndLabels)print(\"Test Data Aread under ROC score is : \", metrics.areaUnderROC)"
},
{
"code": null,
"e": 14982,
"s": 14437,
"text": "from sklearn.metrics import roc_curve, auc fpr = dict()tpr = dict()roc_auc = dict() y_test = [i[1] for i in results_list]y_score = [i[0] for i in results_list] fpr, tpr, _ = roc_curve(y_test, y_score)roc_auc = auc(fpr, tpr) %matplotlib inlineplt.figure()plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)plt.plot([0, 1], [0, 1], 'k--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic Graph')plt.legend(loc=\"lower right\")plt.show()"
},
{
"code": null,
"e": 15366,
"s": 14982,
"text": "As we can see, we got the score of AUC-ROC around 98 which is very good. The model might be overfitted due to the usage of SMOTE technique. (But Logistic Regression works well for this dataset. But there seem to be some bugs in pyspark2pmml library which doesn’t export the logistic regression model properly.) So for demonstration purpose I am going to use Decision Tree model file."
},
{
"code": null,
"e": 15502,
"s": 15366,
"text": "To do this, we are going to use a library called PySPark2PMML and its details can be found here (https://github.com/jpmml/pyspark2pmml)"
},
{
"code": null,
"e": 15555,
"s": 15502,
"text": "Save the jupyter file and exit the jupyter notebook."
},
{
"code": null,
"e": 15663,
"s": 15555,
"text": "Download the jpmml-sparkml-executable-1.5.3.jar file from — https://github.com/jpmml/jpmml-sparkml/releases"
},
{
"code": null,
"e": 15686,
"s": 15663,
"text": "Upload it into the SSH"
},
{
"code": null,
"e": 15753,
"s": 15686,
"text": "After upload, if we check by running “ls” command we see our file."
},
{
"code": null,
"e": 15936,
"s": 15753,
"text": "Now we need to setup jupyter notebook in such a way that when we type pyspark in the ssh, we need to fire open jupyter notebook. To do so, we need to change the environment variable."
},
{
"code": null,
"e": 15981,
"s": 15936,
"text": "Update PySpark driver environment variables:"
},
{
"code": null,
"e": 16123,
"s": 15981,
"text": "add the below lines to your ~/.bashrc (or ~/.zshrc) file. Press “i” to insert the new lines. Copy the below code and paste it using “CTRL+V”."
},
{
"code": null,
"e": 16204,
"s": 16123,
"text": "export PYSPARK_DRIVER_PYTHON=jupyterexport PYSPARK_DRIVER_PYTHON_OPTS='notebook'"
},
{
"code": null,
"e": 16270,
"s": 16204,
"text": "To save and exit the vi editor, press “ESC” and “:wq” to save it."
},
{
"code": null,
"e": 16361,
"s": 16270,
"text": "Restart your terminal and then type “pyspark”. You should be able to run jupyter notebook."
},
{
"code": null,
"e": 16424,
"s": 16361,
"text": "You should be able to see the port number in one of the lines."
},
{
"code": null,
"e": 16510,
"s": 16424,
"text": "Now to use the pmml library, open jupyter notebook by calling with the below command."
},
{
"code": null,
"e": 16588,
"s": 16510,
"text": "pyspark --jars /home/yashwanthmadaka_imp24/jpmml-sparkml-executable-1.5.3.jar"
},
{
"code": null,
"e": 16706,
"s": 16588,
"text": "After opening the jupyter notebook, run all the cells which we had written earlier. Now, add the below piece of code."
},
{
"code": null,
"e": 17188,
"s": 16706,
"text": "trainingData = trainingData.drop(“features”)from pyspark.ml.feature import RFormulaformula = RFormula(formula = \"label ~ .\")classifier = DecisionTreeClassifier(maxDepth=25, minInstancesPerNode=30, impurity=\"gini\")pipeline = Pipeline(stages = [formula, classifier])pipelineModel = pipeline.fit(trainingData)from pyspark2pmml import PMMLBuilderpmmlBuilder = PMMLBuilder(sc, trainingData, pipelineModel) \\ .putOption(classifier, \"compact\", True)pmmlBuilder.buildFile(\"dt-stroke.pmml\")"
},
{
"code": null,
"e": 17381,
"s": 17188,
"text": "After running the above code, a new file will be created at the location mentioned. Download this file to your local desktop and let’s start building a website to interact with our model file."
},
{
"code": null,
"e": 17428,
"s": 17381,
"text": "The entire jupyter notebook can be found here."
},
{
"code": null,
"e": 17482,
"s": 17428,
"text": "Step 6a. Building a REST server from our model files:"
},
{
"code": null,
"e": 17656,
"s": 17482,
"text": "For an application to interact with the model file, we need to expose the application as a REST web service. To do this, we are going to use the help of Openscoring library."
},
{
"code": null,
"e": 17845,
"s": 17656,
"text": "We need to install Openscoring using maven. Make sure you place the model file which we downloaded from our Google clouds VM machine into PATH/openscoring/openscoring-client/target folder."
},
{
"code": null,
"e": 17902,
"s": 17845,
"text": "where PATH = the path where the openscoring files exist."
},
{
"code": null,
"e": 17983,
"s": 17902,
"text": "After installation, we need to start the server by following the below commands."
},
{
"code": null,
"e": 18065,
"s": 17983,
"text": "First, start a server by going into the server folder and type the commands below"
},
{
"code": null,
"e": 18150,
"s": 18065,
"text": "cd openscoring-server/targetjava -jar openscoring-server-executable-2.0-SNAPSHOT.jar"
},
{
"code": null,
"e": 18287,
"s": 18150,
"text": "Next, start the client side by going to the client folder and type the below commands. Next, open a new cmd and type the below commands."
},
{
"code": null,
"e": 18480,
"s": 18287,
"text": "cd openscoring-client/targetjava -cp openscoring-client-executable-2.0-SNAPSHOT.jar org.openscoring.client.Deployer --model http://localhost:8080/openscoring/model/stroke --file dt-stroke.pmml"
},
{
"code": null,
"e": 18576,
"s": 18480,
"text": "When we visit the http://localhost:8080/openscoring/model/stroke we can see the below structure"
},
{
"code": null,
"e": 18634,
"s": 18576,
"text": "Step 6b. Downloading the ReactJS Frontend and running it:"
},
{
"code": null,
"e": 18689,
"s": 18634,
"text": "Now visit the this Github link and clone this project."
},
{
"code": null,
"e": 18786,
"s": 18689,
"text": "After downloading, open this project folder using the VS Code. Open the terminal inside and type"
},
{
"code": null,
"e": 18798,
"s": 18786,
"text": "npm install"
},
{
"code": null,
"e": 18906,
"s": 18798,
"text": "Before starting our ReactJS application, we need to enable CORS. To do this, we can add a chrome extension."
},
{
"code": null,
"e": 18979,
"s": 18906,
"text": "After switching on the CORS, type the below command in VS Code terminal."
},
{
"code": null,
"e": 18989,
"s": 18979,
"text": "npm start"
},
{
"code": null,
"e": 19031,
"s": 18989,
"text": "A web interface will open as shown below."
},
{
"code": null,
"e": 19185,
"s": 19031,
"text": "We can input any values and test it. We will get the prediction, the probability of occurrence of stroke and the probability of non-occurrence of stroke."
},
{
"code": null,
"e": 19269,
"s": 19185,
"text": "All the methods of interacting with the REST server are coded in the index.js file."
},
{
"code": null,
"e": 19420,
"s": 19269,
"text": "Reality model scores of 98 are impossible to achieve and the main significance of this blog is to show how to interact with ML models made in pyspark."
},
{
"code": null,
"e": 19672,
"s": 19420,
"text": "The better is our data preprocessing, the better will be our model. The quality of the model directly depends on the quality and diversity of the data we use. So, it’s better to spend more time doing proper data cleaning and data filtering techniques."
},
{
"code": null,
"e": 19947,
"s": 19672,
"text": "SMOTE — https://medium.com/coinmonks/smote-and-adasyn-handling-imbalanced-data-set-34f5223e167pyspark2pmml — https://github.com/jpmml/pyspark2pmmlOpenscoring — https://github.com/openscoring/openscoringReactJs Frontend — https://github.com/yashwanthmadaka24/React-Js-Website"
},
{
"code": null,
"e": 20042,
"s": 19947,
"text": "SMOTE — https://medium.com/coinmonks/smote-and-adasyn-handling-imbalanced-data-set-34f5223e167"
},
{
"code": null,
"e": 20095,
"s": 20042,
"text": "pyspark2pmml — https://github.com/jpmml/pyspark2pmml"
},
{
"code": null,
"e": 20152,
"s": 20095,
"text": "Openscoring — https://github.com/openscoring/openscoring"
},
{
"code": null,
"e": 20225,
"s": 20152,
"text": "ReactJs Frontend — https://github.com/yashwanthmadaka24/React-Js-Website"
}
] |
User defined and custom exceptions in Java
|
An exception is an issue (run time error) that occurred during the execution of a program. For understanding purpose let us look at it in a different manner.
Generally, when you compile a program, if it gets compiled without a .class file will be created, this is the executable file in Java, and every time you execute this .class file it is supposed to run successfully executing each line in the program without any issues. But, in some exceptional cases, while executing the program, JVM encounters some ambiguous scenarios where it doesn’t know what to do.
Here are some example scenarios −
If you have an array of size 10 if a line in your code tries to access the 11th element in this array.
If you have an array of size 10 if a line in your code tries to access the 11th element in this array.
If you are trying to divide a number with 0 which (results to infinity and JVM doesn’t understand how to evaluate it).
If you are trying to divide a number with 0 which (results to infinity and JVM doesn’t understand how to evaluate it).
Such cases are known as exceptions when an exception occurs the program gets terminated abnormally. Certain exceptions are prompted at compile time they are known as checked exceptions or, compile-time exceptions and, exceptions that occur at run-time are known as run time exceptions or, unchecked exceptions.
Each possible exception is represented by a predefined class and all these classes are found in the java.lang package. Following are some exception classes
NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, IllegalArgumentException, IllegalStateException etc...
Live Demo
import java.util.Scanner;
public class ExceptionExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = sc.nextInt();
System.out.println("Enter second number: ");
int b = sc.nextInt();
int c = a/b;
System.out.println("The result is: "+c);
}
}
Enter first number:
100
Enter second number:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:10)
Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class AIOBSample {
public static void main(String args[]){
int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};
System.out.println("Elements in the array are: ");
System.out.println(Arrays.toString(myArray));
Scanner sc = new Scanner(System.in);
System.out.println("Enter the index of the required element: ");
int element = sc.nextInt();
System.out.println("Element in the given index is :: "+myArray[element]);
}
}
Elements in the array are:
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element:
7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at AIOBSample.main(AIOBSample.java:12)
Live Demo
import java.util.Arrays;
public class ArrayStoreExceptionExample {
public static void main(String args[]) {
Number integerArray[] = new Integer[3];
integerArray[0] = 12548;
integerArray[1] = 36987;
integerArray[2] = 555.50;
integerArray[3] = 12548;
System.out.println(Arrays.toString(integerArray));
}
}
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double
at ther.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:9)
Live Demo
import java.util.Enumeration;
import java.util.Vector;
public class EnumExample {
public static void main(String args[]) {
//instantiating a Vector
Vector<Integer> vec = new Vector<Integer>( );
//Populating the vector
vec.add(1254);
vec.add(4587);
//Retrieving the elements using the Enumeration
Enumeration<Integer> en = vec.elements();
System.out.println(en.nextElement());
System.out.println(en.nextElement());
//Retrieving the next element after reaching the end
System.out.println(en.nextElement());
}
}
1254
4587
Exception in thread "main" java.util.NoSuchElementException: Vector Enumeration
at java.util.Vector$1.nextElement(Unknown Source)
at July_set2.EnumExample.main(EnumExample.java:18)
You can create your own exceptions in Java and they are known as user-defined exceptions or custom exceptions.
To create a user-defined exception extend one of the above-mentioned classes. To display the message override the toString() method or, call the superclass parameterized constructor bypassing the message in String format.
MyException(String msg){
super(msg);
}
Or,
public String toString(){
return " MyException [Message of your exception]";
}
Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword.
MyException ex = new MyException ();
If(condition..........){
throw ex;
}
All exceptions must be a child of Throwable.
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException class.
If you want to write a runtime exception, you need to extend the RuntimeException class.
Following Java program Demonstrates how to create a Custom checked exception.
Live Demo
import java.util.Scanner;
class NotProperNameException extends Exception {
NotProperNameException(String msg){
super(msg);
}
}
public class CustomCheckedException{
private String name;
private int age;
public static boolean containsAlphabet(String name) {
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (!(ch >= 'a' && ch <= 'z')) {
return false;
}
}
return true;
}
public CustomCheckedException(String name, int age){
if(!containsAlphabet(name)&&name!=null) {
String msg = "Improper name (Should contain only characters between a to z (all small))";
NotProperNameException exName = new NotProperNameException(msg);
throw exName;
}
this.name = name;
this.age = age;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter the name of the person: ");
String name = sc.next();
System.out.println("Enter the age of the person: ");
int age = sc.nextInt();
CustomCheckedException obj = new CustomCheckedException(name, age);
obj.display();
}
}
On compiling, the above program generates the following exception.
CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown
throw exName;
^
1 error
If you simply change the class that your custom exception inherits to RuntimeException it will be thrown at run time
class NotProperNameException extends RuntimeException {
NotProperNameException(String msg){
super(msg);
}
}
If you run the previous program By replacing the NotProperNameException class with the above piece of code and run it, it generates the following runtime exception.
Enter the name of the person:
Krishna1234
Enter the age of the person:
20
Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))
at july_set3.CustomCheckedException.<init>(CustomCheckedException.java:25)
at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)
|
[
{
"code": null,
"e": 1220,
"s": 1062,
"text": "An exception is an issue (run time error) that occurred during the execution of a program. For understanding purpose let us look at it in a different manner."
},
{
"code": null,
"e": 1624,
"s": 1220,
"text": "Generally, when you compile a program, if it gets compiled without a .class file will be created, this is the executable file in Java, and every time you execute this .class file it is supposed to run successfully executing each line in the program without any issues. But, in some exceptional cases, while executing the program, JVM encounters some ambiguous scenarios where it doesn’t know what to do."
},
{
"code": null,
"e": 1658,
"s": 1624,
"text": "Here are some example scenarios −"
},
{
"code": null,
"e": 1761,
"s": 1658,
"text": "If you have an array of size 10 if a line in your code tries to access the 11th element in this array."
},
{
"code": null,
"e": 1864,
"s": 1761,
"text": "If you have an array of size 10 if a line in your code tries to access the 11th element in this array."
},
{
"code": null,
"e": 1983,
"s": 1864,
"text": "If you are trying to divide a number with 0 which (results to infinity and JVM doesn’t understand how to evaluate it)."
},
{
"code": null,
"e": 2102,
"s": 1983,
"text": "If you are trying to divide a number with 0 which (results to infinity and JVM doesn’t understand how to evaluate it)."
},
{
"code": null,
"e": 2413,
"s": 2102,
"text": "Such cases are known as exceptions when an exception occurs the program gets terminated abnormally. Certain exceptions are prompted at compile time they are known as checked exceptions or, compile-time exceptions and, exceptions that occur at run-time are known as run time exceptions or, unchecked exceptions."
},
{
"code": null,
"e": 2569,
"s": 2413,
"text": "Each possible exception is represented by a predefined class and all these classes are found in the java.lang package. Following are some exception classes"
},
{
"code": null,
"e": 2698,
"s": 2569,
"text": "NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, IllegalArgumentException, IllegalStateException etc..."
},
{
"code": null,
"e": 2709,
"s": 2698,
"text": " Live Demo"
},
{
"code": null,
"e": 3084,
"s": 2709,
"text": "import java.util.Scanner;\npublic class ExceptionExample {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter first number: \");\n int a = sc.nextInt();\n System.out.println(\"Enter second number: \");\n int b = sc.nextInt();\n int c = a/b;\n System.out.println(\"The result is: \"+c);\n }\n}"
},
{
"code": null,
"e": 3250,
"s": 3084,
"text": "Enter first number:\n100\nEnter second number:\n0\nException in thread \"main\" java.lang.ArithmeticException: / by zero\nat ExceptionExample.main(ExceptionExample.java:10)"
},
{
"code": null,
"e": 3261,
"s": 3250,
"text": " Live Demo"
},
{
"code": null,
"e": 3790,
"s": 3261,
"text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class AIOBSample {\n public static void main(String args[]){\n int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};\n System.out.println(\"Elements in the array are: \");\n System.out.println(Arrays.toString(myArray));\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the index of the required element: \");\n int element = sc.nextInt();\n System.out.println(\"Element in the given index is :: \"+myArray[element]);\n }\n}"
},
{
"code": null,
"e": 4001,
"s": 3790,
"text": "Elements in the array are:\n[897, 56, 78, 90, 12, 123, 75]\nEnter the index of the required element:\n7\nException in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 7\nat AIOBSample.main(AIOBSample.java:12)"
},
{
"code": null,
"e": 4012,
"s": 4001,
"text": " Live Demo"
},
{
"code": null,
"e": 4358,
"s": 4012,
"text": "import java.util.Arrays;\npublic class ArrayStoreExceptionExample {\n public static void main(String args[]) {\n Number integerArray[] = new Integer[3];\n integerArray[0] = 12548;\n integerArray[1] = 36987;\n integerArray[2] = 555.50;\n integerArray[3] = 12548;\n System.out.println(Arrays.toString(integerArray));\n }\n}"
},
{
"code": null,
"e": 4508,
"s": 4358,
"text": "Exception in thread \"main\" java.lang.ArrayStoreException: java.lang.Double\nat ther.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:9)"
},
{
"code": null,
"e": 4519,
"s": 4508,
"text": " Live Demo"
},
{
"code": null,
"e": 5100,
"s": 4519,
"text": "import java.util.Enumeration;\nimport java.util.Vector;\npublic class EnumExample {\n public static void main(String args[]) {\n //instantiating a Vector\n Vector<Integer> vec = new Vector<Integer>( );\n //Populating the vector\n vec.add(1254);\n vec.add(4587);\n //Retrieving the elements using the Enumeration\n Enumeration<Integer> en = vec.elements();\n System.out.println(en.nextElement());\n System.out.println(en.nextElement());\n //Retrieving the next element after reaching the end\n System.out.println(en.nextElement());\n }\n}"
},
{
"code": null,
"e": 5291,
"s": 5100,
"text": "1254\n4587\nException in thread \"main\" java.util.NoSuchElementException: Vector Enumeration\nat java.util.Vector$1.nextElement(Unknown Source)\nat July_set2.EnumExample.main(EnumExample.java:18)"
},
{
"code": null,
"e": 5402,
"s": 5291,
"text": "You can create your own exceptions in Java and they are known as user-defined exceptions or custom exceptions."
},
{
"code": null,
"e": 5624,
"s": 5402,
"text": "To create a user-defined exception extend one of the above-mentioned classes. To display the message override the toString() method or, call the superclass parameterized constructor bypassing the message in String format."
},
{
"code": null,
"e": 5752,
"s": 5624,
"text": "MyException(String msg){\n super(msg);\n}\nOr,\npublic String toString(){\n return \" MyException [Message of your exception]\";\n}"
},
{
"code": null,
"e": 5927,
"s": 5752,
"text": "Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword."
},
{
"code": null,
"e": 6004,
"s": 5927,
"text": "MyException ex = new MyException ();\nIf(condition..........){\n throw ex;\n}"
},
{
"code": null,
"e": 6049,
"s": 6004,
"text": "All exceptions must be a child of Throwable."
},
{
"code": null,
"e": 6094,
"s": 6049,
"text": "All exceptions must be a child of Throwable."
},
{
"code": null,
"e": 6237,
"s": 6094,
"text": "If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class."
},
{
"code": null,
"e": 6380,
"s": 6237,
"text": "If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class."
},
{
"code": null,
"e": 6469,
"s": 6380,
"text": "If you want to write a runtime exception, you need to extend the RuntimeException class."
},
{
"code": null,
"e": 6558,
"s": 6469,
"text": "If you want to write a runtime exception, you need to extend the RuntimeException class."
},
{
"code": null,
"e": 6636,
"s": 6558,
"text": "Following Java program Demonstrates how to create a Custom checked exception."
},
{
"code": null,
"e": 6647,
"s": 6636,
"text": " Live Demo"
},
{
"code": null,
"e": 7998,
"s": 6647,
"text": "import java.util.Scanner;\nclass NotProperNameException extends Exception {\n NotProperNameException(String msg){\n super(msg);\n }\n}\npublic class CustomCheckedException{\n private String name;\n private int age;\n public static boolean containsAlphabet(String name) {\n for (int i = 0; i < name.length(); i++) {\n char ch = name.charAt(i);\n if (!(ch >= 'a' && ch <= 'z')) {\n return false;\n }\n }\n return true;\n }\n public CustomCheckedException(String name, int age){\n if(!containsAlphabet(name)&&name!=null) {\n String msg = \"Improper name (Should contain only characters between a to z (all small))\";\n NotProperNameException exName = new NotProperNameException(msg);\n throw exName;\n }\n this.name = name;\n this.age = age;\n }\n public void display(){\n System.out.println(\"Name of the Student: \"+this.name );\n System.out.println(\"Age of the Student: \"+this.age );\n }\n public static void main(String args[]) {\n Scanner sc= new Scanner(System.in);\n System.out.println(\"Enter the name of the person: \");\n String name = sc.next();\n System.out.println(\"Enter the age of the person: \");\n int age = sc.nextInt();\n CustomCheckedException obj = new CustomCheckedException(name, age);\n obj.display();\n }\n}"
},
{
"code": null,
"e": 8065,
"s": 7998,
"text": "On compiling, the above program generates the following exception."
},
{
"code": null,
"e": 8219,
"s": 8065,
"text": "CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown\n throw exName;\n ^\n1 error"
},
{
"code": null,
"e": 8336,
"s": 8219,
"text": "If you simply change the class that your custom exception inherits to RuntimeException it will be thrown at run time"
},
{
"code": null,
"e": 8456,
"s": 8336,
"text": "class NotProperNameException extends RuntimeException {\n NotProperNameException(String msg){\n super(msg);\n }\n}"
},
{
"code": null,
"e": 8621,
"s": 8456,
"text": "If you run the previous program By replacing the NotProperNameException class with the above piece of code and run it, it generates the following runtime exception."
},
{
"code": null,
"e": 8978,
"s": 8621,
"text": "Enter the name of the person:\nKrishna1234\nEnter the age of the person:\n20\nException in thread \"main\" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))\nat july_set3.CustomCheckedException.<init>(CustomCheckedException.java:25)\nat july_set3.CustomCheckedException.main(CustomCheckedException.java:41)"
}
] |
Build a Machine Learning simulation tool with Dash | by Pierre-Louis Bescond | Towards Data Science
|
You have done it! It all started with a business issue raised by your colleagues and you went through the dark valleys of data consolidation, cleansing, feature engineering, and modeling. Your model’s robustness is checked and you would like to share your findings.
However, not everyone is familiar with RMSE, Confusion Matrix or Shapey values...
As an example, operational teams in Industry are facing daily challenges to optimize production or supply-chain and Machine Learning is offering a new way to understand complex processes behaviors... as long as it can be translated into an intelligible analysis. And when comes the time to share some insights brought by A.I., a Python Notebook is probably not the best choice!
More than the model predicting power itself, teams are always keen to understand what the most important factors are among the numerous production parameters involved and how each of them might influence the model’s behavior.
The concept is pretty simple:
You create a .py script where your “classic” machine learning tasks are combined with a coded web-layout design, close from HTML code.
When executed, the python script generates a dynamic web page on a local address (http://127.0.0.1:8050/) where components interact with each other.
First, we need to design a “look-a-like” industrial use-case! “make_regression” from Scikit-learn will generate our data source. We will fine-tune some of the features to get realistic figures in the example:
Once the “Machine Learning” tasks are done, we still need to prepare the dynamic information to be displayed on our web browser. For this example, we will create:
A bar chart showing the model features’ importance
Three sliders allowing the user to change the values of the three most important features and understand their impact on the model prediction
You might have noticed that the bar chart creation is similar to the one used in Plotly except that the .show() function is not called. The reason is that the chart will be rendered in the “Layout” section.
The “Layout” section (below) requires some practice for users who are not familiar with both Python and HTML.
The philosophy here is to combine HTML elements (called by htm.xxx) with Dynamic Dash Components (dcc.xxx).
We will keep it very simple for this example:
<H1> Title<DCC> Features Importance Chart<H4> #1 Importance Feature Name<DCC> #1 Feature slider<H4> #2 Importance Feature Name<DCC> #2 Feature slider<H4> #2 Importance Feature Name<DCC> #2 Feature slider<H2> Updated predictions
Here comes the “touchiest” part of the script: the app.callback function allows you to encapsulate a standard python function so that it will interact with the web page components designed above. Its mechanism can be simplified as follows:
@app.callback(Output_on_webpage, Input_1_from_webpage, Input_2_from_webpage, Input_3_from_webpage)python_function(Input_1, Input_2, Input_3): Output = model_evaluation([Input_1, Input_2, Input_3]) return Output
You might have noticed that we considered here that only the three most important features were worth being updated. Thus, we considered the mean value of every other feature when the model is evaluating the array. This is obviously a design choice for simplification purposes.
We open the command prompt and type “python dashboard.py”
(base) PS C:\Users\...\> jupyter dashboard.py * Serving Flask app "__main__" (lazy loading) * Environment: production * Debug mode: off * Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)
Now, we just have to open our favorite web-browser at http://127.0.0.1:8050/ and check the result:
Every time a slider moves, the app.callback function runs the python script to re-evaluate the prediction!
The complete script is stored here on GitHub.
As you can imagine, it becomes a very powerful tool to have non-data-scientist teams interact with the model and understand its behavior. This is also a very good platform to test the model’s accuracy: operational teams will be able to check and confirm that the model’s behavior does correspond to their field experience.
A few recommendations before we close this article:
If you are not familiar with Plotly and Dash, you should start by training yourself on standard Plotly charts (the steps are extremely well explained):
plotly.com
The online course below is really well designed and it will guide you through Python basics (Pandas / NumPy), Plotly chart syntax as well as Dash design. I hardly recommend it:
|
[
{
"code": null,
"e": 313,
"s": 47,
"text": "You have done it! It all started with a business issue raised by your colleagues and you went through the dark valleys of data consolidation, cleansing, feature engineering, and modeling. Your model’s robustness is checked and you would like to share your findings."
},
{
"code": null,
"e": 395,
"s": 313,
"text": "However, not everyone is familiar with RMSE, Confusion Matrix or Shapey values..."
},
{
"code": null,
"e": 773,
"s": 395,
"text": "As an example, operational teams in Industry are facing daily challenges to optimize production or supply-chain and Machine Learning is offering a new way to understand complex processes behaviors... as long as it can be translated into an intelligible analysis. And when comes the time to share some insights brought by A.I., a Python Notebook is probably not the best choice!"
},
{
"code": null,
"e": 999,
"s": 773,
"text": "More than the model predicting power itself, teams are always keen to understand what the most important factors are among the numerous production parameters involved and how each of them might influence the model’s behavior."
},
{
"code": null,
"e": 1029,
"s": 999,
"text": "The concept is pretty simple:"
},
{
"code": null,
"e": 1164,
"s": 1029,
"text": "You create a .py script where your “classic” machine learning tasks are combined with a coded web-layout design, close from HTML code."
},
{
"code": null,
"e": 1313,
"s": 1164,
"text": "When executed, the python script generates a dynamic web page on a local address (http://127.0.0.1:8050/) where components interact with each other."
},
{
"code": null,
"e": 1522,
"s": 1313,
"text": "First, we need to design a “look-a-like” industrial use-case! “make_regression” from Scikit-learn will generate our data source. We will fine-tune some of the features to get realistic figures in the example:"
},
{
"code": null,
"e": 1685,
"s": 1522,
"text": "Once the “Machine Learning” tasks are done, we still need to prepare the dynamic information to be displayed on our web browser. For this example, we will create:"
},
{
"code": null,
"e": 1736,
"s": 1685,
"text": "A bar chart showing the model features’ importance"
},
{
"code": null,
"e": 1878,
"s": 1736,
"text": "Three sliders allowing the user to change the values of the three most important features and understand their impact on the model prediction"
},
{
"code": null,
"e": 2085,
"s": 1878,
"text": "You might have noticed that the bar chart creation is similar to the one used in Plotly except that the .show() function is not called. The reason is that the chart will be rendered in the “Layout” section."
},
{
"code": null,
"e": 2195,
"s": 2085,
"text": "The “Layout” section (below) requires some practice for users who are not familiar with both Python and HTML."
},
{
"code": null,
"e": 2303,
"s": 2195,
"text": "The philosophy here is to combine HTML elements (called by htm.xxx) with Dynamic Dash Components (dcc.xxx)."
},
{
"code": null,
"e": 2349,
"s": 2303,
"text": "We will keep it very simple for this example:"
},
{
"code": null,
"e": 2582,
"s": 2349,
"text": "<H1> Title<DCC> Features Importance Chart<H4> #1 Importance Feature Name<DCC> #1 Feature slider<H4> #2 Importance Feature Name<DCC> #2 Feature slider<H4> #2 Importance Feature Name<DCC> #2 Feature slider<H2> Updated predictions"
},
{
"code": null,
"e": 2822,
"s": 2582,
"text": "Here comes the “touchiest” part of the script: the app.callback function allows you to encapsulate a standard python function so that it will interact with the web page components designed above. Its mechanism can be simplified as follows:"
},
{
"code": null,
"e": 3084,
"s": 2822,
"text": "@app.callback(Output_on_webpage, Input_1_from_webpage, Input_2_from_webpage, Input_3_from_webpage)python_function(Input_1, Input_2, Input_3): Output = model_evaluation([Input_1, Input_2, Input_3]) return Output"
},
{
"code": null,
"e": 3362,
"s": 3084,
"text": "You might have noticed that we considered here that only the three most important features were worth being updated. Thus, we considered the mean value of every other feature when the model is evaluating the array. This is obviously a design choice for simplification purposes."
},
{
"code": null,
"e": 3420,
"s": 3362,
"text": "We open the command prompt and type “python dashboard.py”"
},
{
"code": null,
"e": 3615,
"s": 3420,
"text": "(base) PS C:\\Users\\...\\> jupyter dashboard.py * Serving Flask app \"__main__\" (lazy loading) * Environment: production * Debug mode: off * Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)"
},
{
"code": null,
"e": 3714,
"s": 3615,
"text": "Now, we just have to open our favorite web-browser at http://127.0.0.1:8050/ and check the result:"
},
{
"code": null,
"e": 3821,
"s": 3714,
"text": "Every time a slider moves, the app.callback function runs the python script to re-evaluate the prediction!"
},
{
"code": null,
"e": 3867,
"s": 3821,
"text": "The complete script is stored here on GitHub."
},
{
"code": null,
"e": 4190,
"s": 3867,
"text": "As you can imagine, it becomes a very powerful tool to have non-data-scientist teams interact with the model and understand its behavior. This is also a very good platform to test the model’s accuracy: operational teams will be able to check and confirm that the model’s behavior does correspond to their field experience."
},
{
"code": null,
"e": 4242,
"s": 4190,
"text": "A few recommendations before we close this article:"
},
{
"code": null,
"e": 4394,
"s": 4242,
"text": "If you are not familiar with Plotly and Dash, you should start by training yourself on standard Plotly charts (the steps are extremely well explained):"
},
{
"code": null,
"e": 4405,
"s": 4394,
"text": "plotly.com"
}
] |
Face landmarks detection with MediaPipe Facemesh | by Benson Ruan | Towards Data Science
|
Tensorflow.js released the MediaPipe Facemesh model in March, it is a lightweight machine learning pipeline predicting 486 3D facial landmarks to infer the approximate surface geometry of a human face.
During the pandemic time, I stay at home and play with this facemesh model. I would like to remind people of the importance of wearing a face mask. So I built a virtual face mask fitting room, which can detect face landmarks in an image or webcam stream, and put on the selected face mask on your face.
Try it yourself in the link below :
bensonruan.com
Wearing a face mask is a gesture of concern for one’s community. It prevent the wearer from inadvertently passing the disease along to others. The virtual face mask fitting room utilizes an advanced technique called Face Landmark Detection, which can identify human faces in an image or video stream.
If you are interested in building a face landmark detection app, please follow me below for the journey of how I implemented it.
First of all, simply include the script Tensorflow.js and its facemesh model in the <head> section of the html file.
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-core"></script><script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-converter"></script><script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/facemesh"></script>
Or you can install it via npm for use in a TypeScript / ES6 project
npm install @tensorflow-models/facemesh//import in jsconst facemesh = require('@tensorflow-models/facemesh');
The next thing we will need to do is to add the html <img> or <video> element as the source, so that we can perform face landmark detection on that image or webcam video stream.
<img id="faces" src="images/Donal_Thrump_White_House.jpg"><video id="webcam" autoplay playsinline width="640" height="480"></video>
To stream your webcam into the browser, I utilize the npm JavaScript module webcam-easy.js, which provides an easy to use module that can access webcam and take a photo. To find out more details about that, please refer to my previous blog :
medium.com
In order to perform face landmark detection, we first need to load the pre-trained Facemesh model, by calling the API of facemesh.load(modelParams). FaceMesh comes with a few optional parameters of the model:
maxContinuousChecks (default value : 5)
— How many frames to go without running the bounding box detector. Only relevant if maxFaces > 1
detectionConfidence (default value : 0.9)
— Threshold for discarding a prediction
maxFaces (default value : 10)
— The maximum number of faces detected in the input. Should be set to the minimum number for performance
iouThreshold (default value : 0.3)
— A float representing the threshold for deciding whether boxes overlap too much in non-maximum suppression. Must be between [0, 1]
scoreThreshold (default value : 0.75)
— A threshold for deciding when to remove boxes based on score in non-maximum suppression
facemesh.load().then(mdl => { model = mdl; console.log("model loaded"); cameraFrame = detectFaces();});
Next, we start to feed the image or webcam stream through the Facemesh model to perform face landmark detection, by calling the API of model.estimateFaces(inputElement). It takes an input image element (Can be a tensor, DOM element image, video, or canvas) and returns an array of facial landmark key points, bounding boxes and confidence level.
The estimateFaces API comes with a few parameters of the model:
input
— The image to classify. Can be a tensor, DOM element image, video, or canvas.
returnTensors (default value : false)
— Whether to return tensors as opposed to values
flipHorizontal (default value : false)
— Whether to flip/mirror the facial keypoints horizontally. Should be true for user facing webcam stream
let inputElement = isVideo? webcamElement : imageElement;let flipHorizontal = isVideo;model.estimateFaces(inputElement, false, flipHorizontal).then(predictions => { console.log(predictions); drawMask(predictions);});
Return of predictions would look like:
For each of the facial landmark key point, it contains the location of the x, y axis and depth.
0: Array(3) 0: 202.05661010742188 1: 207.98629760742188 2: -5.985757827758789 length: 3
In the above function, we get 468 face landmark key points. For our face mask application, I utilize 4 of those landmarks:
Forehead: 10
Left Cheek: 234
Chin: 152
Right Cheek: 454
Then we can use those key points to calculate where we should overlay the face mask PNG image. We need to calculate 3 numbers below:
The (x,y) location of the top-left corner for the mask image
The width of the mask image
The height of the mask image
Here is how I get the mask image with: use the Right Cheek landmark’s x axis value — Left Cheek landmark’s x axis value
maskWidth =(dots[rightCheekIndex].left - dots[leftCheekIndex].left);
For the height and top-left corner location, there is a difference between Half mask and Full mask.
Full Mask
— Top-left corner: {x: Forehead x axis value; y: Left Cheek y axis value}
— Height: [Chin y axis value] — [Forehead y axis value]
Half Mask
— Top-left corner: {x, y : Left landmark’s x,y axis value}
— Height: [Chin y axis value] — [Left Cheek y axis value]
switch(maskType) { case 'full': maskCoordinate= { top: dots[foreheadIndex].top, left: dots[leftCheekIndex].left}; maskHeight = (dots[chinIndex].top - dots[foreheadIndex].top) ; break; case 'half': maskCoordinate = dots[leftCheekIndex]; maskHeight = (dots[chinIndex].top - dots[leftCheekIndex].top) ; break;}
The last step is to overlay the face mask PNG image to the face.
maskElement = $("<img src='"+selectedMask.attr('src')+"' class='mask' />");maskElement.appendTo($("#canvas"));maskElement.css({ top: maskCoordinate.top, left: maskCoordinate.left, width: maskWidth , height: maskHeight, position:'absolute'});
That’s pretty much for the code! Now choose your favorite mask and try it on yourself!
You can download the complete code of the above demo in the link below:
github.c
Facemesh model is designed for front-facing cameras on mobile devices, where faces in view tend to occupy a relatively large fraction of the canvas. MediaPipe Facemesh may struggle to identify far-away faces.
With fears of spreading the coronavirus at the forefront of everyone’s minds, facial detection & recognition systems may be a safer, cleaner option than traditional bio-metric access control systems. This technology can not only reduce the risk of cross-infection but also improve traffic efficiency by more than 10 times, which will save time and reduce congestion.
At last, I wish everyone to stay healthy and stay at home during the pandemic, let’s utilize the latest machine learning technology to help us fight against the virus.
Thank you for reading. If you like this article, please share on Facebook or Twitter. Let me know in the comment if you have any questions. Follow me on GitHub and Linkedin.
|
[
{
"code": null,
"e": 373,
"s": 171,
"text": "Tensorflow.js released the MediaPipe Facemesh model in March, it is a lightweight machine learning pipeline predicting 486 3D facial landmarks to infer the approximate surface geometry of a human face."
},
{
"code": null,
"e": 676,
"s": 373,
"text": "During the pandemic time, I stay at home and play with this facemesh model. I would like to remind people of the importance of wearing a face mask. So I built a virtual face mask fitting room, which can detect face landmarks in an image or webcam stream, and put on the selected face mask on your face."
},
{
"code": null,
"e": 712,
"s": 676,
"text": "Try it yourself in the link below :"
},
{
"code": null,
"e": 727,
"s": 712,
"text": "bensonruan.com"
},
{
"code": null,
"e": 1028,
"s": 727,
"text": "Wearing a face mask is a gesture of concern for one’s community. It prevent the wearer from inadvertently passing the disease along to others. The virtual face mask fitting room utilizes an advanced technique called Face Landmark Detection, which can identify human faces in an image or video stream."
},
{
"code": null,
"e": 1157,
"s": 1028,
"text": "If you are interested in building a face landmark detection app, please follow me below for the journey of how I implemented it."
},
{
"code": null,
"e": 1274,
"s": 1157,
"text": "First of all, simply include the script Tensorflow.js and its facemesh model in the <head> section of the html file."
},
{
"code": null,
"e": 1508,
"s": 1274,
"text": "<script src=\"https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-core\"></script><script src=\"https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-converter\"></script><script src=\"https://cdn.jsdelivr.net/npm/@tensorflow-models/facemesh\"></script>"
},
{
"code": null,
"e": 1576,
"s": 1508,
"text": "Or you can install it via npm for use in a TypeScript / ES6 project"
},
{
"code": null,
"e": 1686,
"s": 1576,
"text": "npm install @tensorflow-models/facemesh//import in jsconst facemesh = require('@tensorflow-models/facemesh');"
},
{
"code": null,
"e": 1864,
"s": 1686,
"text": "The next thing we will need to do is to add the html <img> or <video> element as the source, so that we can perform face landmark detection on that image or webcam video stream."
},
{
"code": null,
"e": 1996,
"s": 1864,
"text": "<img id=\"faces\" src=\"images/Donal_Thrump_White_House.jpg\"><video id=\"webcam\" autoplay playsinline width=\"640\" height=\"480\"></video>"
},
{
"code": null,
"e": 2238,
"s": 1996,
"text": "To stream your webcam into the browser, I utilize the npm JavaScript module webcam-easy.js, which provides an easy to use module that can access webcam and take a photo. To find out more details about that, please refer to my previous blog :"
},
{
"code": null,
"e": 2249,
"s": 2238,
"text": "medium.com"
},
{
"code": null,
"e": 2458,
"s": 2249,
"text": "In order to perform face landmark detection, we first need to load the pre-trained Facemesh model, by calling the API of facemesh.load(modelParams). FaceMesh comes with a few optional parameters of the model:"
},
{
"code": null,
"e": 2498,
"s": 2458,
"text": "maxContinuousChecks (default value : 5)"
},
{
"code": null,
"e": 2595,
"s": 2498,
"text": "— How many frames to go without running the bounding box detector. Only relevant if maxFaces > 1"
},
{
"code": null,
"e": 2637,
"s": 2595,
"text": "detectionConfidence (default value : 0.9)"
},
{
"code": null,
"e": 2677,
"s": 2637,
"text": "— Threshold for discarding a prediction"
},
{
"code": null,
"e": 2707,
"s": 2677,
"text": "maxFaces (default value : 10)"
},
{
"code": null,
"e": 2812,
"s": 2707,
"text": "— The maximum number of faces detected in the input. Should be set to the minimum number for performance"
},
{
"code": null,
"e": 2847,
"s": 2812,
"text": "iouThreshold (default value : 0.3)"
},
{
"code": null,
"e": 2979,
"s": 2847,
"text": "— A float representing the threshold for deciding whether boxes overlap too much in non-maximum suppression. Must be between [0, 1]"
},
{
"code": null,
"e": 3017,
"s": 2979,
"text": "scoreThreshold (default value : 0.75)"
},
{
"code": null,
"e": 3107,
"s": 3017,
"text": "— A threshold for deciding when to remove boxes based on score in non-maximum suppression"
},
{
"code": null,
"e": 3222,
"s": 3107,
"text": "facemesh.load().then(mdl => { model = mdl; console.log(\"model loaded\"); cameraFrame = detectFaces();});"
},
{
"code": null,
"e": 3568,
"s": 3222,
"text": "Next, we start to feed the image or webcam stream through the Facemesh model to perform face landmark detection, by calling the API of model.estimateFaces(inputElement). It takes an input image element (Can be a tensor, DOM element image, video, or canvas) and returns an array of facial landmark key points, bounding boxes and confidence level."
},
{
"code": null,
"e": 3632,
"s": 3568,
"text": "The estimateFaces API comes with a few parameters of the model:"
},
{
"code": null,
"e": 3638,
"s": 3632,
"text": "input"
},
{
"code": null,
"e": 3717,
"s": 3638,
"text": "— The image to classify. Can be a tensor, DOM element image, video, or canvas."
},
{
"code": null,
"e": 3755,
"s": 3717,
"text": "returnTensors (default value : false)"
},
{
"code": null,
"e": 3804,
"s": 3755,
"text": "— Whether to return tensors as opposed to values"
},
{
"code": null,
"e": 3843,
"s": 3804,
"text": "flipHorizontal (default value : false)"
},
{
"code": null,
"e": 3948,
"s": 3843,
"text": "— Whether to flip/mirror the facial keypoints horizontally. Should be true for user facing webcam stream"
},
{
"code": null,
"e": 4171,
"s": 3948,
"text": "let inputElement = isVideo? webcamElement : imageElement;let flipHorizontal = isVideo;model.estimateFaces(inputElement, false, flipHorizontal).then(predictions => { console.log(predictions); drawMask(predictions);});"
},
{
"code": null,
"e": 4210,
"s": 4171,
"text": "Return of predictions would look like:"
},
{
"code": null,
"e": 4306,
"s": 4210,
"text": "For each of the facial landmark key point, it contains the location of the x, y axis and depth."
},
{
"code": null,
"e": 4406,
"s": 4306,
"text": "0: Array(3) 0: 202.05661010742188 1: 207.98629760742188 2: -5.985757827758789 length: 3"
},
{
"code": null,
"e": 4529,
"s": 4406,
"text": "In the above function, we get 468 face landmark key points. For our face mask application, I utilize 4 of those landmarks:"
},
{
"code": null,
"e": 4542,
"s": 4529,
"text": "Forehead: 10"
},
{
"code": null,
"e": 4558,
"s": 4542,
"text": "Left Cheek: 234"
},
{
"code": null,
"e": 4568,
"s": 4558,
"text": "Chin: 152"
},
{
"code": null,
"e": 4585,
"s": 4568,
"text": "Right Cheek: 454"
},
{
"code": null,
"e": 4718,
"s": 4585,
"text": "Then we can use those key points to calculate where we should overlay the face mask PNG image. We need to calculate 3 numbers below:"
},
{
"code": null,
"e": 4779,
"s": 4718,
"text": "The (x,y) location of the top-left corner for the mask image"
},
{
"code": null,
"e": 4807,
"s": 4779,
"text": "The width of the mask image"
},
{
"code": null,
"e": 4836,
"s": 4807,
"text": "The height of the mask image"
},
{
"code": null,
"e": 4956,
"s": 4836,
"text": "Here is how I get the mask image with: use the Right Cheek landmark’s x axis value — Left Cheek landmark’s x axis value"
},
{
"code": null,
"e": 5025,
"s": 4956,
"text": "maskWidth =(dots[rightCheekIndex].left - dots[leftCheekIndex].left);"
},
{
"code": null,
"e": 5125,
"s": 5025,
"text": "For the height and top-left corner location, there is a difference between Half mask and Full mask."
},
{
"code": null,
"e": 5135,
"s": 5125,
"text": "Full Mask"
},
{
"code": null,
"e": 5209,
"s": 5135,
"text": "— Top-left corner: {x: Forehead x axis value; y: Left Cheek y axis value}"
},
{
"code": null,
"e": 5265,
"s": 5209,
"text": "— Height: [Chin y axis value] — [Forehead y axis value]"
},
{
"code": null,
"e": 5275,
"s": 5265,
"text": "Half Mask"
},
{
"code": null,
"e": 5334,
"s": 5275,
"text": "— Top-left corner: {x, y : Left landmark’s x,y axis value}"
},
{
"code": null,
"e": 5392,
"s": 5334,
"text": "— Height: [Chin y axis value] — [Left Cheek y axis value]"
},
{
"code": null,
"e": 5720,
"s": 5392,
"text": "switch(maskType) { case 'full': maskCoordinate= { top: dots[foreheadIndex].top, left: dots[leftCheekIndex].left}; maskHeight = (dots[chinIndex].top - dots[foreheadIndex].top) ; break; case 'half': maskCoordinate = dots[leftCheekIndex]; maskHeight = (dots[chinIndex].top - dots[leftCheekIndex].top) ; break;}"
},
{
"code": null,
"e": 5785,
"s": 5720,
"text": "The last step is to overlay the face mask PNG image to the face."
},
{
"code": null,
"e": 6044,
"s": 5785,
"text": "maskElement = $(\"<img src='\"+selectedMask.attr('src')+\"' class='mask' />\");maskElement.appendTo($(\"#canvas\"));maskElement.css({ top: maskCoordinate.top, left: maskCoordinate.left, width: maskWidth , height: maskHeight, position:'absolute'});"
},
{
"code": null,
"e": 6131,
"s": 6044,
"text": "That’s pretty much for the code! Now choose your favorite mask and try it on yourself!"
},
{
"code": null,
"e": 6203,
"s": 6131,
"text": "You can download the complete code of the above demo in the link below:"
},
{
"code": null,
"e": 6212,
"s": 6203,
"text": "github.c"
},
{
"code": null,
"e": 6421,
"s": 6212,
"text": "Facemesh model is designed for front-facing cameras on mobile devices, where faces in view tend to occupy a relatively large fraction of the canvas. MediaPipe Facemesh may struggle to identify far-away faces."
},
{
"code": null,
"e": 6788,
"s": 6421,
"text": "With fears of spreading the coronavirus at the forefront of everyone’s minds, facial detection & recognition systems may be a safer, cleaner option than traditional bio-metric access control systems. This technology can not only reduce the risk of cross-infection but also improve traffic efficiency by more than 10 times, which will save time and reduce congestion."
},
{
"code": null,
"e": 6956,
"s": 6788,
"text": "At last, I wish everyone to stay healthy and stay at home during the pandemic, let’s utilize the latest machine learning technology to help us fight against the virus."
}
] |
Cognizant GenC Interview Experience 2021 - GeeksforGeeks
|
15 Mar, 2021
Round 1: Round 1 is an Aptitude round that is on the AMCAT Platform. This round consists of four sections namely.
Quantitative Aptitude (24 questions: 35 minutes)
Logical Reasoning (25 questions: 35 minutes)
Code debugging/Automata Fix (7 questions: 20 minutes)
Essay question (1 question: 15 minutes) Essay Topic was regarding which qualities you would prefer in a person while establishing a long-term friendship/Relationship.
Round 2: Based on your performance you are eligible for GenC Next Interview or GenC Interview, I am selected for GenC. Mostly if you can solve 6 questions correctly from the Automata Fix section out of 7 you are 90% sure to get selected for GenC Interview as this section is of utmost weightage.
The interview was scheduled on the AMCAT platform. In an interview, there are also divided into the section. These rounds are combined into one interview for about 40 minutes.
Whole Interview Process:
Tell me about yourself.After that he asked me about my projects from my resume as I have done my projects in ML :What is global minima?What is the learning rate?What is Hadoop?After that he give me a program to write on Editor (Language allowed : (C or Java)Program to print 100 odd numbers.CC#include <stdio.h> int main(){ int k = 1; for (int i = 0; i < 100;) { if (k % 2 != 0) { printf("%d ", k); i++; k++; } else { k++; } } return 0;}After that he asked me two aptitude questions.The first question from the Series pattern. It was a little difficult, but he gives me a hint from time to time.The second question from Averages.What quality you would prefer in-person while establishing a long-term friendship.After that he asked me do you have any questions?Are you comfortable with relocation?
Tell me about yourself.
Tell me about yourself.
After that he asked me about my projects from my resume as I have done my projects in ML :What is global minima?What is the learning rate?
After that he asked me about my projects from my resume as I have done my projects in ML :
What is global minima?
What is the learning rate?
What is Hadoop?
What is Hadoop?
After that he give me a program to write on Editor (Language allowed : (C or Java)Program to print 100 odd numbers.CC#include <stdio.h> int main(){ int k = 1; for (int i = 0; i < 100;) { if (k % 2 != 0) { printf("%d ", k); i++; k++; } else { k++; } } return 0;}
After that he give me a program to write on Editor (Language allowed : (C or Java)
Program to print 100 odd numbers.
C
#include <stdio.h> int main(){ int k = 1; for (int i = 0; i < 100;) { if (k % 2 != 0) { printf("%d ", k); i++; k++; } else { k++; } } return 0;}
After that he asked me two aptitude questions.The first question from the Series pattern. It was a little difficult, but he gives me a hint from time to time.The second question from Averages.
After that he asked me two aptitude questions.
The first question from the Series pattern. It was a little difficult, but he gives me a hint from time to time.
The second question from Averages.
What quality you would prefer in-person while establishing a long-term friendship.
What quality you would prefer in-person while establishing a long-term friendship.
After that he asked me do you have any questions?
After that he asked me do you have any questions?
Are you comfortable with relocation?
Are you comfortable with relocation?
After one month I get the news that I am selected for the internship with Cognizant from the training and placement department.
Cognizant
Cognizant-interview-experience
Marketing
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience
Microsoft Interview Experience for Internship (Via Engage)
Zoho Interview | Set 3 (Off-Campus)
Directi Interview | Set 7 (Programming Questions)
Amazon Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience for SDE-1
|
[
{
"code": null,
"e": 25494,
"s": 25466,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 25608,
"s": 25494,
"text": "Round 1: Round 1 is an Aptitude round that is on the AMCAT Platform. This round consists of four sections namely."
},
{
"code": null,
"e": 25657,
"s": 25608,
"text": "Quantitative Aptitude (24 questions: 35 minutes)"
},
{
"code": null,
"e": 25702,
"s": 25657,
"text": "Logical Reasoning (25 questions: 35 minutes)"
},
{
"code": null,
"e": 25756,
"s": 25702,
"text": "Code debugging/Automata Fix (7 questions: 20 minutes)"
},
{
"code": null,
"e": 25923,
"s": 25756,
"text": "Essay question (1 question: 15 minutes) Essay Topic was regarding which qualities you would prefer in a person while establishing a long-term friendship/Relationship."
},
{
"code": null,
"e": 26219,
"s": 25923,
"text": "Round 2: Based on your performance you are eligible for GenC Next Interview or GenC Interview, I am selected for GenC. Mostly if you can solve 6 questions correctly from the Automata Fix section out of 7 you are 90% sure to get selected for GenC Interview as this section is of utmost weightage."
},
{
"code": null,
"e": 26395,
"s": 26219,
"text": "The interview was scheduled on the AMCAT platform. In an interview, there are also divided into the section. These rounds are combined into one interview for about 40 minutes."
},
{
"code": null,
"e": 26420,
"s": 26395,
"text": "Whole Interview Process:"
},
{
"code": null,
"e": 27302,
"s": 26420,
"text": "Tell me about yourself.After that he asked me about my projects from my resume as I have done my projects in ML :What is global minima?What is the learning rate?What is Hadoop?After that he give me a program to write on Editor (Language allowed : (C or Java)Program to print 100 odd numbers.CC#include <stdio.h> int main(){ int k = 1; for (int i = 0; i < 100;) { if (k % 2 != 0) { printf(\"%d \", k); i++; k++; } else { k++; } } return 0;}After that he asked me two aptitude questions.The first question from the Series pattern. It was a little difficult, but he gives me a hint from time to time.The second question from Averages.What quality you would prefer in-person while establishing a long-term friendship.After that he asked me do you have any questions?Are you comfortable with relocation?"
},
{
"code": null,
"e": 27326,
"s": 27302,
"text": "Tell me about yourself."
},
{
"code": null,
"e": 27350,
"s": 27326,
"text": "Tell me about yourself."
},
{
"code": null,
"e": 27489,
"s": 27350,
"text": "After that he asked me about my projects from my resume as I have done my projects in ML :What is global minima?What is the learning rate?"
},
{
"code": null,
"e": 27580,
"s": 27489,
"text": "After that he asked me about my projects from my resume as I have done my projects in ML :"
},
{
"code": null,
"e": 27603,
"s": 27580,
"text": "What is global minima?"
},
{
"code": null,
"e": 27630,
"s": 27603,
"text": "What is the learning rate?"
},
{
"code": null,
"e": 27646,
"s": 27630,
"text": "What is Hadoop?"
},
{
"code": null,
"e": 27662,
"s": 27646,
"text": "What is Hadoop?"
},
{
"code": null,
"e": 28009,
"s": 27662,
"text": "After that he give me a program to write on Editor (Language allowed : (C or Java)Program to print 100 odd numbers.CC#include <stdio.h> int main(){ int k = 1; for (int i = 0; i < 100;) { if (k % 2 != 0) { printf(\"%d \", k); i++; k++; } else { k++; } } return 0;}"
},
{
"code": null,
"e": 28092,
"s": 28009,
"text": "After that he give me a program to write on Editor (Language allowed : (C or Java)"
},
{
"code": null,
"e": 28126,
"s": 28092,
"text": "Program to print 100 odd numbers."
},
{
"code": null,
"e": 28128,
"s": 28126,
"text": "C"
},
{
"code": "#include <stdio.h> int main(){ int k = 1; for (int i = 0; i < 100;) { if (k % 2 != 0) { printf(\"%d \", k); i++; k++; } else { k++; } } return 0;}",
"e": 28358,
"s": 28128,
"text": null
},
{
"code": null,
"e": 28551,
"s": 28358,
"text": "After that he asked me two aptitude questions.The first question from the Series pattern. It was a little difficult, but he gives me a hint from time to time.The second question from Averages."
},
{
"code": null,
"e": 28598,
"s": 28551,
"text": "After that he asked me two aptitude questions."
},
{
"code": null,
"e": 28711,
"s": 28598,
"text": "The first question from the Series pattern. It was a little difficult, but he gives me a hint from time to time."
},
{
"code": null,
"e": 28746,
"s": 28711,
"text": "The second question from Averages."
},
{
"code": null,
"e": 28829,
"s": 28746,
"text": "What quality you would prefer in-person while establishing a long-term friendship."
},
{
"code": null,
"e": 28912,
"s": 28829,
"text": "What quality you would prefer in-person while establishing a long-term friendship."
},
{
"code": null,
"e": 28962,
"s": 28912,
"text": "After that he asked me do you have any questions?"
},
{
"code": null,
"e": 29012,
"s": 28962,
"text": "After that he asked me do you have any questions?"
},
{
"code": null,
"e": 29049,
"s": 29012,
"text": "Are you comfortable with relocation?"
},
{
"code": null,
"e": 29086,
"s": 29049,
"text": "Are you comfortable with relocation?"
},
{
"code": null,
"e": 29214,
"s": 29086,
"text": "After one month I get the news that I am selected for the internship with Cognizant from the training and placement department."
},
{
"code": null,
"e": 29224,
"s": 29214,
"text": "Cognizant"
},
{
"code": null,
"e": 29255,
"s": 29224,
"text": "Cognizant-interview-experience"
},
{
"code": null,
"e": 29265,
"s": 29255,
"text": "Marketing"
},
{
"code": null,
"e": 29287,
"s": 29265,
"text": "Interview Experiences"
},
{
"code": null,
"e": 29385,
"s": 29287,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29435,
"s": 29385,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 29463,
"s": 29435,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 29522,
"s": 29463,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 29558,
"s": 29522,
"text": "Zoho Interview | Set 3 (Off-Campus)"
},
{
"code": null,
"e": 29608,
"s": 29558,
"text": "Directi Interview | Set 7 (Programming Questions)"
},
{
"code": null,
"e": 29646,
"s": 29608,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 29682,
"s": 29646,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 29728,
"s": 29682,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 29778,
"s": 29728,
"text": "Amazon Interview Experience for SDE-1(Off-Campus)"
}
] |
How to convert File into a Stream in Java?
|
Let’s say we have a file “input.txt” here in the directory E:/ with the following content:
Open a file with Bufferedreader. We have taken the above file here which is located at E: directory;
BufferedReader buffReader = Files.newBufferedReader(Paths.get("E:\\input.txt"),StandardCharsets.UTF_8);
Now get the stream of lines from the above file and display:
buffReader.lines().forEach(System.out::println);
The following is an example to convert File into a Stream in Java:
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Demo {
public static void main(String[] argv) throws Exception {
BufferedReader buffReader = Files.newBufferedReader(Paths.get("E:\\input.txt"), StandardCharsets.UTF_8);
System.out.println("Stream of lines...");
buffReader.lines().forEach(System.out::println);
}
}
Stream of lines...
Amit
Tom
David
Andre
Keemo
Gayle
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "Let’s say we have a file “input.txt” here in the directory E:/ with the following content:"
},
{
"code": null,
"e": 1254,
"s": 1153,
"text": "Open a file with Bufferedreader. We have taken the above file here which is located at E: directory;"
},
{
"code": null,
"e": 1358,
"s": 1254,
"text": "BufferedReader buffReader = Files.newBufferedReader(Paths.get(\"E:\\\\input.txt\"),StandardCharsets.UTF_8);"
},
{
"code": null,
"e": 1419,
"s": 1358,
"text": "Now get the stream of lines from the above file and display:"
},
{
"code": null,
"e": 1468,
"s": 1419,
"text": "buffReader.lines().forEach(System.out::println);"
},
{
"code": null,
"e": 1535,
"s": 1468,
"text": "The following is an example to convert File into a Stream in Java:"
},
{
"code": null,
"e": 1966,
"s": 1535,
"text": "import java.io.BufferedReader;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n BufferedReader buffReader = Files.newBufferedReader(Paths.get(\"E:\\\\input.txt\"), StandardCharsets.UTF_8);\n System.out.println(\"Stream of lines...\");\n buffReader.lines().forEach(System.out::println);\n }\n}"
},
{
"code": null,
"e": 2018,
"s": 1966,
"text": "Stream of lines...\nAmit\nTom\nDavid\nAndre\nKeemo\nGayle"
}
] |
The Anonymous Functions in Python
|
These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo
#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
|
[
{
"code": null,
"e": 1246,
"s": 1062,
"text": "These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions."
},
{
"code": null,
"e": 1402,
"s": 1246,
"text": "Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions."
},
{
"code": null,
"e": 1495,
"s": 1402,
"text": "An anonymous function cannot be a direct call to print because lambda requires an expression"
},
{
"code": null,
"e": 1647,
"s": 1495,
"text": "Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace."
},
{
"code": null,
"e": 1874,
"s": 1647,
"text": "Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons."
},
{
"code": null,
"e": 1961,
"s": 1874,
"text": "The syntax of lambda functions contains only a single statement, which is as follows −"
},
{
"code": null,
"e": 2004,
"s": 1961,
"text": "lambda [arg1 [,arg2,.....argn]]:expression"
},
{
"code": null,
"e": 2073,
"s": 2004,
"text": "Following is the example to show how lambda form of function works −"
},
{
"code": null,
"e": 2084,
"s": 2073,
"text": " Live Demo"
},
{
"code": null,
"e": 2289,
"s": 2084,
"text": "#!/usr/bin/python\n# Function definition is here\nsum = lambda arg1, arg2: arg1 + arg2;\n# Now you can call sum as a function\nprint \"Value of total : \", sum( 10, 20 )\nprint \"Value of total : \", sum( 20, 20 )"
},
{
"code": null,
"e": 2357,
"s": 2289,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2397,
"s": 2357,
"text": "Value of total : 30\nValue of total : 40"
}
] |
# and ## Operators in C - GeeksforGeeks
|
03 Dec, 2019
Stringizing operator (#)
This operator causes the corresponding actual argument to be enclosed in double quotation marks. The # operator, which is generally called the stringize operator, turns the argument it precedes into a quoted string. For more on pre-processor directives – refer thisExamples :
The following preprocessor turns the line printf(mkstr(geeksforgeeks)); into printf(“geeksforgeeks”);// CPP program to illustrate (#) operator#include <stdio.h>#define mkstr(s) #sint main(void){ printf(mkstr(geeksforgeeks)); return 0;}Output:geeksforgeeks
In this program, value of a is replaced by macro.// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define a 8.3297 int main(){ cout << "Value of a is " << a << endl; return 0;}Output:Value of a is 8.3297
This program finds out maximum out of two numbers using macro// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define MAX(i, j) (((i) > (j)) ? i : j) int main(){ int a, b; a = 250; b = 25; cout << "The maximum is " << MAX(a, b) << endl; return 0;}Output:The maximum is 250
The following preprocessor turns the line printf(mkstr(geeksforgeeks)); into printf(“geeksforgeeks”);// CPP program to illustrate (#) operator#include <stdio.h>#define mkstr(s) #sint main(void){ printf(mkstr(geeksforgeeks)); return 0;}Output:geeksforgeeks
// CPP program to illustrate (#) operator#include <stdio.h>#define mkstr(s) #sint main(void){ printf(mkstr(geeksforgeeks)); return 0;}
Output:
geeksforgeeks
In this program, value of a is replaced by macro.// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define a 8.3297 int main(){ cout << "Value of a is " << a << endl; return 0;}Output:Value of a is 8.3297
// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define a 8.3297 int main(){ cout << "Value of a is " << a << endl; return 0;}
Output:
Value of a is 8.3297
This program finds out maximum out of two numbers using macro// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define MAX(i, j) (((i) > (j)) ? i : j) int main(){ int a, b; a = 250; b = 25; cout << "The maximum is " << MAX(a, b) << endl; return 0;}Output:The maximum is 250
// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define MAX(i, j) (((i) > (j)) ? i : j) int main(){ int a, b; a = 250; b = 25; cout << "The maximum is " << MAX(a, b) << endl; return 0;}
Output:
The maximum is 250
Token-pasting operator (##)
Allows tokens used as actual arguments to be concatenated to form other tokens. It is often useful to merge two tokens into one while expanding macros. This is called token pasting or token concatenation. The ‘##’ pre-processing operator performs token pasting. When a macro is expanded, the two tokens on either side of each ‘##’ operator are combined into a single token, which then replaces the ‘##’ and the two original tokens in the macro expansion.Examples :
The preprocessor transforms printf(“%d”, concat(x, y)); into printf(“%d”, xy);// CPP program to illustrate (##) operator#include <stdio.h>#define concat(a, b) a##bint main(void){ int xy = 30; printf("%d", concat(x, y)); return 0;}Output:30
The preprocessor transforms printf(“%d”, concat(x, y)); into printf(“%d”, xy);// CPP program to illustrate (##) operator#include <stdio.h>#define concat(a, b) a##bint main(void){ int xy = 30; printf("%d", concat(x, y)); return 0;}Output:30
// CPP program to illustrate (##) operator#include <stdio.h>#define concat(a, b) a##bint main(void){ int xy = 30; printf("%d", concat(x, y)); return 0;}
Output:
30
Application: The ## provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed, and the result is re-scanned.
This article is contributed by Shivani Ghughtyal. 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.
shruti_sharma
C-Operators
cpp-operator
C Language
cpp-operator
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Structures in C
|
[
{
"code": null,
"e": 24021,
"s": 23993,
"text": "\n03 Dec, 2019"
},
{
"code": null,
"e": 24046,
"s": 24021,
"text": "Stringizing operator (#)"
},
{
"code": null,
"e": 24322,
"s": 24046,
"text": "This operator causes the corresponding actual argument to be enclosed in double quotation marks. The # operator, which is generally called the stringize operator, turns the argument it precedes into a quoted string. For more on pre-processor directives – refer thisExamples :"
},
{
"code": null,
"e": 25159,
"s": 24322,
"text": "The following preprocessor turns the line printf(mkstr(geeksforgeeks)); into printf(“geeksforgeeks”);// CPP program to illustrate (#) operator#include <stdio.h>#define mkstr(s) #sint main(void){ printf(mkstr(geeksforgeeks)); return 0;}Output:geeksforgeeks\nIn this program, value of a is replaced by macro.// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define a 8.3297 int main(){ cout << \"Value of a is \" << a << endl; return 0;}Output:Value of a is 8.3297\nThis program finds out maximum out of two numbers using macro// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define MAX(i, j) (((i) > (j)) ? i : j) int main(){ int a, b; a = 250; b = 25; cout << \"The maximum is \" << MAX(a, b) << endl; return 0;}Output:The maximum is 250\n"
},
{
"code": null,
"e": 25422,
"s": 25159,
"text": "The following preprocessor turns the line printf(mkstr(geeksforgeeks)); into printf(“geeksforgeeks”);// CPP program to illustrate (#) operator#include <stdio.h>#define mkstr(s) #sint main(void){ printf(mkstr(geeksforgeeks)); return 0;}Output:geeksforgeeks\n"
},
{
"code": "// CPP program to illustrate (#) operator#include <stdio.h>#define mkstr(s) #sint main(void){ printf(mkstr(geeksforgeeks)); return 0;}",
"e": 25563,
"s": 25422,
"text": null
},
{
"code": null,
"e": 25571,
"s": 25563,
"text": "Output:"
},
{
"code": null,
"e": 25586,
"s": 25571,
"text": "geeksforgeeks\n"
},
{
"code": null,
"e": 25833,
"s": 25586,
"text": "In this program, value of a is replaced by macro.// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define a 8.3297 int main(){ cout << \"Value of a is \" << a << endl; return 0;}Output:Value of a is 8.3297\n"
},
{
"code": "// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define a 8.3297 int main(){ cout << \"Value of a is \" << a << endl; return 0;}",
"e": 26003,
"s": 25833,
"text": null
},
{
"code": null,
"e": 26011,
"s": 26003,
"text": "Output:"
},
{
"code": null,
"e": 26033,
"s": 26011,
"text": "Value of a is 8.3297\n"
},
{
"code": null,
"e": 26362,
"s": 26033,
"text": "This program finds out maximum out of two numbers using macro// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define MAX(i, j) (((i) > (j)) ? i : j) int main(){ int a, b; a = 250; b = 25; cout << \"The maximum is \" << MAX(a, b) << endl; return 0;}Output:The maximum is 250\n"
},
{
"code": "// CPP program to illustrate (#) operator#include <iostream>using namespace std; #define MAX(i, j) (((i) > (j)) ? i : j) int main(){ int a, b; a = 250; b = 25; cout << \"The maximum is \" << MAX(a, b) << endl; return 0;}",
"e": 26604,
"s": 26362,
"text": null
},
{
"code": null,
"e": 26612,
"s": 26604,
"text": "Output:"
},
{
"code": null,
"e": 26632,
"s": 26612,
"text": "The maximum is 250\n"
},
{
"code": null,
"e": 26660,
"s": 26632,
"text": "Token-pasting operator (##)"
},
{
"code": null,
"e": 27125,
"s": 26660,
"text": "Allows tokens used as actual arguments to be concatenated to form other tokens. It is often useful to merge two tokens into one while expanding macros. This is called token pasting or token concatenation. The ‘##’ pre-processing operator performs token pasting. When a macro is expanded, the two tokens on either side of each ‘##’ operator are combined into a single token, which then replaces the ‘##’ and the two original tokens in the macro expansion.Examples :"
},
{
"code": null,
"e": 27375,
"s": 27125,
"text": "The preprocessor transforms printf(“%d”, concat(x, y)); into printf(“%d”, xy);// CPP program to illustrate (##) operator#include <stdio.h>#define concat(a, b) a##bint main(void){ int xy = 30; printf(\"%d\", concat(x, y)); return 0;}Output:30\n"
},
{
"code": null,
"e": 27625,
"s": 27375,
"text": "The preprocessor transforms printf(“%d”, concat(x, y)); into printf(“%d”, xy);// CPP program to illustrate (##) operator#include <stdio.h>#define concat(a, b) a##bint main(void){ int xy = 30; printf(\"%d\", concat(x, y)); return 0;}Output:30\n"
},
{
"code": "// CPP program to illustrate (##) operator#include <stdio.h>#define concat(a, b) a##bint main(void){ int xy = 30; printf(\"%d\", concat(x, y)); return 0;}",
"e": 27787,
"s": 27625,
"text": null
},
{
"code": null,
"e": 27795,
"s": 27787,
"text": "Output:"
},
{
"code": null,
"e": 27799,
"s": 27795,
"text": "30\n"
},
{
"code": null,
"e": 28078,
"s": 27799,
"text": "Application: The ## provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed, and the result is re-scanned."
},
{
"code": null,
"e": 28383,
"s": 28078,
"text": "This article is contributed by Shivani Ghughtyal. 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": 28508,
"s": 28383,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28522,
"s": 28508,
"text": "shruti_sharma"
},
{
"code": null,
"e": 28534,
"s": 28522,
"text": "C-Operators"
},
{
"code": null,
"e": 28547,
"s": 28534,
"text": "cpp-operator"
},
{
"code": null,
"e": 28558,
"s": 28547,
"text": "C Language"
},
{
"code": null,
"e": 28571,
"s": 28558,
"text": "cpp-operator"
},
{
"code": null,
"e": 28669,
"s": 28571,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28678,
"s": 28669,
"text": "Comments"
},
{
"code": null,
"e": 28691,
"s": 28678,
"text": "Old Comments"
},
{
"code": null,
"e": 28726,
"s": 28691,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28754,
"s": 28726,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28800,
"s": 28754,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28812,
"s": 28800,
"text": "fork() in C"
},
{
"code": null,
"e": 28844,
"s": 28812,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 28861,
"s": 28844,
"text": "Substring in C++"
},
{
"code": null,
"e": 28883,
"s": 28861,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 28930,
"s": 28883,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 28968,
"s": 28930,
"text": "TCP Server-Client implementation in C"
}
] |
End-to-End Time Series Analysis and Forecasting: a Trio of SARIMAX, LSTM and Prophet (Part 1) | by Bruce Nguyen | Towards Data Science
|
In collaboration with Alex Le.
Part 2: End-to-End Time Series Analysis and Forecasting: a Trio of SARIMAX, LSTM and Prophet (Part 2) | by Son Le | Dec, 2021 | Medium
Time series, or series of data points indexed in time order, is a ubiquitous type of data. Economists analyze economies by looking at how they performed in the past; weather forecasts are generated partly based on historical numbers, and so on. Any quantitative problem that concerns a temporal dimension, overall, will inevitably involve working with time-series data. Thus, time series analysis and forecasting has been an actively researched area, with tangible rewards promised for academics and businesses alike.
In this article, we will walk you through 3 of the most popular techniques/tools currently used to forecast a time series: a classical SARIMAX model, an LSTM neural network and Prophet. All the content will be based on our project mentioned above. Its scope is to analyze and predict the aggregate energy consumption level from a selected list of locations in the City of Helsinki. In particular, we will go through the post in this order:
The DataExploratory Data Analysis (EDA)Baseline ModelSARIMAXLSTMProphet
The Data
Exploratory Data Analysis (EDA)
Baseline Model
SARIMAX
LSTM
Prophet
For the more ‘hardcore’ viewers, you can get right into the code (commented, unfortunately :) ) in our notebooks on the project website.
We fetched the dataset from www.avoindata.fi, an open data repository maintained by the Finnish Digital and Population Data Services Agency. You can find it in the Energy category, titled ‘Energy consumption data of the City of Helsinki’s utility and service properties.’ On the dataset’s page, there is a link that takes you to the API documentation.
For our project, we used three years of daily and hourly data of electricity consumption from 2017–2020 exclusive. This is because we found that it is just the right amount of data for modeling — no need for older data, and the year 2020 itself has been a significant outlier in terms of energy consumption due to the pandemic — no need for newer data. Here is what the procured raw dataset roughly looks like:
Right away, we can see that there is a lot of redundant information, including the building addresses even. To get the aggregate energy consumption, the values along the locationName feature needs to be summed up. However, this process was complicated by how common missing values from locations are, implying the need for interpolation. Nevertheless, we arrived at the desired form of the data after some work (of course, you can see what we did in details in the notebooks):
That’s it for data preparation. Now we get to the fun part of visualizations!
By having a first overview of the data, we can already recognize the notable yearly (seasonal) electricity demand pattern, with peaks during winter-spring then bottoms out in summer. Our assumption can be checked further by looking at the data from each year.
The data behaves just as we expected, with an almost identical pattern across 3 years. That said, we can see some abnormalities in September 2018, where energy demand unexpectedly drops by a visible margin. Further investigations into this were carried out but with inconclusive results.
To go even further, we can zoom in on the data within every year, analyzing the patterns across the months, weeks and days.
Take the first two months of data in 2017 as an example. The repeating patterns here is very striking. By comparing them with the respective date, it is evident that the data has a 7-day seasonality — in other words, a weekly one. From the plot, we can see the energy consumption is at its height during the weekdays, then drops significantly during weekends. This very much fits our expectation, since factories and office operations, which consume a lot of energy, follow such a schedule.
Time Series Decomposition
Now that we get a better feel for the data, we will get more technical by using a statistical technique called time series decomposition. Conceptually, it works by dividing the time series into 3 components:
Trend-cycle — increases or decreases within the data in the long-term or not of a fixed frequency. Ex: energy demand goes up over time as there are more people and businesses.
Seasonal — pattern occurs when a time series is affected by seasonal factors. Ex: the weekly pattern that we just saw in the data.
Residuals — the remainder after removing the two aforementioned components. As every time series is inherently a stochastic process, there will always be random noises in the data. Ex: One building may have a few broken light bulbs, or some employees are sick, and the energy level thus fluctuates.
In particular, we used the Loess decomposition implemented in the class STL within the package statsmodels. For clarity, we only apply the decomposition on the data from one year:
stl = STL(ts2017,seasonal=7,robust=True)res = stl.fit()fig = res.plot()
It can be seen that the plot only further confirms our existing belief about the data. With the decomposition done, the exploratory phase comes to an end. Now, it’s modeling time!
In every modeling process, there needs to be a baseline model whose results can be used to assess our primary ones. In our case, we chose to use a Linear Regression model because of its simplicity and efficiency.
Regarding the modeling procedure itself, our test set composed all the data in December 2019. You may already have guessed that forecasting this time period would be very challenging due to the holiday season. And, worry not, this is precisely our intentions! We want to see just how the models handle exceptional times. And, a little challenge only makes things more interesting, isn’t it?
Without further ado, we get the forecasts from linear regression with a few lines of code:
Now we know that our models need to do better than an error of roughly 90,000 kWh!
To use this technique, we first need to know the basics.
What is SARIMAX?
Seasonal Auto-Regressive Integrated Moving Average with eXogenous factors, or SARIMAX, is an extension of the ARIMA class of models. Intuitively, ARIMA models compose 2 parts: the autoregressive term (AR) and the moving-average term (MA). The former views the value at one time just as a weighted sum of past values. The latter model that same value also as a weighted sum but of past residuals (confer. time series decomposition). There is also an integrated term (I) to difference the time series (we will discuss this further below). Since this is such a rich topic with a lot of math involved, we strongly recommend you to do further readings to have a better understanding.
Overall, ARIMA is a very decent type of models. However, the problem with this vanilla version is that it cannot handle seasonality — a big weakness. Comes SARIMA — the predecessor of SARIMAX. One shorthand notation for SARIMA models is:
where p = non-seasonal autoregressive (AR) order, d = non-seasonal differencing, q= non-seasonal moving average (MA) order, P = seasonal AR order, D = seasonal differencing, Q = seasonal MA order, and S = length of repeating seasonal pattern. We will use this notation from now on. By adding those seasonal AR and seasonal MA components, SARIMA solves the seasonality problem.
SARIMAX extends on this framework just by adding the capability to handle exogenous variables. Holidays is the go-to option, but you can also get your own domain-specific features if you need to. In our case, we fetched the list of holidays in Finland from the package holidays:
The SARIMAX implementation we use in the project also comes from the package statsmodels.
Lag
Lags are simply delays in time steps within a series. Consider a time index t, the lag 1 time index with respect to t is simply t-1, lag 2 is t-2, and so on.
Stationarity
A stationary time series is one that has its mean, variance and autocorrelation structure unchanging overtime. In other words, it does not have any cycle/trend or seasonality. The ARMA models family is actually built on this concept.
Autocorrelation function (ACF) and Partial Autocorrelation function (PACF)
Both of these functions measure how correlated the data at time t is to its past values t-1,t-2,... There is one crucial difference, however. The ACF also measures indirect correlation up to the lag in question, while PCAF does not. In practice, their plots are vital for many tasks, especially choosing the parameters for the SARIMAX model. You can read more about how to interpret such plots here.
With the basics out of the way, we proceed to model the time series using the Box-Jenkins procedure.
Differencing to achieve stationarity
We start by making sure that our data is stationary. Looking at the plots we made initially, it is evident that the data is not stationary with such a clear trend and seasonality. However, we can be more scientific with our guess by employing a statistical test: the Augmented Dickey-Fuller test, also implemented in the statsmodels package.
def test_stationarity(timeseries,maxlag): # Perform Dickey-Fuller test: print('Results of Dickey-Fuller Test:') dftest = adfuller(timeseries,maxlag=maxlag, autolag='AIC') dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used']) for key,value in dftest[4].items(): dfoutput['Critical Value (%s)'%key] = value print (round(dfoutput,3))
Just as expected, the p-value is bigger than 0.05. Thus, we cannot reject the null hypothesis, and the time series is not stationary. The question now is, “how do we make it so?” The answer in the procedure is differencing — represented by the d and D orders of the Integrated term. Differencing the data simply means to take the difference between the data points and its lagged version. Intuitively, this is analogous to taking the derivatives of functions.
This looks more like it! We turn to the Dickey-Fuller test again for verification.
Perfect! Now we know the parameters for the Integrated terms in SARIMAX: 1 for both seasonal and non-seasonal ones. The next step in the modeling process is finding the order for the AR and MA terms using ACF and PACF plots.
Identify p and q using ACF and PACF plots
In the plots, we can find intricate autocorrelation patterns with no clear-cut interpretations. Thus, orders for both seasonal and non-seasonal AR and MA terms cannot be decisively chosen, complicating our process. This demonstrates how real-life statistics can be much messier than textbook examples, and we have to make do with the uncertainty of our own choices. Fortunately, we can avoid any unscientific guessing by employing an optimization method called Grid Search.
Grid Search
This algorithm simply conduct an exhaustive search over all the combinations of parameters. The best one among all of them will be chosen according to a loss function of our choice. In our case, we use the popular Akaike Information Criterion (AIC) as per the standard in the ARMA modeling process.
def sarimax(ts,exo,all_param): results = [] for param in all_param: try: mod = SARIMAX(ts, exog = exo, order=param[0], seasonal_order=param[1]) res = mod.fit() results.append((res,res.aic,param)) print('Tried out SARIMAX{}x{} - AIC:{}'.format(param[0], param[1], round(res.aic,2))) except Exception as e: print(e) continue return results# set parameter rangep,d,q = range(0,3),[1],range(0,3)P,D,Q,s = range(0,3),[1],range(0,3),[7]# list of all parameter combospdq = list(itertools.product(p, d, q))seasonal_pdq = list(itertools.product(P, D, Q, s))all_param = list(itertools.product(pdq,seasonal_pdq))all_res = sarimax(train,exo_train,all_param)
We end up with our top 5 models after the search:
And right away, we can use the first set of parameters. Even though the parsimony principle (sum of parameters < 6) is violated for this model, the margin is small enough, and we can gain from some flexibility.
Residual Diagnostics
To determine the goodness of fit of the model, we can examine its residuals using the standard assumption: they should be normally distributed around 0, or in other words, white noise.
We can check this by looking at the various plots showing the distribution of the residuals. This can be generated conveniently using the plot_diagnostics method. In addition, the Ljung-Box test can also be used to do this more precisely.
res.plot_diagnostics(figsize=(15, 12))plt.show()print("Ljung-box p-values:\n" + str(res.test_serial_correlation(method='ljungbox')[0][1]))res.summary()
In the plots, the residuals seem to be normally distributed around 0 — which is the condition that we need — with slightly heavy tails. However, looking at the Ljung box statistics, we cannot reject the hypothesis that the data are not independently distributed, since the p-values are smaller than α=0.05 for some lags from 6 onwards.
Nevertheless, let us use this model to predict on the test set and judge it for ourselves.
fig, ax = plt.subplots(figsize=(12,7))ax.set(title='Energy consumption', ylabel='kWh')ts.plot(ax=ax, style = 'o')pred.predicted_mean.plot(ax=ax, style='o')ci = pred_ci.loc[demo_start:]ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color='r', alpha=0.1)
Overall, the in-sample prediction seems to fit the time series pretty well! There is no notable pattern of error, except that the model seems to predict the energy level during weekdays better than that of the weekends. Now, let’s see how it forecasts on the test set:
The out-sample prediction also looks also very satisfactory! During the first 2 weeks of the month, the forecasted values fit the actual ones well, with no systematic error in prediction. There is, however, possibly an exception, with the values on the 6th of December being wildly incorrect. Fortunately, we know the simple reason for it: it was the Independence day of Finland.
With regards to the winter holiday season, the model unfortunately did not do as well. During the period, the forecasts consistently over-predicted the electricity consumption, despite the addition of the exogenous ‘holidays’ variable. Apparently, not only the Christmas holidays saw the energy dropping, but the whole winter holidays period as well. And, that information is not incorporated in the model. This explains why the error rate remains very high — not much of an improvement over the baseline model.
We redid the process again behind the scenes with a different split of train-test, and the results expectedly got much better. The error rate dropped to around 30,000 kWh or less than 5%. Not so bad for a class of model theorized 50 years ago, right? Nevertheless, all of this shows the challenges of forecasting during exceptional periods, emphasizing the need for even better techniques. Aside from that, this model still shows promise in forecasting when the data behaves predictably.
Oops... This post has gotten too long already! Also, this seems like a good place to stop, with all the SARIMAX deployment covered. In the next post, we will get to the ‘modern’ section of the Time Series Analysis textbook, so to speak. We will discover the process of fitting time series with Prophet. That said, thank you very much for getting this far through walls of text :). See you next time!
Part 2: End-to-End Time Series Analysis and Forecasting: a Trio of SARIMAX, LSTM and Prophet (Part 2) | by Son Le | Dec, 2021 | Medium
P/S: Again, for the interested viewers out there craving for more future-predicting, you can see all the code as well as the more technical comments in our notebooks on the project website.
|
[
{
"code": null,
"e": 202,
"s": 171,
"text": "In collaboration with Alex Le."
},
{
"code": null,
"e": 337,
"s": 202,
"text": "Part 2: End-to-End Time Series Analysis and Forecasting: a Trio of SARIMAX, LSTM and Prophet (Part 2) | by Son Le | Dec, 2021 | Medium"
},
{
"code": null,
"e": 855,
"s": 337,
"text": "Time series, or series of data points indexed in time order, is a ubiquitous type of data. Economists analyze economies by looking at how they performed in the past; weather forecasts are generated partly based on historical numbers, and so on. Any quantitative problem that concerns a temporal dimension, overall, will inevitably involve working with time-series data. Thus, time series analysis and forecasting has been an actively researched area, with tangible rewards promised for academics and businesses alike."
},
{
"code": null,
"e": 1295,
"s": 855,
"text": "In this article, we will walk you through 3 of the most popular techniques/tools currently used to forecast a time series: a classical SARIMAX model, an LSTM neural network and Prophet. All the content will be based on our project mentioned above. Its scope is to analyze and predict the aggregate energy consumption level from a selected list of locations in the City of Helsinki. In particular, we will go through the post in this order:"
},
{
"code": null,
"e": 1367,
"s": 1295,
"text": "The DataExploratory Data Analysis (EDA)Baseline ModelSARIMAXLSTMProphet"
},
{
"code": null,
"e": 1376,
"s": 1367,
"text": "The Data"
},
{
"code": null,
"e": 1408,
"s": 1376,
"text": "Exploratory Data Analysis (EDA)"
},
{
"code": null,
"e": 1423,
"s": 1408,
"text": "Baseline Model"
},
{
"code": null,
"e": 1431,
"s": 1423,
"text": "SARIMAX"
},
{
"code": null,
"e": 1436,
"s": 1431,
"text": "LSTM"
},
{
"code": null,
"e": 1444,
"s": 1436,
"text": "Prophet"
},
{
"code": null,
"e": 1581,
"s": 1444,
"text": "For the more ‘hardcore’ viewers, you can get right into the code (commented, unfortunately :) ) in our notebooks on the project website."
},
{
"code": null,
"e": 1933,
"s": 1581,
"text": "We fetched the dataset from www.avoindata.fi, an open data repository maintained by the Finnish Digital and Population Data Services Agency. You can find it in the Energy category, titled ‘Energy consumption data of the City of Helsinki’s utility and service properties.’ On the dataset’s page, there is a link that takes you to the API documentation."
},
{
"code": null,
"e": 2344,
"s": 1933,
"text": "For our project, we used three years of daily and hourly data of electricity consumption from 2017–2020 exclusive. This is because we found that it is just the right amount of data for modeling — no need for older data, and the year 2020 itself has been a significant outlier in terms of energy consumption due to the pandemic — no need for newer data. Here is what the procured raw dataset roughly looks like:"
},
{
"code": null,
"e": 2821,
"s": 2344,
"text": "Right away, we can see that there is a lot of redundant information, including the building addresses even. To get the aggregate energy consumption, the values along the locationName feature needs to be summed up. However, this process was complicated by how common missing values from locations are, implying the need for interpolation. Nevertheless, we arrived at the desired form of the data after some work (of course, you can see what we did in details in the notebooks):"
},
{
"code": null,
"e": 2899,
"s": 2821,
"text": "That’s it for data preparation. Now we get to the fun part of visualizations!"
},
{
"code": null,
"e": 3159,
"s": 2899,
"text": "By having a first overview of the data, we can already recognize the notable yearly (seasonal) electricity demand pattern, with peaks during winter-spring then bottoms out in summer. Our assumption can be checked further by looking at the data from each year."
},
{
"code": null,
"e": 3447,
"s": 3159,
"text": "The data behaves just as we expected, with an almost identical pattern across 3 years. That said, we can see some abnormalities in September 2018, where energy demand unexpectedly drops by a visible margin. Further investigations into this were carried out but with inconclusive results."
},
{
"code": null,
"e": 3571,
"s": 3447,
"text": "To go even further, we can zoom in on the data within every year, analyzing the patterns across the months, weeks and days."
},
{
"code": null,
"e": 4062,
"s": 3571,
"text": "Take the first two months of data in 2017 as an example. The repeating patterns here is very striking. By comparing them with the respective date, it is evident that the data has a 7-day seasonality — in other words, a weekly one. From the plot, we can see the energy consumption is at its height during the weekdays, then drops significantly during weekends. This very much fits our expectation, since factories and office operations, which consume a lot of energy, follow such a schedule."
},
{
"code": null,
"e": 4088,
"s": 4062,
"text": "Time Series Decomposition"
},
{
"code": null,
"e": 4296,
"s": 4088,
"text": "Now that we get a better feel for the data, we will get more technical by using a statistical technique called time series decomposition. Conceptually, it works by dividing the time series into 3 components:"
},
{
"code": null,
"e": 4472,
"s": 4296,
"text": "Trend-cycle — increases or decreases within the data in the long-term or not of a fixed frequency. Ex: energy demand goes up over time as there are more people and businesses."
},
{
"code": null,
"e": 4603,
"s": 4472,
"text": "Seasonal — pattern occurs when a time series is affected by seasonal factors. Ex: the weekly pattern that we just saw in the data."
},
{
"code": null,
"e": 4902,
"s": 4603,
"text": "Residuals — the remainder after removing the two aforementioned components. As every time series is inherently a stochastic process, there will always be random noises in the data. Ex: One building may have a few broken light bulbs, or some employees are sick, and the energy level thus fluctuates."
},
{
"code": null,
"e": 5082,
"s": 4902,
"text": "In particular, we used the Loess decomposition implemented in the class STL within the package statsmodels. For clarity, we only apply the decomposition on the data from one year:"
},
{
"code": null,
"e": 5154,
"s": 5082,
"text": "stl = STL(ts2017,seasonal=7,robust=True)res = stl.fit()fig = res.plot()"
},
{
"code": null,
"e": 5334,
"s": 5154,
"text": "It can be seen that the plot only further confirms our existing belief about the data. With the decomposition done, the exploratory phase comes to an end. Now, it’s modeling time!"
},
{
"code": null,
"e": 5547,
"s": 5334,
"text": "In every modeling process, there needs to be a baseline model whose results can be used to assess our primary ones. In our case, we chose to use a Linear Regression model because of its simplicity and efficiency."
},
{
"code": null,
"e": 5938,
"s": 5547,
"text": "Regarding the modeling procedure itself, our test set composed all the data in December 2019. You may already have guessed that forecasting this time period would be very challenging due to the holiday season. And, worry not, this is precisely our intentions! We want to see just how the models handle exceptional times. And, a little challenge only makes things more interesting, isn’t it?"
},
{
"code": null,
"e": 6029,
"s": 5938,
"text": "Without further ado, we get the forecasts from linear regression with a few lines of code:"
},
{
"code": null,
"e": 6112,
"s": 6029,
"text": "Now we know that our models need to do better than an error of roughly 90,000 kWh!"
},
{
"code": null,
"e": 6169,
"s": 6112,
"text": "To use this technique, we first need to know the basics."
},
{
"code": null,
"e": 6186,
"s": 6169,
"text": "What is SARIMAX?"
},
{
"code": null,
"e": 6865,
"s": 6186,
"text": "Seasonal Auto-Regressive Integrated Moving Average with eXogenous factors, or SARIMAX, is an extension of the ARIMA class of models. Intuitively, ARIMA models compose 2 parts: the autoregressive term (AR) and the moving-average term (MA). The former views the value at one time just as a weighted sum of past values. The latter model that same value also as a weighted sum but of past residuals (confer. time series decomposition). There is also an integrated term (I) to difference the time series (we will discuss this further below). Since this is such a rich topic with a lot of math involved, we strongly recommend you to do further readings to have a better understanding."
},
{
"code": null,
"e": 7103,
"s": 6865,
"text": "Overall, ARIMA is a very decent type of models. However, the problem with this vanilla version is that it cannot handle seasonality — a big weakness. Comes SARIMA — the predecessor of SARIMAX. One shorthand notation for SARIMA models is:"
},
{
"code": null,
"e": 7480,
"s": 7103,
"text": "where p = non-seasonal autoregressive (AR) order, d = non-seasonal differencing, q= non-seasonal moving average (MA) order, P = seasonal AR order, D = seasonal differencing, Q = seasonal MA order, and S = length of repeating seasonal pattern. We will use this notation from now on. By adding those seasonal AR and seasonal MA components, SARIMA solves the seasonality problem."
},
{
"code": null,
"e": 7759,
"s": 7480,
"text": "SARIMAX extends on this framework just by adding the capability to handle exogenous variables. Holidays is the go-to option, but you can also get your own domain-specific features if you need to. In our case, we fetched the list of holidays in Finland from the package holidays:"
},
{
"code": null,
"e": 7849,
"s": 7759,
"text": "The SARIMAX implementation we use in the project also comes from the package statsmodels."
},
{
"code": null,
"e": 7853,
"s": 7849,
"text": "Lag"
},
{
"code": null,
"e": 8011,
"s": 7853,
"text": "Lags are simply delays in time steps within a series. Consider a time index t, the lag 1 time index with respect to t is simply t-1, lag 2 is t-2, and so on."
},
{
"code": null,
"e": 8024,
"s": 8011,
"text": "Stationarity"
},
{
"code": null,
"e": 8258,
"s": 8024,
"text": "A stationary time series is one that has its mean, variance and autocorrelation structure unchanging overtime. In other words, it does not have any cycle/trend or seasonality. The ARMA models family is actually built on this concept."
},
{
"code": null,
"e": 8333,
"s": 8258,
"text": "Autocorrelation function (ACF) and Partial Autocorrelation function (PACF)"
},
{
"code": null,
"e": 8733,
"s": 8333,
"text": "Both of these functions measure how correlated the data at time t is to its past values t-1,t-2,... There is one crucial difference, however. The ACF also measures indirect correlation up to the lag in question, while PCAF does not. In practice, their plots are vital for many tasks, especially choosing the parameters for the SARIMAX model. You can read more about how to interpret such plots here."
},
{
"code": null,
"e": 8834,
"s": 8733,
"text": "With the basics out of the way, we proceed to model the time series using the Box-Jenkins procedure."
},
{
"code": null,
"e": 8871,
"s": 8834,
"text": "Differencing to achieve stationarity"
},
{
"code": null,
"e": 9213,
"s": 8871,
"text": "We start by making sure that our data is stationary. Looking at the plots we made initially, it is evident that the data is not stationary with such a clear trend and seasonality. However, we can be more scientific with our guess by employing a statistical test: the Augmented Dickey-Fuller test, also implemented in the statsmodels package."
},
{
"code": null,
"e": 9649,
"s": 9213,
"text": "def test_stationarity(timeseries,maxlag): # Perform Dickey-Fuller test: print('Results of Dickey-Fuller Test:') dftest = adfuller(timeseries,maxlag=maxlag, autolag='AIC') dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used']) for key,value in dftest[4].items(): dfoutput['Critical Value (%s)'%key] = value print (round(dfoutput,3))"
},
{
"code": null,
"e": 10109,
"s": 9649,
"text": "Just as expected, the p-value is bigger than 0.05. Thus, we cannot reject the null hypothesis, and the time series is not stationary. The question now is, “how do we make it so?” The answer in the procedure is differencing — represented by the d and D orders of the Integrated term. Differencing the data simply means to take the difference between the data points and its lagged version. Intuitively, this is analogous to taking the derivatives of functions."
},
{
"code": null,
"e": 10192,
"s": 10109,
"text": "This looks more like it! We turn to the Dickey-Fuller test again for verification."
},
{
"code": null,
"e": 10417,
"s": 10192,
"text": "Perfect! Now we know the parameters for the Integrated terms in SARIMAX: 1 for both seasonal and non-seasonal ones. The next step in the modeling process is finding the order for the AR and MA terms using ACF and PACF plots."
},
{
"code": null,
"e": 10459,
"s": 10417,
"text": "Identify p and q using ACF and PACF plots"
},
{
"code": null,
"e": 10933,
"s": 10459,
"text": "In the plots, we can find intricate autocorrelation patterns with no clear-cut interpretations. Thus, orders for both seasonal and non-seasonal AR and MA terms cannot be decisively chosen, complicating our process. This demonstrates how real-life statistics can be much messier than textbook examples, and we have to make do with the uncertainty of our own choices. Fortunately, we can avoid any unscientific guessing by employing an optimization method called Grid Search."
},
{
"code": null,
"e": 10945,
"s": 10933,
"text": "Grid Search"
},
{
"code": null,
"e": 11244,
"s": 10945,
"text": "This algorithm simply conduct an exhaustive search over all the combinations of parameters. The best one among all of them will be chosen according to a loss function of our choice. In our case, we use the popular Akaike Information Criterion (AIC) as per the standard in the ARMA modeling process."
},
{
"code": null,
"e": 12066,
"s": 11244,
"text": "def sarimax(ts,exo,all_param): results = [] for param in all_param: try: mod = SARIMAX(ts, exog = exo, order=param[0], seasonal_order=param[1]) res = mod.fit() results.append((res,res.aic,param)) print('Tried out SARIMAX{}x{} - AIC:{}'.format(param[0], param[1], round(res.aic,2))) except Exception as e: print(e) continue return results# set parameter rangep,d,q = range(0,3),[1],range(0,3)P,D,Q,s = range(0,3),[1],range(0,3),[7]# list of all parameter combospdq = list(itertools.product(p, d, q))seasonal_pdq = list(itertools.product(P, D, Q, s))all_param = list(itertools.product(pdq,seasonal_pdq))all_res = sarimax(train,exo_train,all_param)"
},
{
"code": null,
"e": 12116,
"s": 12066,
"text": "We end up with our top 5 models after the search:"
},
{
"code": null,
"e": 12327,
"s": 12116,
"text": "And right away, we can use the first set of parameters. Even though the parsimony principle (sum of parameters < 6) is violated for this model, the margin is small enough, and we can gain from some flexibility."
},
{
"code": null,
"e": 12348,
"s": 12327,
"text": "Residual Diagnostics"
},
{
"code": null,
"e": 12533,
"s": 12348,
"text": "To determine the goodness of fit of the model, we can examine its residuals using the standard assumption: they should be normally distributed around 0, or in other words, white noise."
},
{
"code": null,
"e": 12772,
"s": 12533,
"text": "We can check this by looking at the various plots showing the distribution of the residuals. This can be generated conveniently using the plot_diagnostics method. In addition, the Ljung-Box test can also be used to do this more precisely."
},
{
"code": null,
"e": 12924,
"s": 12772,
"text": "res.plot_diagnostics(figsize=(15, 12))plt.show()print(\"Ljung-box p-values:\\n\" + str(res.test_serial_correlation(method='ljungbox')[0][1]))res.summary()"
},
{
"code": null,
"e": 13260,
"s": 12924,
"text": "In the plots, the residuals seem to be normally distributed around 0 — which is the condition that we need — with slightly heavy tails. However, looking at the Ljung box statistics, we cannot reject the hypothesis that the data are not independently distributed, since the p-values are smaller than α=0.05 for some lags from 6 onwards."
},
{
"code": null,
"e": 13351,
"s": 13260,
"text": "Nevertheless, let us use this model to predict on the test set and judge it for ourselves."
},
{
"code": null,
"e": 13611,
"s": 13351,
"text": "fig, ax = plt.subplots(figsize=(12,7))ax.set(title='Energy consumption', ylabel='kWh')ts.plot(ax=ax, style = 'o')pred.predicted_mean.plot(ax=ax, style='o')ci = pred_ci.loc[demo_start:]ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color='r', alpha=0.1)"
},
{
"code": null,
"e": 13880,
"s": 13611,
"text": "Overall, the in-sample prediction seems to fit the time series pretty well! There is no notable pattern of error, except that the model seems to predict the energy level during weekdays better than that of the weekends. Now, let’s see how it forecasts on the test set:"
},
{
"code": null,
"e": 14260,
"s": 13880,
"text": "The out-sample prediction also looks also very satisfactory! During the first 2 weeks of the month, the forecasted values fit the actual ones well, with no systematic error in prediction. There is, however, possibly an exception, with the values on the 6th of December being wildly incorrect. Fortunately, we know the simple reason for it: it was the Independence day of Finland."
},
{
"code": null,
"e": 14772,
"s": 14260,
"text": "With regards to the winter holiday season, the model unfortunately did not do as well. During the period, the forecasts consistently over-predicted the electricity consumption, despite the addition of the exogenous ‘holidays’ variable. Apparently, not only the Christmas holidays saw the energy dropping, but the whole winter holidays period as well. And, that information is not incorporated in the model. This explains why the error rate remains very high — not much of an improvement over the baseline model."
},
{
"code": null,
"e": 15260,
"s": 14772,
"text": "We redid the process again behind the scenes with a different split of train-test, and the results expectedly got much better. The error rate dropped to around 30,000 kWh or less than 5%. Not so bad for a class of model theorized 50 years ago, right? Nevertheless, all of this shows the challenges of forecasting during exceptional periods, emphasizing the need for even better techniques. Aside from that, this model still shows promise in forecasting when the data behaves predictably."
},
{
"code": null,
"e": 15660,
"s": 15260,
"text": "Oops... This post has gotten too long already! Also, this seems like a good place to stop, with all the SARIMAX deployment covered. In the next post, we will get to the ‘modern’ section of the Time Series Analysis textbook, so to speak. We will discover the process of fitting time series with Prophet. That said, thank you very much for getting this far through walls of text :). See you next time!"
},
{
"code": null,
"e": 15795,
"s": 15660,
"text": "Part 2: End-to-End Time Series Analysis and Forecasting: a Trio of SARIMAX, LSTM and Prophet (Part 2) | by Son Le | Dec, 2021 | Medium"
}
] |
How to loop through a menu list on a webpage using Selenium?
|
We can loop through a menu list on a webpage using Selenium webdriver.
In a webpage, a list is represented by an ul tag and it consists of elements with li tag. Thus the li tag can be said as the child of ul.
First, we have to identify the element with ul tag with any locator, then traverse through its li sub-elements with the help of a loop. Finally, use the method getText to obtain the text on the li elements.
Let us try to identify the menu list on a webpage.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class MenuItemLst{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify elements in menu with findElements
List<WebElement> p = driver.
findElements(By.xpath("//ul[@class='toc reading']/li"));
System.out.println("Menu Items are: ");
//iterate through list
for( WebElement i: p){
System.out.println(i.getText());
driver.quit();}
}
}
}
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "We can loop through a menu list on a webpage using Selenium webdriver."
},
{
"code": null,
"e": 1271,
"s": 1133,
"text": "In a webpage, a list is represented by an ul tag and it consists of elements with li tag. Thus the li tag can be said as the child of ul."
},
{
"code": null,
"e": 1478,
"s": 1271,
"text": "First, we have to identify the element with ul tag with any locator, then traverse through its li sub-elements with the help of a loop. Finally, use the method getText to obtain the text on the li elements."
},
{
"code": null,
"e": 1529,
"s": 1478,
"text": "Let us try to identify the menu list on a webpage."
},
{
"code": null,
"e": 2503,
"s": 1529,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\npublic class MenuItemLst{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify elements in menu with findElements\n List<WebElement> p = driver.\n findElements(By.xpath(\"//ul[@class='toc reading']/li\"));\n System.out.println(\"Menu Items are: \");\n //iterate through list\n for( WebElement i: p){\n System.out.println(i.getText());\n driver.quit();}\n }\n }\n}"
}
] |
How to create default function parameter in PHP? - GeeksforGeeks
|
15 May, 2020
The default parameter concept comes from C++ style default argument values, same as in PHP you can provide default parameters so that when a parameter is not passed to the function. Then it is still available within the function with a pre-defined value. This function also can be called optional parameter.
Syntax:
function greeting($name=" parameter_value ")
Parameter: This function accepts a single parameter that is $name here, holds the parameter value.
Below examples illustrate the procedure to create and use the default function parameter:Example 1:
<?php function greeting($name="GeeksforGeeks") { echo "Welcome to $name "; echo("\n"); } greeting("Gfg"); // Passing no value greeting(); greeting("A Computer Science Portal"); ?>
Output:
Welcome to Gfg
Welcome to GeeksforGeeks
Welcome to A Computer Science Portal
Example 2:
<?php function welcome($first="GeeksforGeeks", $last="A Computer Science Portal for Geeks") { echo "Greeting: $first $last"; echo("\n"); } welcome(); welcome("night_fury"); welcome("night_fury","Contributer"); ?>
Output:
Greeting: GeeksforGeeks A Computer Science Portal for Geeks
Greeting: night_fury A Computer Science Portal for Geeks
Greeting: night_fury Contributer
PHP-basics
Picked
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 32651,
"s": 32623,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 32959,
"s": 32651,
"text": "The default parameter concept comes from C++ style default argument values, same as in PHP you can provide default parameters so that when a parameter is not passed to the function. Then it is still available within the function with a pre-defined value. This function also can be called optional parameter."
},
{
"code": null,
"e": 32967,
"s": 32959,
"text": "Syntax:"
},
{
"code": null,
"e": 33012,
"s": 32967,
"text": "function greeting($name=\" parameter_value \")"
},
{
"code": null,
"e": 33111,
"s": 33012,
"text": "Parameter: This function accepts a single parameter that is $name here, holds the parameter value."
},
{
"code": null,
"e": 33211,
"s": 33111,
"text": "Below examples illustrate the procedure to create and use the default function parameter:Example 1:"
},
{
"code": "<?php function greeting($name=\"GeeksforGeeks\") { echo \"Welcome to $name \"; echo(\"\\n\"); } greeting(\"Gfg\"); // Passing no value greeting(); greeting(\"A Computer Science Portal\"); ?> ",
"e": 33442,
"s": 33211,
"text": null
},
{
"code": null,
"e": 33450,
"s": 33442,
"text": "Output:"
},
{
"code": null,
"e": 33530,
"s": 33450,
"text": "Welcome to Gfg \nWelcome to GeeksforGeeks \nWelcome to A Computer Science Portal "
},
{
"code": null,
"e": 33541,
"s": 33530,
"text": "Example 2:"
},
{
"code": "<?php function welcome($first=\"GeeksforGeeks\", $last=\"A Computer Science Portal for Geeks\") { echo \"Greeting: $first $last\"; echo(\"\\n\"); } welcome(); welcome(\"night_fury\"); welcome(\"night_fury\",\"Contributer\"); ?> ",
"e": 33879,
"s": 33541,
"text": null
},
{
"code": null,
"e": 33887,
"s": 33879,
"text": "Output:"
},
{
"code": null,
"e": 34037,
"s": 33887,
"text": "Greeting: GeeksforGeeks A Computer Science Portal for Geeks\nGreeting: night_fury A Computer Science Portal for Geeks\nGreeting: night_fury Contributer"
},
{
"code": null,
"e": 34048,
"s": 34037,
"text": "PHP-basics"
},
{
"code": null,
"e": 34055,
"s": 34048,
"text": "Picked"
},
{
"code": null,
"e": 34059,
"s": 34055,
"text": "PHP"
},
{
"code": null,
"e": 34076,
"s": 34059,
"text": "Web Technologies"
},
{
"code": null,
"e": 34103,
"s": 34076,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 34107,
"s": 34103,
"text": "PHP"
},
{
"code": null,
"e": 34205,
"s": 34107,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34250,
"s": 34205,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 34300,
"s": 34250,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 34324,
"s": 34300,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 34364,
"s": 34324,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 34416,
"s": 34364,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 34456,
"s": 34416,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34489,
"s": 34456,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34534,
"s": 34489,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34577,
"s": 34534,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Understanding clientHeight, offsetHeight & scrollHeight Properties in CSS
|
clientHeight gives the measure of the height of an element including the padding. Note that border, margin, and scrollbar height (if renedered) are not included in this.
offsetHeight gives the measure of the height of an element including the vertical padding, top and bottom borders. Margin is not including here.
scrollHeight gives the measure of the height of an element including the vertical padding and the content which is not visible on the screen because of its overflow property.
The following examples illustrate clientHeight, offsetHeight, and scrollHeight.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#parent {
margin-top: 10px;
height: 200px;
width: 200px;
overflow: auto;
margin: 20px;
}
#demo {
height: 250px;
padding: 20px;
background-color: beige;
border: 2px ridge red;
}
</style>
</head>
<body>
<button onclick="getHeight()">Get Client Height</button>
<div id="parent">
<div id="demo">
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
</div>
</div>
<article id="display"></article>
<script>
function getHeight() {
let myItem = document.getElementById("demo");
let y = myItem.clientHeight;
document.getElementById ("display").innerHTML = "Client Height is " + y + "px";
}
</script>
</body>
</html>
This will produce the following result −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#parent {
height: 180px;
width: 180px;
overflow: auto;
margin: 20px;
}
#demo {
height: 220px;
padding: 20px;
background-color: cornflowerblue;
border: 10px ridge red;
color: white;
}
</style>
</head>
<body>
<button onclick="getHeight()">Get Offset Height</button>
<div id="parent">
<div id="demo">
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
</div>
</div>
<article id="display"></article>
<script>
function getHeight() {
let myItem = document.getElementById("demo");
let y = myItem.offsetHeight;
document.getElementById ("display").innerHTML = "Offset Height is " + y + "px";
}
</script>
</body>
</html>
This will produce the following result −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#parent {
margin-top: 10px;
height: 200px;
width: 200px;
overflow: auto;
margin: 20px;
}
#demo {
height: 400px;
padding: 20px;
background-color: bisque;
border: 1px solid green;
}
</style>
</head>
<body>
<button onclick="getHeight()">Get Scroll Height</button>
<div id="parent">
<div id="demo">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
<article id="display"></article>
<script>
function getHeight() {
let myItem = document.getElementById("demo");
let y = myItem.scrollHeight;
document.getElementById ("display").innerHTML = "Scroll Height is " + y + "px";
}
</script>
</body>
</html>
This will produce the following result −
|
[
{
"code": null,
"e": 1232,
"s": 1062,
"text": "clientHeight gives the measure of the height of an element including the padding. Note that border, margin, and scrollbar height (if renedered) are not included in this."
},
{
"code": null,
"e": 1377,
"s": 1232,
"text": "offsetHeight gives the measure of the height of an element including the vertical padding, top and bottom borders. Margin is not including here."
},
{
"code": null,
"e": 1552,
"s": 1377,
"text": "scrollHeight gives the measure of the height of an element including the vertical padding and the content which is not visible on the screen because of its overflow property."
},
{
"code": null,
"e": 1632,
"s": 1552,
"text": "The following examples illustrate clientHeight, offsetHeight, and scrollHeight."
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": " Live Demo"
},
{
"code": null,
"e": 2315,
"s": 1643,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n#parent {\n margin-top: 10px;\n height: 200px;\n width: 200px;\n overflow: auto;\n margin: 20px;\n}\n#demo {\n height: 250px;\n padding: 20px;\n background-color: beige;\n border: 2px ridge red;\n}\n</style>\n</head>\n<body>\n<button onclick=\"getHeight()\">Get Client Height</button>\n<div id=\"parent\">\n<div id=\"demo\">\n<ul>\n<li>a</li>\n<li>b</li>\n<li>c</li>\n</ul>\n</div>\n</div>\n<article id=\"display\"></article>\n<script>\nfunction getHeight() {\n let myItem = document.getElementById(\"demo\");\n let y = myItem.clientHeight;\n document.getElementById (\"display\").innerHTML = \"Client Height is \" + y + \"px\";\n}\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2356,
"s": 2315,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2367,
"s": 2356,
"text": " Live Demo"
},
{
"code": null,
"e": 3045,
"s": 2367,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n#parent {\n height: 180px;\n width: 180px;\n overflow: auto;\n margin: 20px;\n}\n#demo {\n height: 220px;\n padding: 20px;\n background-color: cornflowerblue;\n border: 10px ridge red;\n color: white;\n}\n</style>\n</head>\n<body>\n<button onclick=\"getHeight()\">Get Offset Height</button>\n<div id=\"parent\">\n<div id=\"demo\">\n<ul>\n<li>a</li>\n<li>b</li>\n<li>c</li>\n</ul>\n</div>\n</div>\n<article id=\"display\"></article>\n<script>\nfunction getHeight() {\n let myItem = document.getElementById(\"demo\");\n let y = myItem.offsetHeight;\n document.getElementById (\"display\").innerHTML = \"Offset Height is \" + y + \"px\";\n}\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 3086,
"s": 3045,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3097,
"s": 3086,
"text": " Live Demo"
},
{
"code": null,
"e": 3769,
"s": 3097,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n#parent {\n margin-top: 10px;\n height: 200px;\n width: 200px;\n overflow: auto;\n margin: 20px;\n}\n#demo {\n height: 400px;\n padding: 20px;\n background-color: bisque;\n border: 1px solid green;\n}\n</style>\n</head>\n<body>\n<button onclick=\"getHeight()\">Get Scroll Height</button>\n<div id=\"parent\">\n<div id=\"demo\">\n<ul>\n<li></li>\n<li></li>\n<li></li>\n</ul>\n</div>\n</div>\n<article id=\"display\"></article>\n<script>\nfunction getHeight() {\n let myItem = document.getElementById(\"demo\");\n let y = myItem.scrollHeight;\n document.getElementById (\"display\").innerHTML = \"Scroll Height is \" + y + \"px\";\n}\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 3810,
"s": 3769,
"text": "This will produce the following result −"
}
] |
ReactJS Reactstrap List Component - GeeksforGeeks
|
30 Jul, 2021
Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The List component allows the user to display a list. We can use the following approach in ReactJS to use the ReactJS Reactstrap List Component.
List Props:
tag: It is used to denote the tag for this component.
className: It is used to denote the class name for styling.
cssModule: It is used to denote the CSS module for styling.
type: It is used to denote the type of list.
ListInlineItem Props:
tag: It is used to denote the tag for this component.
className: It is used to denote the class name for styling.
cssModule: It is used to denote the CSS module for styling.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install reactstrap bootstrap
Project Structure: It will look like the following.
Project Structure
Example 1: Now write down the following code in the App.js file. Here, we have shown the List component with the ListInlineItem component.
App.js
import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { ListInlineItem, List } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap List Component</h4> <List type="inline"> <ListInlineItem>Sample Item 1</ListInlineItem> <ListInlineItem>Sample Item 2</ListInlineItem> <ListInlineItem>Sample Item 3</ListInlineItem> <ListInlineItem>Sample Item 4</ListInlineItem> <ListInlineItem>Sample Item 5</ListInlineItem> </List> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Example 2: Now write down the following code in the App.js file. Here, we have shown the List component without the ListInlineItem component.
App.js
import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { List } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap List Component</h4> <List type="unstyled"> <li>Monday</li> <li>Tuesday</li> <li>Wednesday</li> <li>Thursday</li> <li>Friday</li> <li>Saturday</li> <li>Sunday</li> </List> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://reactstrap.github.io/components/list/
Reactstrap
JavaScript
ReactJS
Web Technologies
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 filter object array based on attributes?
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 ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 26667,
"s": 26639,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 26974,
"s": 26667,
"text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The List component allows the user to display a list. We can use the following approach in ReactJS to use the ReactJS Reactstrap List Component."
},
{
"code": null,
"e": 26986,
"s": 26974,
"text": "List Props:"
},
{
"code": null,
"e": 27040,
"s": 26986,
"text": "tag: It is used to denote the tag for this component."
},
{
"code": null,
"e": 27100,
"s": 27040,
"text": "className: It is used to denote the class name for styling."
},
{
"code": null,
"e": 27160,
"s": 27100,
"text": "cssModule: It is used to denote the CSS module for styling."
},
{
"code": null,
"e": 27205,
"s": 27160,
"text": "type: It is used to denote the type of list."
},
{
"code": null,
"e": 27227,
"s": 27205,
"text": "ListInlineItem Props:"
},
{
"code": null,
"e": 27281,
"s": 27227,
"text": "tag: It is used to denote the tag for this component."
},
{
"code": null,
"e": 27341,
"s": 27281,
"text": "className: It is used to denote the class name for styling."
},
{
"code": null,
"e": 27401,
"s": 27341,
"text": "cssModule: It is used to denote the CSS module for styling."
},
{
"code": null,
"e": 27453,
"s": 27403,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 27548,
"s": 27453,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 27612,
"s": 27548,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27644,
"s": 27612,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27757,
"s": 27644,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 27857,
"s": 27757,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27871,
"s": 27857,
"text": "cd foldername"
},
{
"code": null,
"e": 28008,
"s": 27871,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap"
},
{
"code": null,
"e": 28113,
"s": 28008,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 28146,
"s": 28113,
"text": "npm install reactstrap bootstrap"
},
{
"code": null,
"e": 28198,
"s": 28146,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 28216,
"s": 28198,
"text": "Project Structure"
},
{
"code": null,
"e": 28355,
"s": 28216,
"text": "Example 1: Now write down the following code in the App.js file. Here, we have shown the List component with the ListInlineItem component."
},
{
"code": null,
"e": 28362,
"s": 28355,
"text": "App.js"
},
{
"code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { ListInlineItem, List } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap List Component</h4> <List type=\"inline\"> <ListInlineItem>Sample Item 1</ListInlineItem> <ListInlineItem>Sample Item 2</ListInlineItem> <ListInlineItem>Sample Item 3</ListInlineItem> <ListInlineItem>Sample Item 4</ListInlineItem> <ListInlineItem>Sample Item 5</ListInlineItem> </List> </div> );} export default App;",
"e": 29055,
"s": 28362,
"text": null
},
{
"code": null,
"e": 29170,
"s": 29057,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29180,
"s": 29170,
"text": "npm start"
},
{
"code": null,
"e": 29279,
"s": 29180,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 29421,
"s": 29279,
"text": "Example 2: Now write down the following code in the App.js file. Here, we have shown the List component without the ListInlineItem component."
},
{
"code": null,
"e": 29428,
"s": 29421,
"text": "App.js"
},
{
"code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { List } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap List Component</h4> <List type=\"unstyled\"> <li>Monday</li> <li>Tuesday</li> <li>Wednesday</li> <li>Thursday</li> <li>Friday</li> <li>Saturday</li> <li>Sunday</li> </List> </div> );} export default App;",
"e": 30022,
"s": 29428,
"text": null
},
{
"code": null,
"e": 30135,
"s": 30022,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 30145,
"s": 30135,
"text": "npm start"
},
{
"code": null,
"e": 30244,
"s": 30145,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 30301,
"s": 30244,
"text": "Reference: https://reactstrap.github.io/components/list/"
},
{
"code": null,
"e": 30312,
"s": 30301,
"text": "Reactstrap"
},
{
"code": null,
"e": 30323,
"s": 30312,
"text": "JavaScript"
},
{
"code": null,
"e": 30331,
"s": 30323,
"text": "ReactJS"
},
{
"code": null,
"e": 30348,
"s": 30331,
"text": "Web Technologies"
},
{
"code": null,
"e": 30446,
"s": 30348,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30486,
"s": 30446,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30547,
"s": 30486,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30588,
"s": 30547,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30610,
"s": 30588,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 30658,
"s": 30610,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 30701,
"s": 30658,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30746,
"s": 30701,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 30811,
"s": 30746,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 30879,
"s": 30811,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
How to get the first and last record of the table in MySQL?
|
To get the first and last record, use UNION. LIMIT is also used to get the number of records you want.
Let us first create a table −
mysql> create table DemoTable694 (
EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
EmployeeName varchar(100),
EmployeeSalary int
);
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Chris',457647);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Robert',90883);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('David',123532);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Mike',989322);
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable694;
This will produce the following output -
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
| 1 | Chris | 457647 |
| 2 | Robert | 90883 |
| 3 | David | 123532 |
| 4 | Mike | 989322 |
+------------+--------------+----------------+
4 rows in set (0.00 sec)
Following is the query to get first and last record −
mysql> (select *from DemoTable694 order by EmployeeId ASC LIMIT 1)
UNION
(select *from DemoTable694 order by EmployeeId DESC LIMIT 1);
This will produce the following output -
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
| 1 | Chris | 457647 |
| 4 | Mike | 989322 |
+------------+--------------+----------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "To get the first and last record, use UNION. LIMIT is also used to get the number of records you want."
},
{
"code": null,
"e": 1195,
"s": 1165,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1377,
"s": 1195,
"text": "mysql> create table DemoTable694 (\n EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n EmployeeName varchar(100),\n EmployeeSalary int\n);\nQuery OK, 0 rows affected (0.58 sec)"
},
{
"code": null,
"e": 1433,
"s": 1377,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1916,
"s": 1433,
"text": "mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Chris',457647);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Robert',90883);\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('David',123532);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Mike',989322);\nQuery OK, 1 row affected (0.22 sec)"
},
{
"code": null,
"e": 1976,
"s": 1916,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2010,
"s": 1976,
"text": "mysql> select *from DemoTable694;"
},
{
"code": null,
"e": 2051,
"s": 2010,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2452,
"s": 2051,
"text": "+------------+--------------+----------------+\n| EmployeeId | EmployeeName | EmployeeSalary |\n+------------+--------------+----------------+\n| 1 | Chris | 457647 |\n| 2 | Robert | 90883 |\n| 3 | David | 123532 |\n| 4 | Mike | 989322 |\n+------------+--------------+----------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2506,
"s": 2452,
"text": "Following is the query to get first and last record −"
},
{
"code": null,
"e": 2641,
"s": 2506,
"text": "mysql> (select *from DemoTable694 order by EmployeeId ASC LIMIT 1)\nUNION\n(select *from DemoTable694 order by EmployeeId DESC LIMIT 1);"
},
{
"code": null,
"e": 2682,
"s": 2641,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2989,
"s": 2682,
"text": "+------------+--------------+----------------+\n| EmployeeId | EmployeeName | EmployeeSalary |\n+------------+--------------+----------------+\n| 1 | Chris | 457647 |\n| 4 | Mike | 989322 |\n+------------+--------------+----------------+\n2 rows in set (0.00 sec)"
}
] |
Ordinal Logistic Regression. An overview and implementation in R | by Akanksha Rawat | Towards Data Science
|
Can you guess what is the common link in the variables mentioned below:
Job satisfaction level — Dissatisfied, Satisfied, Highly Satisfied
Performance of an individual — Poor, Fair, Excellent
Impact of a regulation on bank’s performance — Positive, Neutral, Negative
The variables are not only categorical but they are also following an order (low to high / high to low).
If we want to predict such multi-class ordered variables then we can use the proportional odds logistic regression technique.
To understand the working of Ordered Logistic Regression, we’ll consider a study from World Values Surveys, which looks at factors that influence people’s perception of the government’s efforts to reduce poverty.
Our objective is to predict an individual’s perception about government’s effort to reduce poverty based on factors like individual’s country, gender, age etc. In the given case study, individual’s perception can take the following three values - Too Little, About Right, Too Much.
For our analysis, we’ll be using data from the World Values Surveys for Australia, Norway, Sweden, and the United States from ‘carData’ package in R.
library(carData)library(MASS)data(WVS) head(WVS)
Poverty is the multi-class ordered dependent variable with categories — ‘Too Little’, ‘About Right’ and ‘Too Much’. We have the following five independent variables
Religion: member of a religion -no or yes
Degree: held a university degree -no or yes
Country: Australia, Norway, Sweden or the USA
Age: age (years)
Gender: male or female
Let’s now analyze the descriptive statistics for this dataset:
summary(WVS)
We can also analyze the distribution of poverty across age, sex and country
ggplot(WVS, aes(x = poverty, y = age, fill = poverty)) + geom_boxplot(size = .75) + facet_grid(country ~ gender, margins = FALSE) + theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
We’ll now fit the Proportional Odds Logistic Regression model using polr function from the MASS package.
model_fit <- polr(poverty~religion+degree+country+age+gender, data = WVS, Hess = TRUE)summary(model_fit)
In the output above, we get the information about
Model equation
The regression coefficients with their values, standard errors and t value. There is no significance test by default but we can calculate p-value by comparing t value against the standard normal distribution.
Estimates for two intercepts
Residual deviance and AIC, which are used in comparing the performance of different models
summary_table <- coef(summary(model_fit))pval <- pnorm(abs(summary_table[, "t value"]),lower.tail = FALSE)* 2summary_table <- cbind(summary_table, "p value" = round(pval,3))summary_table
Since the p-value for all the variables <0.05, hence they are statistically significant at 95% CI
In order to interpret this model, we first need to understand the working of the proportional odds model.
Let J be the total number of categories of the dependent variable and M be the number of independent variables (In the given dataset, J=3 and M = 5).
The mathematical formulation of the Proportional Odds Model is given below
Here, j is the level of an ordered category with J levels and i corresponds to independent variables
In our case
j = 1 refers to ‘Too Little’
j = 2 refers to ‘About Right’
j = 3 refers to ‘Too Much’
i = 1 refers to ‘religion’
i = 2 refers to ‘degree’
i = 3 refers to ‘country’
i = 4 refers to ‘age’
i = 5 refers to ‘gender’
Coefficients :
The categorical variables like gender can be interpreted as: a male individual, as opposed to a female individual, is associated with a higher likelihood of having a positive perception about government’s efforts to reduce poverty. The t-value is greater than 2 and therefore is statistically significant at the 5% level.
The continuous variables like age can be interpreted as : with one unit increase in age the log of odds of having a positive perception about government’s efforts to reduce poverty increases by 0.011
Intercepts:
Mathematically, the intercept ‘Too Little | About Right’ corresponds to logit[P(Y ≤ 1)]. It can be interpreted as the log of odds of believing that the government is doing ‘Too Little’ versus believing that the government is doing ‘About Right’ or ‘Too Much’
Similarly, the intercept ‘About Right | Too Much’ corresponds to logit[P(Y ≤ 2)]. It can be interpreted as the log of odds of believing that the government is doing ‘Too Little’ or ‘About Right’ versus believing that the government is doing ‘Too Much’
Let say we want to predict the probability corresponding to each perception for an individual — Test_Person with the following characteristics
Religion : yes
Degree : no
Country : Norway
Age : 30
Gender : male
Mathematical Computation
Mathematical Computation
By using the intercept and slope values from the Model Summary, we can estimate the desired probabilities in the following manner
The probability corresponding to Too Little perception will be calculated as:
logit[P(Y ≤ 1)] = 0.7298 -[(0.17973*1)+(0.14092*0)+(-0.32235*1)+(0.01114*30)+(0.17637*1)]
=> logit[P(Y ≤ 1)] =0.36185
=> P(Y ≤ 1)= exp(0.36185)/(1+exp(0.36185)) = 0.589
In our case, P(Y ≤ 1) = P(Y =1) = 0.589
Similarly, the probability corresponding to About Right perception will be calculated as:
logit[P(Y ≤ 2)] = 2.5325 -[(0.17973*1)+(0.14092*0)+(-0.32235*1)+(0.01114*30)+(0.17637*1)]
=> logit[P(Y ≤ 2)] =2.16455
=> P(Y ≤ 2)= exp(2.16455)/(1+exp(2.16455)) = 0.897
Hence, P(Y = 2) = P(Y ≤ 2) — P(Y ≤ 1) = 0.897 -0.589
=> P(Y = 2) = 0.308
The probability corresponding to Too Much perception will be calculated as:
Thus, P(Y = 3) = 1-P(Y ≤2)
=> P(Y = 3) = 0.103
2. Computation in R
Fortunately, we can bypass the above mathematical calculation by using the predict function in R
new_data <- data.frame("religion"= "yes","degree"="no","country"="Norway","age"=30,"gender"="male")round(predict(model_fit,new_data,type = "p"), 3)
Our model predicts that the individual Test_Person believes that the government’s effort to reduce poverty are Too Little
If you wish to learn more about this concept, I encourage you to go through the following links:
|
[
{
"code": null,
"e": 244,
"s": 172,
"text": "Can you guess what is the common link in the variables mentioned below:"
},
{
"code": null,
"e": 311,
"s": 244,
"text": "Job satisfaction level — Dissatisfied, Satisfied, Highly Satisfied"
},
{
"code": null,
"e": 364,
"s": 311,
"text": "Performance of an individual — Poor, Fair, Excellent"
},
{
"code": null,
"e": 439,
"s": 364,
"text": "Impact of a regulation on bank’s performance — Positive, Neutral, Negative"
},
{
"code": null,
"e": 544,
"s": 439,
"text": "The variables are not only categorical but they are also following an order (low to high / high to low)."
},
{
"code": null,
"e": 670,
"s": 544,
"text": "If we want to predict such multi-class ordered variables then we can use the proportional odds logistic regression technique."
},
{
"code": null,
"e": 883,
"s": 670,
"text": "To understand the working of Ordered Logistic Regression, we’ll consider a study from World Values Surveys, which looks at factors that influence people’s perception of the government’s efforts to reduce poverty."
},
{
"code": null,
"e": 1165,
"s": 883,
"text": "Our objective is to predict an individual’s perception about government’s effort to reduce poverty based on factors like individual’s country, gender, age etc. In the given case study, individual’s perception can take the following three values - Too Little, About Right, Too Much."
},
{
"code": null,
"e": 1315,
"s": 1165,
"text": "For our analysis, we’ll be using data from the World Values Surveys for Australia, Norway, Sweden, and the United States from ‘carData’ package in R."
},
{
"code": null,
"e": 1364,
"s": 1315,
"text": "library(carData)library(MASS)data(WVS) head(WVS)"
},
{
"code": null,
"e": 1529,
"s": 1364,
"text": "Poverty is the multi-class ordered dependent variable with categories — ‘Too Little’, ‘About Right’ and ‘Too Much’. We have the following five independent variables"
},
{
"code": null,
"e": 1571,
"s": 1529,
"text": "Religion: member of a religion -no or yes"
},
{
"code": null,
"e": 1615,
"s": 1571,
"text": "Degree: held a university degree -no or yes"
},
{
"code": null,
"e": 1661,
"s": 1615,
"text": "Country: Australia, Norway, Sweden or the USA"
},
{
"code": null,
"e": 1678,
"s": 1661,
"text": "Age: age (years)"
},
{
"code": null,
"e": 1701,
"s": 1678,
"text": "Gender: male or female"
},
{
"code": null,
"e": 1764,
"s": 1701,
"text": "Let’s now analyze the descriptive statistics for this dataset:"
},
{
"code": null,
"e": 1777,
"s": 1764,
"text": "summary(WVS)"
},
{
"code": null,
"e": 1853,
"s": 1777,
"text": "We can also analyze the distribution of poverty across age, sex and country"
},
{
"code": null,
"e": 2059,
"s": 1853,
"text": "ggplot(WVS, aes(x = poverty, y = age, fill = poverty)) + geom_boxplot(size = .75) + facet_grid(country ~ gender, margins = FALSE) + theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))"
},
{
"code": null,
"e": 2164,
"s": 2059,
"text": "We’ll now fit the Proportional Odds Logistic Regression model using polr function from the MASS package."
},
{
"code": null,
"e": 2269,
"s": 2164,
"text": "model_fit <- polr(poverty~religion+degree+country+age+gender, data = WVS, Hess = TRUE)summary(model_fit)"
},
{
"code": null,
"e": 2319,
"s": 2269,
"text": "In the output above, we get the information about"
},
{
"code": null,
"e": 2334,
"s": 2319,
"text": "Model equation"
},
{
"code": null,
"e": 2543,
"s": 2334,
"text": "The regression coefficients with their values, standard errors and t value. There is no significance test by default but we can calculate p-value by comparing t value against the standard normal distribution."
},
{
"code": null,
"e": 2572,
"s": 2543,
"text": "Estimates for two intercepts"
},
{
"code": null,
"e": 2663,
"s": 2572,
"text": "Residual deviance and AIC, which are used in comparing the performance of different models"
},
{
"code": null,
"e": 2850,
"s": 2663,
"text": "summary_table <- coef(summary(model_fit))pval <- pnorm(abs(summary_table[, \"t value\"]),lower.tail = FALSE)* 2summary_table <- cbind(summary_table, \"p value\" = round(pval,3))summary_table"
},
{
"code": null,
"e": 2948,
"s": 2850,
"text": "Since the p-value for all the variables <0.05, hence they are statistically significant at 95% CI"
},
{
"code": null,
"e": 3054,
"s": 2948,
"text": "In order to interpret this model, we first need to understand the working of the proportional odds model."
},
{
"code": null,
"e": 3204,
"s": 3054,
"text": "Let J be the total number of categories of the dependent variable and M be the number of independent variables (In the given dataset, J=3 and M = 5)."
},
{
"code": null,
"e": 3279,
"s": 3204,
"text": "The mathematical formulation of the Proportional Odds Model is given below"
},
{
"code": null,
"e": 3380,
"s": 3279,
"text": "Here, j is the level of an ordered category with J levels and i corresponds to independent variables"
},
{
"code": null,
"e": 3392,
"s": 3380,
"text": "In our case"
},
{
"code": null,
"e": 3421,
"s": 3392,
"text": "j = 1 refers to ‘Too Little’"
},
{
"code": null,
"e": 3451,
"s": 3421,
"text": "j = 2 refers to ‘About Right’"
},
{
"code": null,
"e": 3478,
"s": 3451,
"text": "j = 3 refers to ‘Too Much’"
},
{
"code": null,
"e": 3505,
"s": 3478,
"text": "i = 1 refers to ‘religion’"
},
{
"code": null,
"e": 3530,
"s": 3505,
"text": "i = 2 refers to ‘degree’"
},
{
"code": null,
"e": 3556,
"s": 3530,
"text": "i = 3 refers to ‘country’"
},
{
"code": null,
"e": 3578,
"s": 3556,
"text": "i = 4 refers to ‘age’"
},
{
"code": null,
"e": 3603,
"s": 3578,
"text": "i = 5 refers to ‘gender’"
},
{
"code": null,
"e": 3618,
"s": 3603,
"text": "Coefficients :"
},
{
"code": null,
"e": 3940,
"s": 3618,
"text": "The categorical variables like gender can be interpreted as: a male individual, as opposed to a female individual, is associated with a higher likelihood of having a positive perception about government’s efforts to reduce poverty. The t-value is greater than 2 and therefore is statistically significant at the 5% level."
},
{
"code": null,
"e": 4140,
"s": 3940,
"text": "The continuous variables like age can be interpreted as : with one unit increase in age the log of odds of having a positive perception about government’s efforts to reduce poverty increases by 0.011"
},
{
"code": null,
"e": 4152,
"s": 4140,
"text": "Intercepts:"
},
{
"code": null,
"e": 4411,
"s": 4152,
"text": "Mathematically, the intercept ‘Too Little | About Right’ corresponds to logit[P(Y ≤ 1)]. It can be interpreted as the log of odds of believing that the government is doing ‘Too Little’ versus believing that the government is doing ‘About Right’ or ‘Too Much’"
},
{
"code": null,
"e": 4663,
"s": 4411,
"text": "Similarly, the intercept ‘About Right | Too Much’ corresponds to logit[P(Y ≤ 2)]. It can be interpreted as the log of odds of believing that the government is doing ‘Too Little’ or ‘About Right’ versus believing that the government is doing ‘Too Much’"
},
{
"code": null,
"e": 4806,
"s": 4663,
"text": "Let say we want to predict the probability corresponding to each perception for an individual — Test_Person with the following characteristics"
},
{
"code": null,
"e": 4821,
"s": 4806,
"text": "Religion : yes"
},
{
"code": null,
"e": 4833,
"s": 4821,
"text": "Degree : no"
},
{
"code": null,
"e": 4850,
"s": 4833,
"text": "Country : Norway"
},
{
"code": null,
"e": 4859,
"s": 4850,
"text": "Age : 30"
},
{
"code": null,
"e": 4873,
"s": 4859,
"text": "Gender : male"
},
{
"code": null,
"e": 4898,
"s": 4873,
"text": "Mathematical Computation"
},
{
"code": null,
"e": 4923,
"s": 4898,
"text": "Mathematical Computation"
},
{
"code": null,
"e": 5053,
"s": 4923,
"text": "By using the intercept and slope values from the Model Summary, we can estimate the desired probabilities in the following manner"
},
{
"code": null,
"e": 5131,
"s": 5053,
"text": "The probability corresponding to Too Little perception will be calculated as:"
},
{
"code": null,
"e": 5221,
"s": 5131,
"text": "logit[P(Y ≤ 1)] = 0.7298 -[(0.17973*1)+(0.14092*0)+(-0.32235*1)+(0.01114*30)+(0.17637*1)]"
},
{
"code": null,
"e": 5249,
"s": 5221,
"text": "=> logit[P(Y ≤ 1)] =0.36185"
},
{
"code": null,
"e": 5300,
"s": 5249,
"text": "=> P(Y ≤ 1)= exp(0.36185)/(1+exp(0.36185)) = 0.589"
},
{
"code": null,
"e": 5340,
"s": 5300,
"text": "In our case, P(Y ≤ 1) = P(Y =1) = 0.589"
},
{
"code": null,
"e": 5430,
"s": 5340,
"text": "Similarly, the probability corresponding to About Right perception will be calculated as:"
},
{
"code": null,
"e": 5520,
"s": 5430,
"text": "logit[P(Y ≤ 2)] = 2.5325 -[(0.17973*1)+(0.14092*0)+(-0.32235*1)+(0.01114*30)+(0.17637*1)]"
},
{
"code": null,
"e": 5548,
"s": 5520,
"text": "=> logit[P(Y ≤ 2)] =2.16455"
},
{
"code": null,
"e": 5599,
"s": 5548,
"text": "=> P(Y ≤ 2)= exp(2.16455)/(1+exp(2.16455)) = 0.897"
},
{
"code": null,
"e": 5652,
"s": 5599,
"text": "Hence, P(Y = 2) = P(Y ≤ 2) — P(Y ≤ 1) = 0.897 -0.589"
},
{
"code": null,
"e": 5672,
"s": 5652,
"text": "=> P(Y = 2) = 0.308"
},
{
"code": null,
"e": 5748,
"s": 5672,
"text": "The probability corresponding to Too Much perception will be calculated as:"
},
{
"code": null,
"e": 5775,
"s": 5748,
"text": "Thus, P(Y = 3) = 1-P(Y ≤2)"
},
{
"code": null,
"e": 5795,
"s": 5775,
"text": "=> P(Y = 3) = 0.103"
},
{
"code": null,
"e": 5815,
"s": 5795,
"text": "2. Computation in R"
},
{
"code": null,
"e": 5912,
"s": 5815,
"text": "Fortunately, we can bypass the above mathematical calculation by using the predict function in R"
},
{
"code": null,
"e": 6060,
"s": 5912,
"text": "new_data <- data.frame(\"religion\"= \"yes\",\"degree\"=\"no\",\"country\"=\"Norway\",\"age\"=30,\"gender\"=\"male\")round(predict(model_fit,new_data,type = \"p\"), 3)"
},
{
"code": null,
"e": 6182,
"s": 6060,
"text": "Our model predicts that the individual Test_Person believes that the government’s effort to reduce poverty are Too Little"
}
] |
Compiler Design - Phases of Compiler
|
The compilation process is a sequence of various phases. Each phase takes input from its previous stage, has its own representation of source program, and feeds its output to the next phase of the compiler. Let us understand the phases of a compiler.
The first phase of scanner works as a text scanner. This phase scans the source code as a stream of characters and converts it into meaningful lexemes. Lexical analyzer represents these lexemes in the form of tokens as:
<token-name, attribute-value>
The next phase is called the syntax analysis or parsing. It takes the token produced by lexical analysis as input and generates a parse tree (or syntax tree). In this phase, token arrangements are checked against the source code grammar, i.e. the parser checks if the expression made by the tokens is syntactically correct.
Semantic analysis checks whether the parse tree constructed follows the rules of language. For example, assignment of values is between compatible data types, and adding string to an integer. Also, the semantic analyzer keeps track of identifiers, their types and expressions; whether identifiers are declared before use or not etc. The semantic analyzer produces an annotated syntax tree as an output.
After semantic analysis the compiler generates an intermediate code of the source code for the target machine. It represents a program for some abstract machine. It is in between the high-level language and the machine language. This intermediate code should be generated in such a way that it makes it easier to be translated into the target machine code.
The next phase does code optimization of the intermediate code. Optimization can be assumed as something that removes unnecessary code lines, and arranges the sequence of statements in order to speed up the program execution without wasting resources (CPU, memory).
In this phase, the code generator takes the optimized representation of the intermediate code and maps it to the target machine language. The code generator translates the intermediate code into a sequence of (generally) re-locatable machine code. Sequence of instructions of machine code performs the task as the intermediate code would do.
It is a data-structure maintained throughout all the phases of a compiler. All the identifier's names along with their types are stored here. The symbol table makes it easier for the compiler to quickly search the identifier record and retrieve it. The symbol table is also used for scope management.
102 Lectures
10 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2444,
"s": 2193,
"text": "The compilation process is a sequence of various phases. Each phase takes input from its previous stage, has its own representation of source program, and feeds its output to the next phase of the compiler. Let us understand the phases of a compiler."
},
{
"code": null,
"e": 2664,
"s": 2444,
"text": "The first phase of scanner works as a text scanner. This phase scans the source code as a stream of characters and converts it into meaningful lexemes. Lexical analyzer represents these lexemes in the form of tokens as:"
},
{
"code": null,
"e": 2694,
"s": 2664,
"text": "<token-name, attribute-value>"
},
{
"code": null,
"e": 3018,
"s": 2694,
"text": "The next phase is called the syntax analysis or parsing. It takes the token produced by lexical analysis as input and generates a parse tree (or syntax tree). In this phase, token arrangements are checked against the source code grammar, i.e. the parser checks if the expression made by the tokens is syntactically correct."
},
{
"code": null,
"e": 3421,
"s": 3018,
"text": "Semantic analysis checks whether the parse tree constructed follows the rules of language. For example, assignment of values is between compatible data types, and adding string to an integer. Also, the semantic analyzer keeps track of identifiers, their types and expressions; whether identifiers are declared before use or not etc. The semantic analyzer produces an annotated syntax tree as an output."
},
{
"code": null,
"e": 3778,
"s": 3421,
"text": "After semantic analysis the compiler generates an intermediate code of the source code for the target machine. It represents a program for some abstract machine. It is in between the high-level language and the machine language. This intermediate code should be generated in such a way that it makes it easier to be translated into the target machine code."
},
{
"code": null,
"e": 4044,
"s": 3778,
"text": "The next phase does code optimization of the intermediate code. Optimization can be assumed as something that removes unnecessary code lines, and arranges the sequence of statements in order to speed up the program execution without wasting resources (CPU, memory)."
},
{
"code": null,
"e": 4386,
"s": 4044,
"text": "In this phase, the code generator takes the optimized representation of the intermediate code and maps it to the target machine language. The code generator translates the intermediate code into a sequence of (generally) re-locatable machine code. Sequence of instructions of machine code performs the task as the intermediate code would do."
},
{
"code": null,
"e": 4687,
"s": 4386,
"text": "It is a data-structure maintained throughout all the phases of a compiler. All the identifier's names along with their types are stored here. The symbol table makes it easier for the compiler to quickly search the identifier record and retrieve it. The symbol table is also used for scope management."
},
{
"code": null,
"e": 4722,
"s": 4687,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4741,
"s": 4722,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4748,
"s": 4741,
"text": " Print"
},
{
"code": null,
"e": 4759,
"s": 4748,
"text": " Add Notes"
}
] |
How to assign specific colors to specific cells in a Matplotlib table?
|
To assign specific colors to specific cells in a Matplotlib table, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make a tuple for columns attribute.
Make a list of lists, i.e., list of records.
Make a list of lists, i.e., color of each cell.
Create a figure and a set of subplots.
Add a table to an axes ax.
Turn off the axes.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
columns = ('name', 'age', 'marks', 'salary')
cell_text = [["John", "23", "98", "234"],
["James", "24", "90", "239"]]
colors = [["red", "yellow", "blue", "green"],
["blue", "green", "yellow", "red"]]
fig, ax = plt.subplots()
the_table = ax.table(cellText=cell_text, cellColours=colors,
colLabels=columns, loc='center')
ax.axis('off')
plt.show()
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "To assign specific colors to specific cells in a Matplotlib table, we can take the following steps −"
},
{
"code": null,
"e": 1239,
"s": 1163,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1275,
"s": 1239,
"text": "Make a tuple for columns attribute."
},
{
"code": null,
"e": 1320,
"s": 1275,
"text": "Make a list of lists, i.e., list of records."
},
{
"code": null,
"e": 1368,
"s": 1320,
"text": "Make a list of lists, i.e., color of each cell."
},
{
"code": null,
"e": 1407,
"s": 1368,
"text": "Create a figure and a set of subplots."
},
{
"code": null,
"e": 1434,
"s": 1407,
"text": "Add a table to an axes ax."
},
{
"code": null,
"e": 1453,
"s": 1434,
"text": "Turn off the axes."
},
{
"code": null,
"e": 1495,
"s": 1453,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1986,
"s": 1495,
"text": "import matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ncolumns = ('name', 'age', 'marks', 'salary')\n\ncell_text = [[\"John\", \"23\", \"98\", \"234\"],\n[\"James\", \"24\", \"90\", \"239\"]]\n\ncolors = [[\"red\", \"yellow\", \"blue\", \"green\"],\n[\"blue\", \"green\", \"yellow\", \"red\"]]\n\nfig, ax = plt.subplots()\n\nthe_table = ax.table(cellText=cell_text, cellColours=colors,\n colLabels=columns, loc='center')\nax.axis('off')\n\nplt.show()"
}
] |
Precedence of postfix ++ and prefix ++ in C/C++ - GeeksforGeeks
|
15 Jul, 2021
In C/C++, precedence of Prefix ++ (or Prefix –) has same priority than dereference (*) operator, and precedence of Postfix ++ (or Postfix –) is higher than both Prefix ++ and *. If p is a pointer then *p++ is equivalent to *(p++) and ++*p is equivalent to ++(*p) (both Prefix ++ and * are right associative).For example, program 1 prints ‘h’ and program 2 prints ‘e’.
C
// Program 1#include<stdio.h>int main(){ char arr[] = "geeksforgeeks"; char *p = arr; ++*p; printf(" %c", *p); getchar(); return 0;}
Output:
h
C
// Program 2#include<stdio.h>int main(){ char arr[] = "geeksforgeeks"; char *p = arr; *p++; printf(" %c", *p); getchar(); return 0;}
Output:
e
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sourabh571993
dpatwal8
C-Operators
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 24464,
"s": 24436,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 24833,
"s": 24464,
"text": "In C/C++, precedence of Prefix ++ (or Prefix –) has same priority than dereference (*) operator, and precedence of Postfix ++ (or Postfix –) is higher than both Prefix ++ and *. If p is a pointer then *p++ is equivalent to *(p++) and ++*p is equivalent to ++(*p) (both Prefix ++ and * are right associative).For example, program 1 prints ‘h’ and program 2 prints ‘e’. "
},
{
"code": null,
"e": 24835,
"s": 24833,
"text": "C"
},
{
"code": "// Program 1#include<stdio.h>int main(){ char arr[] = \"geeksforgeeks\"; char *p = arr; ++*p; printf(\" %c\", *p); getchar(); return 0;}",
"e": 24974,
"s": 24835,
"text": null
},
{
"code": null,
"e": 24982,
"s": 24974,
"text": "Output:"
},
{
"code": null,
"e": 24986,
"s": 24982,
"text": " h"
},
{
"code": null,
"e": 24990,
"s": 24988,
"text": "C"
},
{
"code": "// Program 2#include<stdio.h>int main(){ char arr[] = \"geeksforgeeks\"; char *p = arr; *p++; printf(\" %c\", *p); getchar(); return 0;}",
"e": 25129,
"s": 24990,
"text": null
},
{
"code": null,
"e": 25137,
"s": 25129,
"text": "Output:"
},
{
"code": null,
"e": 25141,
"s": 25137,
"text": " e"
},
{
"code": null,
"e": 25267,
"s": 25141,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 25281,
"s": 25267,
"text": "sourabh571993"
},
{
"code": null,
"e": 25290,
"s": 25281,
"text": "dpatwal8"
},
{
"code": null,
"e": 25302,
"s": 25290,
"text": "C-Operators"
},
{
"code": null,
"e": 25313,
"s": 25302,
"text": "C Language"
},
{
"code": null,
"e": 25317,
"s": 25313,
"text": "C++"
},
{
"code": null,
"e": 25321,
"s": 25317,
"text": "CPP"
},
{
"code": null,
"e": 25419,
"s": 25321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25454,
"s": 25419,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25482,
"s": 25454,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25528,
"s": 25482,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 25540,
"s": 25528,
"text": "fork() in C"
},
{
"code": null,
"e": 25580,
"s": 25540,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 25598,
"s": 25580,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 25644,
"s": 25598,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 25663,
"s": 25644,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 25706,
"s": 25663,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
C++ Program to Represent Graph Using Adjacency Matrix
|
The adjacency matrix of a graph is a square matrix of size V x V. The V is the number of vertices of the graph G. In this matrix in each side V vertices are marked. If the graph has some edges from i to j vertices, then in the adjacency matrix at ith row and jth column it will be 1 (or some non-zero value for weighted graph), otherwise that place will hold 0.
The adjacency matrix representation takes O(V2) amount of space while it is computed. When graph has maximum number of edges and minimum number of edges, in both cases the required space will be same.
The adjacency matrix representation takes O(V2) amount of space while it is computed. When graph has maximum number of edges and minimum number of edges, in both cases the required space will be same.
Input
Output
Input − The u and v of an edge {u,v}
Output − Adjacency matrix of the graph G
Begin
adj_matrix[u, v] := 1
adj_matrix[v, u] := 1
End
#include<iostream>
using namespace std;
int vertArr[20][20]; //the adjacency matrix initially 0
int count = 0;
void displayMatrix(int v) {
int i, j;
for(i = 0; i < v; i++) {
for(j = 0; j < v; j++) {
cout << vertArr[i][j] << " ";
}
cout << endl;
}
}
void add_edge(int u, int v) { //function to add edge into the matrix
vertArr[u][v] = 1;
vertArr[v][u] = 1;
}
main(int argc, char* argv[]) {
int v = 6; //there are 6 vertices in the graph
add_edge(0, 4);
add_edge(0, 3);
add_edge(1, 2);
add_edge(1, 4);
add_edge(1, 5);
add_edge(2, 3);
add_edge(2, 5);
add_edge(5, 3);
add_edge(5, 4);
displayMatrix(v);
}
0 0 0 1 1 0
0 0 1 0 1 1
0 1 0 1 0 1
1 0 1 0 0 1
1 1 0 0 0 1
0 1 1 1 1 0
|
[
{
"code": null,
"e": 1424,
"s": 1062,
"text": "The adjacency matrix of a graph is a square matrix of size V x V. The V is the number of vertices of the graph G. In this matrix in each side V vertices are marked. If the graph has some edges from i to j vertices, then in the adjacency matrix at ith row and jth column it will be 1 (or some non-zero value for weighted graph), otherwise that place will hold 0."
},
{
"code": null,
"e": 1625,
"s": 1424,
"text": "The adjacency matrix representation takes O(V2) amount of space while it is computed. When graph has maximum number of edges and minimum number of edges, in both cases the required space will be same."
},
{
"code": null,
"e": 1826,
"s": 1625,
"text": "The adjacency matrix representation takes O(V2) amount of space while it is computed. When graph has maximum number of edges and minimum number of edges, in both cases the required space will be same."
},
{
"code": null,
"e": 1832,
"s": 1826,
"text": "Input"
},
{
"code": null,
"e": 1839,
"s": 1832,
"text": "Output"
},
{
"code": null,
"e": 1876,
"s": 1839,
"text": "Input − The u and v of an edge {u,v}"
},
{
"code": null,
"e": 1917,
"s": 1876,
"text": "Output − Adjacency matrix of the graph G"
},
{
"code": null,
"e": 1971,
"s": 1917,
"text": "Begin\nadj_matrix[u, v] := 1\nadj_matrix[v, u] := 1\nEnd"
},
{
"code": null,
"e": 2613,
"s": 1971,
"text": "#include<iostream>\nusing namespace std;\nint vertArr[20][20]; //the adjacency matrix initially 0\nint count = 0;\nvoid displayMatrix(int v) {\n int i, j;\n for(i = 0; i < v; i++) {\n for(j = 0; j < v; j++) {\n cout << vertArr[i][j] << \" \";\n }\n cout << endl;\n }\n}\nvoid add_edge(int u, int v) { //function to add edge into the matrix\n vertArr[u][v] = 1;\n vertArr[v][u] = 1;\n}\nmain(int argc, char* argv[]) {\nint v = 6; //there are 6 vertices in the graph\nadd_edge(0, 4);\nadd_edge(0, 3);\nadd_edge(1, 2);\nadd_edge(1, 4);\nadd_edge(1, 5);\nadd_edge(2, 3);\nadd_edge(2, 5);\nadd_edge(5, 3);\nadd_edge(5, 4);\ndisplayMatrix(v);\n}"
},
{
"code": null,
"e": 2685,
"s": 2613,
"text": "0 0 0 1 1 0\n0 0 1 0 1 1\n0 1 0 1 0 1\n1 0 1 0 0 1\n1 1 0 0 0 1\n0 1 1 1 1 0"
}
] |
Getting MongoDB results from the previous month
|
At first, get the current month and subtract by 1 to fetch previous month records. Let us first create a collection with documents −
> db.findOneMonthAgoData.insertOne({"CustomerName":"Chris","PurchaseDate":new ISODate("2019-12-26")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04e16c150ee0e76c06a04f")
}
> db.findOneMonthAgoData.insertOne({"CustomerName":"David","PurchaseDate":new ISODate("2019-11-26")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04e178150ee0e76c06a050")
}
> db.findOneMonthAgoData.insertOne({"CustomerName":"Bob","PurchaseDate":new ISODate("2020-11-26")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04e186150ee0e76c06a051")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findOneMonthAgoData.find();
This will produce the following output −
{ "_id" : ObjectId("5e04e16c150ee0e76c06a04f"), "CustomerName" : "Chris", "PurchaseDate" : ISODate("2019-12-26T00:00:00Z") }
{ "_id" : ObjectId("5e04e178150ee0e76c06a050"), "CustomerName" : "David", "PurchaseDate" : ISODate("2019-11-26T00:00:00Z") }
{ "_id" : ObjectId("5e04e186150ee0e76c06a051"), "CustomerName" : "Bob", "PurchaseDate" : ISODate("2020-11-26T00:00:00Z") }
Here is the query to get result from previous month −
> monthData=new Date();
ISODate("2019-12-26T16:43:04.283Z")
> monthData.setMonth(monthData.getMonth() - 1);
1574786584283
> db.findOneMonthAgoData.find({PurchaseDate:{$gte:monthData}});
This will produce the following output −
{ "_id" : ObjectId("5e04e16c150ee0e76c06a04f"), "CustomerName" : "Chris", "PurchaseDate" : ISODate("2019-12-26T00:00:00Z") }
{ "_id" : ObjectId("5e04e186150ee0e76c06a051"), "CustomerName" : "Bob", "PurchaseDate" : ISODate("2020-11-26T00:00:00Z") }
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "At first, get the current month and subtract by 1 to fetch previous month records. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1757,
"s": 1195,
"text": "> db.findOneMonthAgoData.insertOne({\"CustomerName\":\"Chris\",\"PurchaseDate\":new ISODate(\"2019-12-26\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04e16c150ee0e76c06a04f\")\n}\n> db.findOneMonthAgoData.insertOne({\"CustomerName\":\"David\",\"PurchaseDate\":new ISODate(\"2019-11-26\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04e178150ee0e76c06a050\")\n}\n> db.findOneMonthAgoData.insertOne({\"CustomerName\":\"Bob\",\"PurchaseDate\":new ISODate(\"2020-11-26\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04e186150ee0e76c06a051\")\n}"
},
{
"code": null,
"e": 1856,
"s": 1757,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1889,
"s": 1856,
"text": "> db.findOneMonthAgoData.find();"
},
{
"code": null,
"e": 1930,
"s": 1889,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2303,
"s": 1930,
"text": "{ \"_id\" : ObjectId(\"5e04e16c150ee0e76c06a04f\"), \"CustomerName\" : \"Chris\", \"PurchaseDate\" : ISODate(\"2019-12-26T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e04e178150ee0e76c06a050\"), \"CustomerName\" : \"David\", \"PurchaseDate\" : ISODate(\"2019-11-26T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e04e186150ee0e76c06a051\"), \"CustomerName\" : \"Bob\", \"PurchaseDate\" : ISODate(\"2020-11-26T00:00:00Z\") }"
},
{
"code": null,
"e": 2357,
"s": 2303,
"text": "Here is the query to get result from previous month −"
},
{
"code": null,
"e": 2543,
"s": 2357,
"text": "> monthData=new Date();\nISODate(\"2019-12-26T16:43:04.283Z\")\n> monthData.setMonth(monthData.getMonth() - 1);\n1574786584283\n> db.findOneMonthAgoData.find({PurchaseDate:{$gte:monthData}});"
},
{
"code": null,
"e": 2584,
"s": 2543,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2832,
"s": 2584,
"text": "{ \"_id\" : ObjectId(\"5e04e16c150ee0e76c06a04f\"), \"CustomerName\" : \"Chris\", \"PurchaseDate\" : ISODate(\"2019-12-26T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e04e186150ee0e76c06a051\"), \"CustomerName\" : \"Bob\", \"PurchaseDate\" : ISODate(\"2020-11-26T00:00:00Z\") }"
}
] |
PHP | ctype_upper() Function
|
04 Jun, 2018
The ctype_upper() function in PHP used to check each and every character of a given string is in uppercase or not. If the string in upper case then it returns TRUE otherwise returns False.
Syntax:
ctype_upper (string text)
Parameter Used:-
$text : The tested string.
Return Value:Function returns True if each character of text in Upper Case or False if text is not in upper case.
Examples:
Input : GEEKSFORGEEKS
Output : Yes
Explanation: All characters of "GEEKSFORGEEKS"
in UPPERCASE.
Input : GFG2018
Output : No
Explanation : In text "GFG2018", '2', '0', '1', '8'
are not in UPPERCASE.
Input : GFG INDIA
Output : No
Explanation : In String "GFG INDIA" a special character [space]
between GFG and INDIA. so answer will be No.
Note: Except string, if we input anything then it will return FALSE.
Below program illustrates the ctype_upper() function in PHP:
Program: 1
<?php// PHP program to check given string is // all characters -Uppercase characters $string1 = 'GEEKSFORGEEKS'; if (ctype_upper($string1)) { // if true then return Yes echo "Yes\n"; } else { // if False then return No echo "No\n"; }?>
Yes
Program: 2 passing array of string as text and print result for individual values.
<?php // PHP program to check given string is // all characters -Uppercase characters $strings = array('GEEKSFORGEEKS', 'First', 'PROGRAMAT2018', 'ARTICLE'); // Checking above given four strings //by used of ctype_upper() function . foreach ($strings as $test) { if (ctype_upper($test)) { // if true then return Yes echo "Yes\n"; } else { // if False then return No echo "No\n"; }} ?>
Yes
No
No
Yes
Program: 3 Drive a code ctype_upper() function where input will be space, special symbol, returns False.
<?php// PHP program to check given string is // all characters -Uppercase characters $strings = array('GEEK @ . com'); // Checking above given four strings //by used of ctype_upper() function . foreach ($strings as $test) { if (ctype_upper($test)) { // if true then return Yes echo "Yes\n"; } else { // if False then return No echo "No\n"; }} ?>
No
References : http://php.net/manual/en/function.ctype-upper.php
PHP-function
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jun, 2018"
},
{
"code": null,
"e": 217,
"s": 28,
"text": "The ctype_upper() function in PHP used to check each and every character of a given string is in uppercase or not. If the string in upper case then it returns TRUE otherwise returns False."
},
{
"code": null,
"e": 225,
"s": 217,
"text": "Syntax:"
},
{
"code": null,
"e": 252,
"s": 225,
"text": "ctype_upper (string text)\n"
},
{
"code": null,
"e": 269,
"s": 252,
"text": "Parameter Used:-"
},
{
"code": null,
"e": 296,
"s": 269,
"text": "$text : The tested string."
},
{
"code": null,
"e": 410,
"s": 296,
"text": "Return Value:Function returns True if each character of text in Upper Case or False if text is not in upper case."
},
{
"code": null,
"e": 420,
"s": 410,
"text": "Examples:"
},
{
"code": null,
"e": 827,
"s": 420,
"text": "Input : GEEKSFORGEEKS\nOutput : Yes\nExplanation: All characters of \"GEEKSFORGEEKS\" \n in UPPERCASE.\n\nInput : GFG2018\nOutput : No\nExplanation : In text \"GFG2018\", '2', '0', '1', '8'\n are not in UPPERCASE.\n\nInput : GFG INDIA\nOutput : No\nExplanation : In String \"GFG INDIA\" a special character [space] \n between GFG and INDIA. so answer will be No.\n \n"
},
{
"code": null,
"e": 896,
"s": 827,
"text": "Note: Except string, if we input anything then it will return FALSE."
},
{
"code": null,
"e": 957,
"s": 896,
"text": "Below program illustrates the ctype_upper() function in PHP:"
},
{
"code": null,
"e": 968,
"s": 957,
"text": "Program: 1"
},
{
"code": "<?php// PHP program to check given string is // all characters -Uppercase characters $string1 = 'GEEKSFORGEEKS'; if (ctype_upper($string1)) { // if true then return Yes echo \"Yes\\n\"; } else { // if False then return No echo \"No\\n\"; }?>",
"e": 1262,
"s": 968,
"text": null
},
{
"code": null,
"e": 1267,
"s": 1262,
"text": "Yes\n"
},
{
"code": null,
"e": 1350,
"s": 1267,
"text": "Program: 2 passing array of string as text and print result for individual values."
},
{
"code": "<?php // PHP program to check given string is // all characters -Uppercase characters $strings = array('GEEKSFORGEEKS', 'First', 'PROGRAMAT2018', 'ARTICLE'); // Checking above given four strings //by used of ctype_upper() function . foreach ($strings as $test) { if (ctype_upper($test)) { // if true then return Yes echo \"Yes\\n\"; } else { // if False then return No echo \"No\\n\"; }} ?>",
"e": 1799,
"s": 1350,
"text": null
},
{
"code": null,
"e": 1814,
"s": 1799,
"text": "Yes\nNo\nNo\nYes\n"
},
{
"code": null,
"e": 1919,
"s": 1814,
"text": "Program: 3 Drive a code ctype_upper() function where input will be space, special symbol, returns False."
},
{
"code": " <?php// PHP program to check given string is // all characters -Uppercase characters $strings = array('GEEK @ . com'); // Checking above given four strings //by used of ctype_upper() function . foreach ($strings as $test) { if (ctype_upper($test)) { // if true then return Yes echo \"Yes\\n\"; } else { // if False then return No echo \"No\\n\"; }} ?>",
"e": 2317,
"s": 1919,
"text": null
},
{
"code": null,
"e": 2321,
"s": 2317,
"text": "No\n"
},
{
"code": null,
"e": 2384,
"s": 2321,
"text": "References : http://php.net/manual/en/function.ctype-upper.php"
},
{
"code": null,
"e": 2397,
"s": 2384,
"text": "PHP-function"
},
{
"code": null,
"e": 2408,
"s": 2397,
"text": "PHP-string"
},
{
"code": null,
"e": 2412,
"s": 2408,
"text": "PHP"
},
{
"code": null,
"e": 2429,
"s": 2412,
"text": "Web Technologies"
},
{
"code": null,
"e": 2433,
"s": 2429,
"text": "PHP"
}
] |
Sentiment Classification Using BERT
|
08 Sep, 2021
BERT stands for Bidirectional Representation for Transformers, was proposed by researchers at Google AI language in 2018. Although the main aim of that was to improve the understanding of the meaning of queries related to Google Search, BERT becomes one of the most important and complete architecture for various natural language tasks having generated state-of-the-art results on Sentence pair classification task, question-answer task, etc. For more details on the architecture please look at this article
Architecture:
One of the most important features of BERT is that its adaptability to perform different NLP tasks with state-of-the-art accuracy (similar to the transfer learning we used in Computer vision). For that, the paper also proposed the architecture of different tasks. In this post, we will be using BERT architecture for single sentence classification tasks specifically the architecture used for CoLA (Corpus of Linguistic Acceptability) binary classification task. In the previous post about BERT, we discussed BERT architecture in detail, but let’s recap some of the important details of it:
BERT single sentence classification task
BERT has proposed in the two versions:
BERT (BASE): 12 layers of encoder stack with 12 bidirectional self-attention heads and 768 hidden units.
BERT (LARGE): 24 layers of encoder stack with 24 bidirectional self-attention heads and 1024 hidden units.
For TensorFlow implementation, Google has provided two versions of both the BERT BASE and BERT LARGE: Uncased and Cased. In an uncased version, letters are lowercased before WordPiece tokenization.
Implementation:
First, we need to clone the GitHub repo to BERT to make the setup easier.
Code:
python3
! git clone https://github.com / google-research / bert.git
Cloning into 'bert'...
remote: Enumerating objects: 340, done.
remote: Total 340 (delta 0), reused 0 (delta 0), pack-reused 340
Receiving objects: 100% (340/340), 317.20 KiB | 584.00 KiB/s, done.
Resolving deltas: 100% (185/185), done.
Now, we need to download the BERTBASE model using the following link and unzip it into the working directory ( or the desired location).
Code:
python3
# Download BERT BASE model from tF hub ! wget https://storage.googleapis.com / bert_models / 2018_10_18 / uncased_L-12_H-768_A-12.zip ! unzip uncased_L-12_H-768_A-12.zip
Archive: uncased_L-12_H-768_A-12.zip
creating: uncased_L-12_H-768_A-12/
inflating: uncased_L-12_H-768_A-12/bert_model.ckpt.meta
inflating: uncased_L-12_H-768_A-12/bert_model.ckpt.data-00000-of-00001
inflating: uncased_L-12_H-768_A-12/vocab.txt
inflating: uncased_L-12_H-768_A-12/bert_model.ckpt.index
inflating: uncased_L-12_H-768_A-12/bert_config.json
We will be using the TensorFlow 1x version. In Google colab there is a magic function called tensorflow_version that can switch different versions.
Code:
python3
% tensorflow_version 1.x
TensorFlow 1.x selected.
Now, we will import modules necessary for running this project, we will be using NumPy, scikit-learn and Keras from TensorFlow inbuilt modules. These are already preinstalled in colab, make sure to install these in your environment.
Code:
python3
import osimport reimport numpy as npimport pandas as pdfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_splitimport tensorflow as tffrom tensorflow import kerasimport csvfrom sklearn import metrics
Now we will load IMDB sentiments datasets and do some preprocessing before training. For loading the IMDB dataset from TensorFlow Hub, we will follow this tutorial.
Code:
python3
# load data from positive and negative directories and a columns that takes there\# positive and negative labeldef load_directory_data(directory): data = {} data["sentence"] = [] data["sentiment"] = [] for file_path in os.listdir(directory): with tf.gfile.GFile(os.path.join(directory, file_path), "r") as f: data["sentence"].append(f.read()) data["sentiment"].append(re.match("\d+_(\d+)\.txt", file_path).group(1)) return pd.DataFrame.from_dict(data) # Merge positive and negative examples, add a polarity column and shuffle.def load_dataset(directory): pos_df = load_directory_data(os.path.join(directory, "pos")) neg_df = load_directory_data(os.path.join(directory, "neg")) pos_df["polarity"] = 1 neg_df["polarity"] = 0 return pd.concat([pos_df, neg_df]).sample(frac = 1).reset_index(drop = True) # Download and process the dataset files.def download_and_load_datasets(force_download = False): dataset = tf.keras.utils.get_file( fname ="aclImdb.tar.gz", origin ="http://ai.stanford.edu/~amaas / data / sentiment / aclImdb_v1.tar.gz", extract = True) train_df = load_dataset(os.path.join(os.path.dirname(dataset), "aclImdb", "train")) test_df = load_dataset(os.path.join(os.path.dirname(dataset), "aclImdb", "test")) return train_df, test_dftrain, test = download_and_load_datasets()train.shape, test.shape
Downloading data from http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
84131840/84125825 [==============================] - 8s 0us/step
((25000, 3), (25000, 3))
This dataset contains 50k reviews 25k for each training and test, we will sample 5k reviews from each test and train. Also, both test and train dataset contains 3 columns whose list is given below
Code:
python3
# sample 5k datapoints for both train and testtrain = train.sample(5000)test = test.sample(5000)# List columns of train and test datatrain.columns, test.columns
(Index(['sentence', 'sentiment', 'polarity'], dtype='object'),
Index(['sentence', 'sentiment', 'polarity'], dtype='object'))
Now, we need to convert the specific format that is required by the BERT model to train and predict, for that we will use pandas dataframe. Below are the columns required in BERT training and test format:GUID: An id for the row. Required for both train and test dataClass label.: A value of 0 or 1 depending on positive and negative sentiment.alpha: This is a dummy column for text classification but is expected by BERT during training.text: The review text of the data point which needed to be classified. Obviously required for both training and test
GUID: An id for the row. Required for both train and test data
Class label.: A value of 0 or 1 depending on positive and negative sentiment.
alpha: This is a dummy column for text classification but is expected by BERT during training.
text: The review text of the data point which needed to be classified. Obviously required for both training and test
Code:
python3
# code# Convert training data into BERT formattrain_bert = pd.DataFrame({ 'guid': range(len(train)), 'label':train['polarity'], 'alpha': ['a']*train.shape[0], 'text': train['sentence'].replace(r'\n', '', regex = True)}) train_bert.head()print("-----")# convert test data into bert formatbert_test = pd.DataFrame({ 'id':range(len(test)), 'text': test['sentence'].replace(r'\n', ' ', regex = True)})bert_test.head()
guid label alpha text
14930 0 1 a William Hurt may not be an American matinee id...
1445 1 1 a Rock solid giallo from a master filmmaker of t...
16943 2 1 a This movie surprised me. Some things were "cli...
6391 3 1 a This film may seem dated today, but remember t...
4526 4 0 a The Twilight Zone has achieved a certain mytho...
-----
guid text
20010 0 One of Alfred Hitchcock's three greatest films...
16132 1 Hitchcock once gave an interview where he said...
24947 2 I had nothing to do before going out one night...
5471 3 tell you what that was excellent. Dylan Moran ...
21075 4 I watched this show until my puberty but still...
Now, we split the data into three parts: train, dev, and test and save it into tsv file save it into a folder (here “IMDB Dataset”). This is because run classifier file requires dataset in tsv format.
Code:
python3
# split data into train and validation setbert_train, bert_val = train_test_split(train_bert, test_size = 0.1)# save train, validation and testfile to afolderbert_train.to_csv('bert / IMDB_dataset / train.tsv', sep ='\t', index = False, header = False)bert_val.to_csv('bert / IMDB_dataset / dev.tsv', sep ='\t', index = False, header = False)bert_test.to_csv('bert / IMDB_dataset / test.tsv', sep ='\t', index = False, header = True)
In this step, we train the model using the following command, for executing bash commands on colab, we use ! sign in front of the command. The run_classifier file trains the model with the help of given command. Due to time and resource constraints, we will run it only on 3 epochs.
Code:
python3
# Most of the arguments hereare self-explanatory but some arguments needs to be explained:# task name:We have discussed this above .Here we need toperform binary classification that why we use cola# vocab file : A vocab file (vocab.txt) to map WordPiece to word id.# init checkpoint: A tensorflow checkpoint required. Here we used downloaded bert.# max_seq_length :caps the maximunumber of words to each reviews# bert_config_file: file contains hyperparameter settings ! python bert / run_classifier.py--task_name = cola --do_train = true --do_eval = true--data_dir =/content / bert / IMDB_dataset--vocab_file =/content / uncased_L-12_H-768_A-12 / vocab.txt--bert_config_file =/content / uncased_L-12_H-768_A-12 / bert_config.json--init_checkpoint =/content / uncased_L-12_H-768_A-12 / bert_model.ckpt--max_seq_length = 64--train_batch_size = 8 --learning_rate = 2e-5--num_train_epochs = 3.0--output_dir =/content / bert_output/--do_lower_case = True--save_checkpoints_steps 10000
# Last few lines
INFO:tensorflow:***** Eval results *****
I0713 06:06:28.966619 139722620139392 run_classifier.py:923] ***** Eval results *****
INFO:tensorflow: eval_accuracy = 0.796
I0713 06:06:28.966814 139722620139392 run_classifier.py:925] eval_accuracy = 0.796
INFO:tensorflow: eval_loss = 0.95403963
I0713 06:06:28.967138 139722620139392 run_classifier.py:925] eval_loss = 0.95403963
INFO:tensorflow: global_step = 1687
I0713 06:06:28.967317 139722620139392 run_classifier.py:925] global_step = 1687
INFO:tensorflow: loss = 0.95741796
I0713 06:06:28.967507 139722620139392 run_classifier.py:925] loss = 0.95741796
Now we will use test data to evaluate our model with the following bash script. This script saves the predictions into a tsv file.
Code:
python3
# code to predict bert on test.tsv# here we use saved training checkpoint as initial model ! python bert / run_classifier.py--task_name = cola--do_predict = true--data_dir =/content / bert / IMDB_dataset--vocab_file =/content / uncased_L-12_H-768_A-12 / vocab.txt--bert_config_file =/content / uncased_L-12_H-768_A-12 / bert_config.json--init_checkpoint =/content / bert_output / model.ckpt-0--max_seq_length = 128--output_dir =/content / bert_output/
INFO:tensorflow:Restoring parameters from /content/bert_output/model.ckpt-1687
I0713 06:08:22.372014 140390020667264 saver.py:1284] Restoring parameters from /content/bert_output/model.ckpt-1687
INFO:tensorflow:Running local_init_op.
I0713 06:08:23.801442 140390020667264 session_manager.py:500] Running local_init_op.
INFO:tensorflow:Done running local_init_op.
I0713 06:08:23.859703 140390020667264 session_manager.py:502] Done running local_init_op.
2020-07-13 06:08:24.453814: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10
INFO:tensorflow:prediction_loop marked as finished
I0713 06:10:02.280455 140390020667264 error_handling.py:101] prediction_loop marked as finished
INFO:tensorflow:prediction_loop marked as finished
I0713 06:10:02.280870 140390020667264 error_handling.py:101] prediction_loop marked as finished
The code below takes maximum prediction for each row of test data and store it into a list.
Code:
python3
# codeimport csvlabel_results =[]with open('/content / bert_output / test_results.tsv') as file: rows = csv.reader(file, delimiter ="\t") for row in rows: data_1 =[float(i) for i in row] label_results.append(data_1.index(max(data_1)))
The code below calculates accuracy and F1-score.
Code:
python3
print("Accuracy", metrics.accuracy_score(test['polarity'], label_results))print("F1-Score", metrics.f1_score(test['polarity'], label_results))
Accuracy 0.8548
F1-Score 0.8496894409937888
We have achieved 85% accuracy and F1-score on the IMDB reviews dataset while training BERT (BASE) just for 3 epochs which is quite a good result. Training on more epochs will certainly improve the accuracy.
References:
BERT paper
Google BERT repo
MC.ai BERT text classification
simmytarika5
abhishek0719kadiyan
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 537,
"s": 28,
"text": "BERT stands for Bidirectional Representation for Transformers, was proposed by researchers at Google AI language in 2018. Although the main aim of that was to improve the understanding of the meaning of queries related to Google Search, BERT becomes one of the most important and complete architecture for various natural language tasks having generated state-of-the-art results on Sentence pair classification task, question-answer task, etc. For more details on the architecture please look at this article"
},
{
"code": null,
"e": 551,
"s": 537,
"text": "Architecture:"
},
{
"code": null,
"e": 1142,
"s": 551,
"text": "One of the most important features of BERT is that its adaptability to perform different NLP tasks with state-of-the-art accuracy (similar to the transfer learning we used in Computer vision). For that, the paper also proposed the architecture of different tasks. In this post, we will be using BERT architecture for single sentence classification tasks specifically the architecture used for CoLA (Corpus of Linguistic Acceptability) binary classification task. In the previous post about BERT, we discussed BERT architecture in detail, but let’s recap some of the important details of it:"
},
{
"code": null,
"e": 1183,
"s": 1142,
"text": "BERT single sentence classification task"
},
{
"code": null,
"e": 1222,
"s": 1183,
"text": "BERT has proposed in the two versions:"
},
{
"code": null,
"e": 1327,
"s": 1222,
"text": "BERT (BASE): 12 layers of encoder stack with 12 bidirectional self-attention heads and 768 hidden units."
},
{
"code": null,
"e": 1434,
"s": 1327,
"text": "BERT (LARGE): 24 layers of encoder stack with 24 bidirectional self-attention heads and 1024 hidden units."
},
{
"code": null,
"e": 1632,
"s": 1434,
"text": "For TensorFlow implementation, Google has provided two versions of both the BERT BASE and BERT LARGE: Uncased and Cased. In an uncased version, letters are lowercased before WordPiece tokenization."
},
{
"code": null,
"e": 1648,
"s": 1632,
"text": "Implementation:"
},
{
"code": null,
"e": 1722,
"s": 1648,
"text": "First, we need to clone the GitHub repo to BERT to make the setup easier."
},
{
"code": null,
"e": 1729,
"s": 1722,
"text": "Code: "
},
{
"code": null,
"e": 1737,
"s": 1729,
"text": "python3"
},
{
"code": "! git clone https://github.com / google-research / bert.git",
"e": 1797,
"s": 1737,
"text": null
},
{
"code": null,
"e": 2033,
"s": 1797,
"text": "Cloning into 'bert'...\nremote: Enumerating objects: 340, done.\nremote: Total 340 (delta 0), reused 0 (delta 0), pack-reused 340\nReceiving objects: 100% (340/340), 317.20 KiB | 584.00 KiB/s, done.\nResolving deltas: 100% (185/185), done."
},
{
"code": null,
"e": 2170,
"s": 2033,
"text": "Now, we need to download the BERTBASE model using the following link and unzip it into the working directory ( or the desired location)."
},
{
"code": null,
"e": 2177,
"s": 2170,
"text": "Code: "
},
{
"code": null,
"e": 2185,
"s": 2177,
"text": "python3"
},
{
"code": "# Download BERT BASE model from tF hub ! wget https://storage.googleapis.com / bert_models / 2018_10_18 / uncased_L-12_H-768_A-12.zip ! unzip uncased_L-12_H-768_A-12.zip",
"e": 2355,
"s": 2185,
"text": null
},
{
"code": null,
"e": 2732,
"s": 2355,
"text": "Archive: uncased_L-12_H-768_A-12.zip\n creating: uncased_L-12_H-768_A-12/\n inflating: uncased_L-12_H-768_A-12/bert_model.ckpt.meta \n inflating: uncased_L-12_H-768_A-12/bert_model.ckpt.data-00000-of-00001 \n inflating: uncased_L-12_H-768_A-12/vocab.txt \n inflating: uncased_L-12_H-768_A-12/bert_model.ckpt.index \n inflating: uncased_L-12_H-768_A-12/bert_config.json "
},
{
"code": null,
"e": 2880,
"s": 2732,
"text": "We will be using the TensorFlow 1x version. In Google colab there is a magic function called tensorflow_version that can switch different versions."
},
{
"code": null,
"e": 2887,
"s": 2880,
"text": "Code: "
},
{
"code": null,
"e": 2895,
"s": 2887,
"text": "python3"
},
{
"code": "% tensorflow_version 1.x",
"e": 2920,
"s": 2895,
"text": null
},
{
"code": null,
"e": 2945,
"s": 2920,
"text": "TensorFlow 1.x selected."
},
{
"code": null,
"e": 3178,
"s": 2945,
"text": "Now, we will import modules necessary for running this project, we will be using NumPy, scikit-learn and Keras from TensorFlow inbuilt modules. These are already preinstalled in colab, make sure to install these in your environment."
},
{
"code": null,
"e": 3185,
"s": 3178,
"text": "Code: "
},
{
"code": null,
"e": 3193,
"s": 3185,
"text": "python3"
},
{
"code": "import osimport reimport numpy as npimport pandas as pdfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_splitimport tensorflow as tffrom tensorflow import kerasimport csvfrom sklearn import metrics",
"e": 3435,
"s": 3193,
"text": null
},
{
"code": null,
"e": 3601,
"s": 3435,
"text": "Now we will load IMDB sentiments datasets and do some preprocessing before training. For loading the IMDB dataset from TensorFlow Hub, we will follow this tutorial. "
},
{
"code": null,
"e": 3608,
"s": 3601,
"text": "Code: "
},
{
"code": null,
"e": 3616,
"s": 3608,
"text": "python3"
},
{
"code": "# load data from positive and negative directories and a columns that takes there\\# positive and negative labeldef load_directory_data(directory): data = {} data[\"sentence\"] = [] data[\"sentiment\"] = [] for file_path in os.listdir(directory): with tf.gfile.GFile(os.path.join(directory, file_path), \"r\") as f: data[\"sentence\"].append(f.read()) data[\"sentiment\"].append(re.match(\"\\d+_(\\d+)\\.txt\", file_path).group(1)) return pd.DataFrame.from_dict(data) # Merge positive and negative examples, add a polarity column and shuffle.def load_dataset(directory): pos_df = load_directory_data(os.path.join(directory, \"pos\")) neg_df = load_directory_data(os.path.join(directory, \"neg\")) pos_df[\"polarity\"] = 1 neg_df[\"polarity\"] = 0 return pd.concat([pos_df, neg_df]).sample(frac = 1).reset_index(drop = True) # Download and process the dataset files.def download_and_load_datasets(force_download = False): dataset = tf.keras.utils.get_file( fname =\"aclImdb.tar.gz\", origin =\"http://ai.stanford.edu/~amaas / data / sentiment / aclImdb_v1.tar.gz\", extract = True) train_df = load_dataset(os.path.join(os.path.dirname(dataset), \"aclImdb\", \"train\")) test_df = load_dataset(os.path.join(os.path.dirname(dataset), \"aclImdb\", \"test\")) return train_df, test_dftrain, test = download_and_load_datasets()train.shape, test.shape",
"e": 5048,
"s": 3616,
"text": null
},
{
"code": null,
"e": 5223,
"s": 5048,
"text": "Downloading data from http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n84131840/84125825 [==============================] - 8s 0us/step\n((25000, 3), (25000, 3))"
},
{
"code": null,
"e": 5420,
"s": 5223,
"text": "This dataset contains 50k reviews 25k for each training and test, we will sample 5k reviews from each test and train. Also, both test and train dataset contains 3 columns whose list is given below"
},
{
"code": null,
"e": 5427,
"s": 5420,
"text": "Code: "
},
{
"code": null,
"e": 5435,
"s": 5427,
"text": "python3"
},
{
"code": "# sample 5k datapoints for both train and testtrain = train.sample(5000)test = test.sample(5000)# List columns of train and test datatrain.columns, test.columns",
"e": 5596,
"s": 5435,
"text": null
},
{
"code": null,
"e": 5722,
"s": 5596,
"text": "(Index(['sentence', 'sentiment', 'polarity'], dtype='object'),\n Index(['sentence', 'sentiment', 'polarity'], dtype='object'))"
},
{
"code": null,
"e": 6277,
"s": 5722,
"text": "Now, we need to convert the specific format that is required by the BERT model to train and predict, for that we will use pandas dataframe. Below are the columns required in BERT training and test format:GUID: An id for the row. Required for both train and test dataClass label.: A value of 0 or 1 depending on positive and negative sentiment.alpha: This is a dummy column for text classification but is expected by BERT during training.text: The review text of the data point which needed to be classified. Obviously required for both training and test"
},
{
"code": null,
"e": 6340,
"s": 6277,
"text": "GUID: An id for the row. Required for both train and test data"
},
{
"code": null,
"e": 6418,
"s": 6340,
"text": "Class label.: A value of 0 or 1 depending on positive and negative sentiment."
},
{
"code": null,
"e": 6513,
"s": 6418,
"text": "alpha: This is a dummy column for text classification but is expected by BERT during training."
},
{
"code": null,
"e": 6631,
"s": 6513,
"text": "text: The review text of the data point which needed to be classified. Obviously required for both training and test"
},
{
"code": null,
"e": 6638,
"s": 6631,
"text": "Code: "
},
{
"code": null,
"e": 6646,
"s": 6638,
"text": "python3"
},
{
"code": "# code# Convert training data into BERT formattrain_bert = pd.DataFrame({ 'guid': range(len(train)), 'label':train['polarity'], 'alpha': ['a']*train.shape[0], 'text': train['sentence'].replace(r'\\n', '', regex = True)}) train_bert.head()print(\"-----\")# convert test data into bert formatbert_test = pd.DataFrame({ 'id':range(len(test)), 'text': test['sentence'].replace(r'\\n', ' ', regex = True)})bert_test.head()",
"e": 7061,
"s": 6646,
"text": null
},
{
"code": null,
"e": 7797,
"s": 7061,
"text": "guid label alpha text\n14930 0 1 a William Hurt may not be an American matinee id...\n1445 1 1 a Rock solid giallo from a master filmmaker of t...\n16943 2 1 a This movie surprised me. Some things were \"cli...\n6391 3 1 a This film may seem dated today, but remember t...\n4526 4 0 a The Twilight Zone has achieved a certain mytho...\n-----\nguid text\n20010 0 One of Alfred Hitchcock's three greatest films...\n16132 1 Hitchcock once gave an interview where he said...\n24947 2 I had nothing to do before going out one night...\n5471 3 tell you what that was excellent. Dylan Moran ...\n21075 4 I watched this show until my puberty but still..."
},
{
"code": null,
"e": 7999,
"s": 7797,
"text": "Now, we split the data into three parts: train, dev, and test and save it into tsv file save it into a folder (here “IMDB Dataset”). This is because run classifier file requires dataset in tsv format."
},
{
"code": null,
"e": 8006,
"s": 7999,
"text": "Code: "
},
{
"code": null,
"e": 8014,
"s": 8006,
"text": "python3"
},
{
"code": "# split data into train and validation setbert_train, bert_val = train_test_split(train_bert, test_size = 0.1)# save train, validation and testfile to afolderbert_train.to_csv('bert / IMDB_dataset / train.tsv', sep ='\\t', index = False, header = False)bert_val.to_csv('bert / IMDB_dataset / dev.tsv', sep ='\\t', index = False, header = False)bert_test.to_csv('bert / IMDB_dataset / test.tsv', sep ='\\t', index = False, header = True)",
"e": 8450,
"s": 8014,
"text": null
},
{
"code": null,
"e": 8734,
"s": 8450,
"text": "In this step, we train the model using the following command, for executing bash commands on colab, we use ! sign in front of the command. The run_classifier file trains the model with the help of given command. Due to time and resource constraints, we will run it only on 3 epochs."
},
{
"code": null,
"e": 8741,
"s": 8734,
"text": "Code: "
},
{
"code": null,
"e": 8749,
"s": 8741,
"text": "python3"
},
{
"code": "# Most of the arguments hereare self-explanatory but some arguments needs to be explained:# task name:We have discussed this above .Here we need toperform binary classification that why we use cola# vocab file : A vocab file (vocab.txt) to map WordPiece to word id.# init checkpoint: A tensorflow checkpoint required. Here we used downloaded bert.# max_seq_length :caps the maximunumber of words to each reviews# bert_config_file: file contains hyperparameter settings ! python bert / run_classifier.py--task_name = cola --do_train = true --do_eval = true--data_dir =/content / bert / IMDB_dataset--vocab_file =/content / uncased_L-12_H-768_A-12 / vocab.txt--bert_config_file =/content / uncased_L-12_H-768_A-12 / bert_config.json--init_checkpoint =/content / uncased_L-12_H-768_A-12 / bert_model.ckpt--max_seq_length = 64--train_batch_size = 8 --learning_rate = 2e-5--num_train_epochs = 3.0--output_dir =/content / bert_output/--do_lower_case = True--save_checkpoints_steps 10000",
"e": 9737,
"s": 8749,
"text": null
},
{
"code": null,
"e": 10369,
"s": 9737,
"text": "# Last few lines\nINFO:tensorflow:***** Eval results *****\nI0713 06:06:28.966619 139722620139392 run_classifier.py:923] ***** Eval results *****\nINFO:tensorflow: eval_accuracy = 0.796\nI0713 06:06:28.966814 139722620139392 run_classifier.py:925] eval_accuracy = 0.796\nINFO:tensorflow: eval_loss = 0.95403963\nI0713 06:06:28.967138 139722620139392 run_classifier.py:925] eval_loss = 0.95403963\nINFO:tensorflow: global_step = 1687\nI0713 06:06:28.967317 139722620139392 run_classifier.py:925] global_step = 1687\nINFO:tensorflow: loss = 0.95741796\nI0713 06:06:28.967507 139722620139392 run_classifier.py:925] loss = 0.95741796"
},
{
"code": null,
"e": 10500,
"s": 10369,
"text": "Now we will use test data to evaluate our model with the following bash script. This script saves the predictions into a tsv file."
},
{
"code": null,
"e": 10507,
"s": 10500,
"text": "Code: "
},
{
"code": null,
"e": 10515,
"s": 10507,
"text": "python3"
},
{
"code": "# code to predict bert on test.tsv# here we use saved training checkpoint as initial model ! python bert / run_classifier.py--task_name = cola--do_predict = true--data_dir =/content / bert / IMDB_dataset--vocab_file =/content / uncased_L-12_H-768_A-12 / vocab.txt--bert_config_file =/content / uncased_L-12_H-768_A-12 / bert_config.json--init_checkpoint =/content / bert_output / model.ckpt-0--max_seq_length = 128--output_dir =/content / bert_output/",
"e": 10969,
"s": 10515,
"text": null
},
{
"code": null,
"e": 11860,
"s": 10969,
"text": "INFO:tensorflow:Restoring parameters from /content/bert_output/model.ckpt-1687\nI0713 06:08:22.372014 140390020667264 saver.py:1284] Restoring parameters from /content/bert_output/model.ckpt-1687\nINFO:tensorflow:Running local_init_op.\nI0713 06:08:23.801442 140390020667264 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0713 06:08:23.859703 140390020667264 session_manager.py:502] Done running local_init_op.\n2020-07-13 06:08:24.453814: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\nINFO:tensorflow:prediction_loop marked as finished\nI0713 06:10:02.280455 140390020667264 error_handling.py:101] prediction_loop marked as finished\nINFO:tensorflow:prediction_loop marked as finished\nI0713 06:10:02.280870 140390020667264 error_handling.py:101] prediction_loop marked as finished"
},
{
"code": null,
"e": 11952,
"s": 11860,
"text": "The code below takes maximum prediction for each row of test data and store it into a list."
},
{
"code": null,
"e": 11959,
"s": 11952,
"text": "Code: "
},
{
"code": null,
"e": 11967,
"s": 11959,
"text": "python3"
},
{
"code": "# codeimport csvlabel_results =[]with open('/content / bert_output / test_results.tsv') as file: rows = csv.reader(file, delimiter =\"\\t\") for row in rows: data_1 =[float(i) for i in row] label_results.append(data_1.index(max(data_1)))",
"e": 12219,
"s": 11967,
"text": null
},
{
"code": null,
"e": 12268,
"s": 12219,
"text": "The code below calculates accuracy and F1-score."
},
{
"code": null,
"e": 12275,
"s": 12268,
"text": "Code: "
},
{
"code": null,
"e": 12283,
"s": 12275,
"text": "python3"
},
{
"code": "print(\"Accuracy\", metrics.accuracy_score(test['polarity'], label_results))print(\"F1-Score\", metrics.f1_score(test['polarity'], label_results))",
"e": 12426,
"s": 12283,
"text": null
},
{
"code": null,
"e": 12470,
"s": 12426,
"text": "Accuracy 0.8548\nF1-Score 0.8496894409937888"
},
{
"code": null,
"e": 12679,
"s": 12470,
"text": "We have achieved 85% accuracy and F1-score on the IMDB reviews dataset while training BERT (BASE) just for 3 epochs which is quite a good result. Training on more epochs will certainly improve the accuracy."
},
{
"code": null,
"e": 12691,
"s": 12679,
"text": "References:"
},
{
"code": null,
"e": 12702,
"s": 12691,
"text": "BERT paper"
},
{
"code": null,
"e": 12719,
"s": 12702,
"text": "Google BERT repo"
},
{
"code": null,
"e": 12750,
"s": 12719,
"text": "MC.ai BERT text classification"
},
{
"code": null,
"e": 12763,
"s": 12750,
"text": "simmytarika5"
},
{
"code": null,
"e": 12783,
"s": 12763,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 12800,
"s": 12783,
"text": "Machine Learning"
},
{
"code": null,
"e": 12807,
"s": 12800,
"text": "Python"
},
{
"code": null,
"e": 12824,
"s": 12807,
"text": "Machine Learning"
}
] |
Analysis of Algorithms | Set 4 (Analysis of Loops)
|
13 Jul, 2022
We have discussed Asymptotic Analysis, Worst, Average and Best Cases and Asymptotic Notations in previous posts. In this post, an analysis of iterative programs with simple examples is discussed.
1) O(1): Time complexity of a function (or set of statements) is considered as O(1) if it doesn’t contain loop, recursion, and call to any other non-constant time function.
// set of non-recursive and non-loop statements
For example, swap() function has O(1) time complexity. A loop or recursion that runs a constant number of times is also considered as O(1). For example, the following loop is O(1).
// Here c is a constant
for (int i = 1; i <= c; i++) {
// some O(1) expressions
}
2) O(n): Time Complexity of a loop is considered as O(n) if the loop variables are incremented/decremented by a constant amount. For example following functions have O(n) time complexity.
// Here c is a positive integer constant
for (int i = 1; i <= n; i += c) {
// some O(1) expressions
}
for (int i = n; i > 0; i -= c) {
// some O(1) expressions
}
3) O(nc): Time complexity of nested loops is equal to the number of times the innermost statement is executed. For example, the following sample loops have O(n2) time complexity
for (int i = 1; i <=n; i += c) {
for (int j = 1; j <=n; j += c) {
// some O(1) expressions
}
}
for (int i = n; i > 0; i -= c) {
for (int j = i+1; j <=n; j += c) {
// some O(1) expressions
}
For example, Selection sort and Insertion Sort have O(n2) time complexity. 4) O(Logn) Time Complexity of a loop is considered as O(Logn) if the loop variables are divided/multiplied by a constant amount. And also for recursive call in recursive function the Time Complexity is considered as O(Logn).
for (int i = 1; i <=n; i *= c) {
// some O(1) expressions
}
for (int i = n; i > 0; i /= c) {
// some O(1) expressions
}
//Recursive function
void recurse(n)
{
if(n==0)
return;
else{
// some O(1) expressions
}
recurse(n-1);
}
For example, Binary Search(refer iterative implementation) has O(Logn) time complexity. Let us see mathematically how it is O(Log n). The series that we get in the first loop is 1, c, c2, c3, ... ck. If we put k equals to Logcn, we get cLogcn which is n. 5) O(LogLogn) Time Complexity of a loop is considered as O(LogLogn) if the loop variables are reduced/increased exponentially by a constant amount.
// Here c is a constant greater than 1
for (int i = 2; i <=n; i = pow(i, c)) {
// some O(1) expressions
}
//Here fun is sqrt or cuberoot or any other constant root
for (int i = n; i > 1; i = fun(i)) {
// some O(1) expressions
}
See this for mathematical details. How to combine the time complexities of consecutive loops? When there are consecutive loops, we calculate time complexity as a sum of time complexities of individual loops.
for (int i = 1; i <=m; i += c) {
// some O(1) expressions
}
for (int i = 1; i <=n; i += c) {
// some O(1) expressions
}
Time complexity of above code is O(m) + O(n) which is O(m+n)
If m == n, the time complexity becomes O(2n) which is O(n).
How to calculate time complexity when there are many if, else statements inside loops? As discussed here, worst-case time complexity is the most useful among best, average and worst. Therefore we need to consider the worst case. We evaluate the situation when values in if-else conditions cause a maximum number of statements to be executed. For example, consider the linear search function where we consider the case when an element is present at the end or not present at all. When the code is too complex to consider all if-else cases, we can get an upper bound by ignoring if-else and other complex control statements. How to calculate the time complexity of recursive functions? The time complexity of a recursive function can be written as a mathematical recurrence relation. To calculate time complexity, we must know how to solve recurrences. We will soon be discussing recurrence solving techniques as a separate post.
The following is a cheat sheet of the time complexities of various algorithms.
Algorithms Cheat Sheet
Quiz on Analysis of Algorithms
For more details, please refer:Design and Analysis of Algorithms.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
meghajatana
23603vaibhav2021
susobhanakhuli
shreyasnaphad
Complexity-analysis
Algorithms
Analysis
Articles
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jul, 2022"
},
{
"code": null,
"e": 250,
"s": 52,
"text": "We have discussed Asymptotic Analysis, Worst, Average and Best Cases and Asymptotic Notations in previous posts. In this post, an analysis of iterative programs with simple examples is discussed. "
},
{
"code": null,
"e": 425,
"s": 250,
"text": "1) O(1): Time complexity of a function (or set of statements) is considered as O(1) if it doesn’t contain loop, recursion, and call to any other non-constant time function. "
},
{
"code": null,
"e": 476,
"s": 425,
"text": " // set of non-recursive and non-loop statements"
},
{
"code": null,
"e": 659,
"s": 476,
"text": "For example, swap() function has O(1) time complexity. A loop or recursion that runs a constant number of times is also considered as O(1). For example, the following loop is O(1). "
},
{
"code": null,
"e": 763,
"s": 659,
"text": " // Here c is a constant \n for (int i = 1; i <= c; i++) { \n // some O(1) expressions\n }"
},
{
"code": null,
"e": 953,
"s": 763,
"text": "2) O(n): Time Complexity of a loop is considered as O(n) if the loop variables are incremented/decremented by a constant amount. For example following functions have O(n) time complexity. "
},
{
"code": null,
"e": 1152,
"s": 953,
"text": " // Here c is a positive integer constant \n for (int i = 1; i <= n; i += c) { \n // some O(1) expressions\n }\n\n for (int i = n; i > 0; i -= c) {\n // some O(1) expressions\n }"
},
{
"code": null,
"e": 1332,
"s": 1152,
"text": "3) O(nc): Time complexity of nested loops is equal to the number of times the innermost statement is executed. For example, the following sample loops have O(n2) time complexity "
},
{
"code": null,
"e": 1579,
"s": 1332,
"text": " \n for (int i = 1; i <=n; i += c) {\n for (int j = 1; j <=n; j += c) {\n // some O(1) expressions\n }\n }\n\n for (int i = n; i > 0; i -= c) {\n for (int j = i+1; j <=n; j += c) {\n // some O(1) expressions\n }"
},
{
"code": null,
"e": 1880,
"s": 1579,
"text": "For example, Selection sort and Insertion Sort have O(n2) time complexity. 4) O(Logn) Time Complexity of a loop is considered as O(Logn) if the loop variables are divided/multiplied by a constant amount. And also for recursive call in recursive function the Time Complexity is considered as O(Logn). "
},
{
"code": null,
"e": 2026,
"s": 1880,
"text": " for (int i = 1; i <=n; i *= c) {\n // some O(1) expressions\n }\n for (int i = n; i > 0; i /= c) {\n // some O(1) expressions\n }"
},
{
"code": null,
"e": 2163,
"s": 2026,
"text": "//Recursive function\nvoid recurse(n)\n{\n if(n==0)\n return;\n else{\n // some O(1) expressions\n }\n recurse(n-1);\n}"
},
{
"code": null,
"e": 2568,
"s": 2163,
"text": "For example, Binary Search(refer iterative implementation) has O(Logn) time complexity. Let us see mathematically how it is O(Log n). The series that we get in the first loop is 1, c, c2, c3, ... ck. If we put k equals to Logcn, we get cLogcn which is n. 5) O(LogLogn) Time Complexity of a loop is considered as O(LogLogn) if the loop variables are reduced/increased exponentially by a constant amount. "
},
{
"code": null,
"e": 2833,
"s": 2568,
"text": " // Here c is a constant greater than 1 \n for (int i = 2; i <=n; i = pow(i, c)) { \n // some O(1) expressions\n }\n //Here fun is sqrt or cuberoot or any other constant root\n for (int i = n; i > 1; i = fun(i)) { \n // some O(1) expressions\n }"
},
{
"code": null,
"e": 3043,
"s": 2833,
"text": "See this for mathematical details. How to combine the time complexities of consecutive loops? When there are consecutive loops, we calculate time complexity as a sum of time complexities of individual loops. "
},
{
"code": null,
"e": 3323,
"s": 3043,
"text": " for (int i = 1; i <=m; i += c) { \n // some O(1) expressions\n }\n for (int i = 1; i <=n; i += c) {\n // some O(1) expressions\n }\n Time complexity of above code is O(m) + O(n) which is O(m+n)\n If m == n, the time complexity becomes O(2n) which is O(n). "
},
{
"code": null,
"e": 4252,
"s": 3323,
"text": "How to calculate time complexity when there are many if, else statements inside loops? As discussed here, worst-case time complexity is the most useful among best, average and worst. Therefore we need to consider the worst case. We evaluate the situation when values in if-else conditions cause a maximum number of statements to be executed. For example, consider the linear search function where we consider the case when an element is present at the end or not present at all. When the code is too complex to consider all if-else cases, we can get an upper bound by ignoring if-else and other complex control statements. How to calculate the time complexity of recursive functions? The time complexity of a recursive function can be written as a mathematical recurrence relation. To calculate time complexity, we must know how to solve recurrences. We will soon be discussing recurrence solving techniques as a separate post. "
},
{
"code": null,
"e": 4331,
"s": 4252,
"text": "The following is a cheat sheet of the time complexities of various algorithms."
},
{
"code": null,
"e": 4354,
"s": 4331,
"text": "Algorithms Cheat Sheet"
},
{
"code": null,
"e": 4386,
"s": 4354,
"text": "Quiz on Analysis of Algorithms "
},
{
"code": null,
"e": 4452,
"s": 4386,
"text": "For more details, please refer:Design and Analysis of Algorithms."
},
{
"code": null,
"e": 4577,
"s": 4452,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4589,
"s": 4577,
"text": "meghajatana"
},
{
"code": null,
"e": 4606,
"s": 4589,
"text": "23603vaibhav2021"
},
{
"code": null,
"e": 4621,
"s": 4606,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 4635,
"s": 4621,
"text": "shreyasnaphad"
},
{
"code": null,
"e": 4655,
"s": 4635,
"text": "Complexity-analysis"
},
{
"code": null,
"e": 4666,
"s": 4655,
"text": "Algorithms"
},
{
"code": null,
"e": 4675,
"s": 4666,
"text": "Analysis"
},
{
"code": null,
"e": 4684,
"s": 4675,
"text": "Articles"
},
{
"code": null,
"e": 4695,
"s": 4684,
"text": "Algorithms"
}
] |
How to create sticky table headers in Chrome ?
|
03 Jun, 2020
The headers of a table remain fixed at the top of the screen while you scroll down through the table are called the sticky table headers. They are used to help the viewers to know the purpose of data in the columns when the original headers are lost from the view. It eliminates the inconvenience of scrolling up and down the table to get the reference of the data being read. Here, we will be seeing how to create sticky table headers in a table.
Approach: The approach is to set the position property as sticky on the table headers so that they remain fixed at the top while scrolling down the table.
Example:
<!DOCTYPE html><html> <head> <title> How to create sticky table headers In Chrome? </title> <style> th { padding: 5px; background-color: #4cb96b; position: -webkit-sticky; position: sticky; top: 0; } </style></head> <body> <p> Below is a table which has sticky table headers </p> <table width="100%"> <thead> <th>CHARACTER</th> <th>ENCODED FORM</th> </thead> <tbody style="text-align: center;"> <tr> <td>backspace</td> <td>%08</td> </tr> <tr> <td>tab</td> <td>%09</td> </tr> <tr> <td>linefeed</td> <td>%0A</td> </tr> <tr> <td>c return</td> <td>%0D</td> </tr> <tr> <td>space</td> <td>%20</td> </tr> <tr> <td>!</td> <td>%21</td> </tr> <tr> <td>“</td> <td>%22</td> </tr> <tr> <td>#</td> <td>%23</td> </tr> <tr> <td>$</td> <td>%24</td> </tr> <tr> <td>%</td> <td>%25</td> </tr> <tr> <td>&</td> <td>%26</td> </tr> <tr> <td>‘</td> <td>%27</td> </tr> <tr> <td>(</td> <td>%28</td> </tr> <tr> <td>)</td> <td>%29</td> </tr> <tr> <td>*</td> <td>%2A</td> </tr> <tr> <td>+</td> <td>%2B</td> </tr> <tr> <td>,</td> <td>%2C</td> </tr> <tr> <td>–</td> <td>%2D</td> </tr> <tr> <td>.</td> <td>%2E</td> </tr> <tr> <td>/</td> <td>%2F</td> </tr> <tr> <td>0</td> <td>%30</td> </tr> <tr> <td>1</td> <td>%31</td> </tr> <tr> <td>2</td> <td>%32</td> </tr> <tr> <td>3</td> <td>%33</td> </tr> <tr> <td>4</td> <td>%34</td> </tr> <tr> <td>5</td> <td>%35</td> </tr> <tr> <td>6</td> <td>%36</td> </tr> <tr> <td>7</td> <td>%37</td> </tr> <tr> <td>8</td> <td>%38</td> </tr> <tr> <td>9</td> <td>%39</td> </tr> </tbody> </table></body> </html>
Output:
Explanation: position: sticky attribute is used to make the header fixed relative to the table body. Remember sticky is not applicable on <thead> or <tr> tags but can be used with <th>. So we style the position of <th> as sticky and set it a dark background color otherwise the transparency would have made the other data of the table visible behind the headers while scrolling down. The top attribute is set as 0 to make the header fixed at the top.
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 477,
"s": 28,
"text": "The headers of a table remain fixed at the top of the screen while you scroll down through the table are called the sticky table headers. They are used to help the viewers to know the purpose of data in the columns when the original headers are lost from the view. It eliminates the inconvenience of scrolling up and down the table to get the reference of the data being read. Here, we will be seeing how to create sticky table headers in a table. "
},
{
"code": null,
"e": 633,
"s": 477,
"text": "Approach: The approach is to set the position property as sticky on the table headers so that they remain fixed at the top while scrolling down the table. "
},
{
"code": null,
"e": 644,
"s": 633,
"text": "Example: "
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to create sticky table headers In Chrome? </title> <style> th { padding: 5px; background-color: #4cb96b; position: -webkit-sticky; position: sticky; top: 0; } </style></head> <body> <p> Below is a table which has sticky table headers </p> <table width=\"100%\"> <thead> <th>CHARACTER</th> <th>ENCODED FORM</th> </thead> <tbody style=\"text-align: center;\"> <tr> <td>backspace</td> <td>%08</td> </tr> <tr> <td>tab</td> <td>%09</td> </tr> <tr> <td>linefeed</td> <td>%0A</td> </tr> <tr> <td>c return</td> <td>%0D</td> </tr> <tr> <td>space</td> <td>%20</td> </tr> <tr> <td>!</td> <td>%21</td> </tr> <tr> <td>“</td> <td>%22</td> </tr> <tr> <td>#</td> <td>%23</td> </tr> <tr> <td>$</td> <td>%24</td> </tr> <tr> <td>%</td> <td>%25</td> </tr> <tr> <td>&</td> <td>%26</td> </tr> <tr> <td>‘</td> <td>%27</td> </tr> <tr> <td>(</td> <td>%28</td> </tr> <tr> <td>)</td> <td>%29</td> </tr> <tr> <td>*</td> <td>%2A</td> </tr> <tr> <td>+</td> <td>%2B</td> </tr> <tr> <td>,</td> <td>%2C</td> </tr> <tr> <td>–</td> <td>%2D</td> </tr> <tr> <td>.</td> <td>%2E</td> </tr> <tr> <td>/</td> <td>%2F</td> </tr> <tr> <td>0</td> <td>%30</td> </tr> <tr> <td>1</td> <td>%31</td> </tr> <tr> <td>2</td> <td>%32</td> </tr> <tr> <td>3</td> <td>%33</td> </tr> <tr> <td>4</td> <td>%34</td> </tr> <tr> <td>5</td> <td>%35</td> </tr> <tr> <td>6</td> <td>%36</td> </tr> <tr> <td>7</td> <td>%37</td> </tr> <tr> <td>8</td> <td>%38</td> </tr> <tr> <td>9</td> <td>%39</td> </tr> </tbody> </table></body> </html>",
"e": 3894,
"s": 644,
"text": null
},
{
"code": null,
"e": 3904,
"s": 3894,
"text": "Output: "
},
{
"code": null,
"e": 4358,
"s": 3906,
"text": "Explanation: position: sticky attribute is used to make the header fixed relative to the table body. Remember sticky is not applicable on <thead> or <tr> tags but can be used with <th>. So we style the position of <th> as sticky and set it a dark background color otherwise the transparency would have made the other data of the table visible behind the headers while scrolling down. The top attribute is set as 0 to make the header fixed at the top. "
},
{
"code": null,
"e": 4367,
"s": 4358,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4377,
"s": 4367,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4384,
"s": 4377,
"text": "Picked"
},
{
"code": null,
"e": 4388,
"s": 4384,
"text": "CSS"
},
{
"code": null,
"e": 4393,
"s": 4388,
"text": "HTML"
},
{
"code": null,
"e": 4410,
"s": 4393,
"text": "Web Technologies"
},
{
"code": null,
"e": 4437,
"s": 4410,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4442,
"s": 4437,
"text": "HTML"
}
] |
Map Reduce in Hadoop
|
04 Apr, 2019
One of the three components of Hadoop is Map Reduce. The first component of Hadoop that is, Hadoop Distributed File System (HDFS) is responsible for storing the file. The second component that is, Map Reduce is responsible for processing the file.
Suppose there is a word file containing some text. Let us name this file as sample.txt. Note that we use Hadoop to deal with huge files but for the sake of easy explanation over here, we are taking a text file as an example. So, let’s assume that this sample.txt file contains few lines as text. The content of the file is as follows:
Hello I am GeeksforGeeks
How can I help you
How can I assist you
Are you an engineer
Are you looking for coding
Are you looking for interview questions
what are you doing these days
what are your strengths
Hence, the above 8 lines are the content of the file. Let’s assume that while storing this file in Hadoop, HDFS broke this file into four parts and named each part as first.txt, second.txt, third.txt, and fourth.txt. So, you can easily see that the above file will be divided into four equal parts and each part will contain 2 lines. First two lines will be in the file first.txt, next two lines in second.txt, next two in third.txt and the last two lines will be stored in fourth.txt. All these files will be stored in Data Nodes and the Name Node will contain the metadata about them. All this is the task of HDFS.
Now, suppose a user wants to process this file. Here is what Map-Reduce comes into the picture. Suppose this user wants to run a query on this sample.txt. So, instead of bringing sample.txt on the local computer, we will send this query on the data. To keep a track of our request, we use Job Tracker (a master service). Job Tracker traps our request and keeps a track of it.
Now suppose that the user wants to run his query on sample.txt and want the output in result.output file. Let the name of the file containing the query is query.jar. So, the user will write a query like:
J$hadoop jar query.jar DriverCode sample.txt result.output
query.jar : query file that needs to be processed on the input file.sample.txt: input file.result.output: directory in which output of the processing will be received.
query.jar : query file that needs to be processed on the input file.
sample.txt: input file.
result.output: directory in which output of the processing will be received.
So, now the Job Tracker traps this request and asks Name Node to run this request on sample.txt. Name Node then provides the metadata to the Job Tracker. Job Tracker now knows that sample.txt is stored in first.txt, second.txt, third.txt, and fourth.txt. As all these four files have three copies stored in HDFS, so the Job Tracker communicates with the Task Tracker (a slave service) of each of these files but it communicates with only one copy of each file which is residing nearest to it.
Note: Applying the desired code on local first.txt, second.txt, third.txt and fourth.txt is a process., This process is called Map.
In Hadoop terminology, the main file sample.txt is called input file and its four subfiles are called input splits. So, in Hadoop the number of mappers for an input file are equal to number of input splits of this input file. In the above case, the input file sample.txt has four input splits hence four mappers will be running to process it. The responsibility of handling these mappers is of Job Tracker.
Note that the task trackers are slave services to the Job Tracker. So, in case any of the local machines breaks down then the processing over that part of the file will stop and it will halt the complete process. So, each task tracker sends heartbeat and its number of slots to Job Tracker in every 3 seconds. This is called the status of Task Trackers. In case any task tracker goes down, the Job Tracker then waits for 10 heartbeat times, that is, 30 seconds, and even after that if it does not get any status, then it assumes that either the task tracker is dead or is extremely busy. So it then communicates with the task tracker of another copy of the same file and directs it to process the desired code over it. Similarly, the slot information is used by the Job Tracker to keep a track of how many tasks are being currently served by the task tracker and how many more tasks can be assigned to it. In this way, the Job Tracker keeps track of our request.Now, suppose that the system has generated output for individual first.txt, second.txt, third.txt, and fourth.txt. But this is not the user’s desired output. To produce the desired output, all these individual outputs have to be merged or reduced to a single output. This reduction of multiple outputs to a single one is also a process which is done by REDUCER. In Hadoop, as many reducers are there, those many number of output files are generated. By default, there is always one reducer per cluster.
Note: Map and Reduce are two different processes of the second component of Hadoop, that is, Map Reduce. These are also called phases of Map Reduce. Thus we can say that Map Reduce has two phases. Phase 1 is Map and Phase 2 is Reduce.
Now, let us move back to our sample.txt file with the same content. Again it is being divided into four input splits namely, first.txt, second.txt, third.txt, and fourth.txt. Now, suppose we want to count number of each word in the file. That is the content of the file looks like:
Hello I am GeeksforGeeks
How can I help you
How can I assist you
Are you an engineer
Are you looking for coding
Are you looking for interview questions
what are you doing these days
what are your strengths
Then the output of the ‘word count’ code will be like:
Hello - 1
I - 1
am - 1
geeksforgeeks - 1
How - 2 (How is written two times in the entire file)
Similarly
Are - 3
are - 2
....and so on
Thus in order to get this output, the user will have to send his query on the data. Suppose the query ‘word count’ is in the file wordcount.jar. So, the query will look like:
J$hadoop jar wordcount.jar DriverCode sample.txt result.output
Now, as we know that there are four input splits, so four mappers will be running. One on each input split. But, Mappers don’t run directly on the input splits. It is because the input splits contain text but mappers don’t understand the text. Mappers understand (key, value) pairs only. Thus the text in input splits first needs to be converted to (key, value) pairs. This is achieved by Record Readers. Thus we can also say that as many numbers of input splits are there, those many numbers of record readers are there.
In Hadoop terminology, each line in a text is termed as a ‘record’. How record reader converts this text into (key, value) pair depends on the format of the file. In Hadoop, there are four formats of a file. These formats are Predefined Classes in Hadoop.
Four types of formats are:
TextInputFormatKeyValueTextInputFormatSequenceFileInputFormatSequenceFileAsTextInputFormat
TextInputFormat
KeyValueTextInputFormat
SequenceFileInputFormat
SequenceFileAsTextInputFormat
By default, a file is in TextInputFormat. Record reader reads one record(line) at a time. While reading, it doesn’t consider the format of the file. But, it converts each record into (key, value) pair depending upon its format. For the time being, let’s assume that the first input split first.txt is in TextInputFormat. Now, the record reader working on this input split converts the record in the form of (byte offset, entire line). For example first.txt has the content:
Hello I am GeeksforGeeks
How can I help you
So, the output of record reader has two pairs (since two records are there in the file). The first pair looks like (0, Hello I am geeksforgeeks) and the second pair looks like (26, How can I help you). Note that the second pair has the byte offset of 26 because there are 25 characters in the first line and the newline operator (\n) is also considered a character. Thus, after the record reader as many numbers of records is there, those many numbers of (key, value) pairs are there. Now, the mapper will run once for each of these pairs. Similarly, other mappers are also running for (key, value) pairs of different input splits. Thus in this way, Hadoop breaks a big task into smaller tasks and executes them in parallel execution.
Now, the mapper provides an output corresponding to each (key, value) pair provided by the record reader. Let us take the first input split of first.txt. The two pairs so generated for this file by the record reader are (0, Hello I am GeeksforGeeks) and (26, How can I help you). Now mapper takes one of these pair at a time and produces output like (Hello, 1), (I, 1), (am, 1) and (GeeksforGeeks, 1) for the first pair and (How, 1), (can, 1), (I, 1), (help, 1) and (you, 1) for the second pair. Similarly, we have outputs of all the mappers. Note that this data contains duplicate keys like (I, 1) and further (how, 1) etc. These duplicate keys also need to be taken care of. This data is also called Intermediate Data. Before passing this intermediate data to the reducer, it is first passed through two more stages, called Shuffling and Sorting.
Shuffling Phase: This phase combines all values associated to an identical key. For eg, (Are, 1) is there three times in the input file. So after the shuffling phase, the output will be like (Are, [1,1,1]).Sorting Phase: Once shuffling is done, the output is sent to the sorting phase where all the (key, value) pairs are sorted automatically. In Hadoop sorting is an automatic process because of the presence of an inbuilt interface called WritableComparableInterface.
Shuffling Phase: This phase combines all values associated to an identical key. For eg, (Are, 1) is there three times in the input file. So after the shuffling phase, the output will be like (Are, [1,1,1]).
Sorting Phase: Once shuffling is done, the output is sent to the sorting phase where all the (key, value) pairs are sorted automatically. In Hadoop sorting is an automatic process because of the presence of an inbuilt interface called WritableComparableInterface.
After the completion of the shuffling and sorting phase, the resultant output is then sent to the reducer. Now, if there are n (key, value) pairs after the shuffling and sorting phase, then the reducer runs n times and thus produces the final result in which the final processed output is there. In the above case, the resultant output after the reducer processing will get stored in the directory result.output as specified in the query code written to process the query on the data.
BigData
Hadoop
MapReduce
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 302,
"s": 54,
"text": "One of the three components of Hadoop is Map Reduce. The first component of Hadoop that is, Hadoop Distributed File System (HDFS) is responsible for storing the file. The second component that is, Map Reduce is responsible for processing the file."
},
{
"code": null,
"e": 637,
"s": 302,
"text": "Suppose there is a word file containing some text. Let us name this file as sample.txt. Note that we use Hadoop to deal with huge files but for the sake of easy explanation over here, we are taking a text file as an example. So, let’s assume that this sample.txt file contains few lines as text. The content of the file is as follows:"
},
{
"code": null,
"e": 844,
"s": 637,
"text": "Hello I am GeeksforGeeks\nHow can I help you\nHow can I assist you\nAre you an engineer\nAre you looking for coding\nAre you looking for interview questions\nwhat are you doing these days\nwhat are your strengths\n"
},
{
"code": null,
"e": 1461,
"s": 844,
"text": "Hence, the above 8 lines are the content of the file. Let’s assume that while storing this file in Hadoop, HDFS broke this file into four parts and named each part as first.txt, second.txt, third.txt, and fourth.txt. So, you can easily see that the above file will be divided into four equal parts and each part will contain 2 lines. First two lines will be in the file first.txt, next two lines in second.txt, next two in third.txt and the last two lines will be stored in fourth.txt. All these files will be stored in Data Nodes and the Name Node will contain the metadata about them. All this is the task of HDFS."
},
{
"code": null,
"e": 1837,
"s": 1461,
"text": "Now, suppose a user wants to process this file. Here is what Map-Reduce comes into the picture. Suppose this user wants to run a query on this sample.txt. So, instead of bringing sample.txt on the local computer, we will send this query on the data. To keep a track of our request, we use Job Tracker (a master service). Job Tracker traps our request and keeps a track of it."
},
{
"code": null,
"e": 2041,
"s": 1837,
"text": "Now suppose that the user wants to run his query on sample.txt and want the output in result.output file. Let the name of the file containing the query is query.jar. So, the user will write a query like:"
},
{
"code": null,
"e": 2100,
"s": 2041,
"text": "J$hadoop jar query.jar DriverCode sample.txt result.output"
},
{
"code": null,
"e": 2268,
"s": 2100,
"text": "query.jar : query file that needs to be processed on the input file.sample.txt: input file.result.output: directory in which output of the processing will be received."
},
{
"code": null,
"e": 2337,
"s": 2268,
"text": "query.jar : query file that needs to be processed on the input file."
},
{
"code": null,
"e": 2361,
"s": 2337,
"text": "sample.txt: input file."
},
{
"code": null,
"e": 2438,
"s": 2361,
"text": "result.output: directory in which output of the processing will be received."
},
{
"code": null,
"e": 2931,
"s": 2438,
"text": "So, now the Job Tracker traps this request and asks Name Node to run this request on sample.txt. Name Node then provides the metadata to the Job Tracker. Job Tracker now knows that sample.txt is stored in first.txt, second.txt, third.txt, and fourth.txt. As all these four files have three copies stored in HDFS, so the Job Tracker communicates with the Task Tracker (a slave service) of each of these files but it communicates with only one copy of each file which is residing nearest to it."
},
{
"code": null,
"e": 3063,
"s": 2931,
"text": "Note: Applying the desired code on local first.txt, second.txt, third.txt and fourth.txt is a process., This process is called Map."
},
{
"code": null,
"e": 3470,
"s": 3063,
"text": "In Hadoop terminology, the main file sample.txt is called input file and its four subfiles are called input splits. So, in Hadoop the number of mappers for an input file are equal to number of input splits of this input file. In the above case, the input file sample.txt has four input splits hence four mappers will be running to process it. The responsibility of handling these mappers is of Job Tracker."
},
{
"code": null,
"e": 4935,
"s": 3470,
"text": "Note that the task trackers are slave services to the Job Tracker. So, in case any of the local machines breaks down then the processing over that part of the file will stop and it will halt the complete process. So, each task tracker sends heartbeat and its number of slots to Job Tracker in every 3 seconds. This is called the status of Task Trackers. In case any task tracker goes down, the Job Tracker then waits for 10 heartbeat times, that is, 30 seconds, and even after that if it does not get any status, then it assumes that either the task tracker is dead or is extremely busy. So it then communicates with the task tracker of another copy of the same file and directs it to process the desired code over it. Similarly, the slot information is used by the Job Tracker to keep a track of how many tasks are being currently served by the task tracker and how many more tasks can be assigned to it. In this way, the Job Tracker keeps track of our request.Now, suppose that the system has generated output for individual first.txt, second.txt, third.txt, and fourth.txt. But this is not the user’s desired output. To produce the desired output, all these individual outputs have to be merged or reduced to a single output. This reduction of multiple outputs to a single one is also a process which is done by REDUCER. In Hadoop, as many reducers are there, those many number of output files are generated. By default, there is always one reducer per cluster."
},
{
"code": null,
"e": 5170,
"s": 4935,
"text": "Note: Map and Reduce are two different processes of the second component of Hadoop, that is, Map Reduce. These are also called phases of Map Reduce. Thus we can say that Map Reduce has two phases. Phase 1 is Map and Phase 2 is Reduce."
},
{
"code": null,
"e": 5452,
"s": 5170,
"text": "Now, let us move back to our sample.txt file with the same content. Again it is being divided into four input splits namely, first.txt, second.txt, third.txt, and fourth.txt. Now, suppose we want to count number of each word in the file. That is the content of the file looks like:"
},
{
"code": null,
"e": 5659,
"s": 5452,
"text": "Hello I am GeeksforGeeks\nHow can I help you\nHow can I assist you\nAre you an engineer\nAre you looking for coding\nAre you looking for interview questions\nwhat are you doing these days\nwhat are your strengths\n"
},
{
"code": null,
"e": 5714,
"s": 5659,
"text": "Then the output of the ‘word count’ code will be like:"
},
{
"code": null,
"e": 5851,
"s": 5714,
"text": "Hello - 1\nI - 1\nam - 1\ngeeksforgeeks - 1\nHow - 2 (How is written two times in the entire file) \nSimilarly\nAre - 3\nare - 2\n....and so on\n"
},
{
"code": null,
"e": 6026,
"s": 5851,
"text": "Thus in order to get this output, the user will have to send his query on the data. Suppose the query ‘word count’ is in the file wordcount.jar. So, the query will look like:"
},
{
"code": null,
"e": 6089,
"s": 6026,
"text": "J$hadoop jar wordcount.jar DriverCode sample.txt result.output"
},
{
"code": null,
"e": 6611,
"s": 6089,
"text": "Now, as we know that there are four input splits, so four mappers will be running. One on each input split. But, Mappers don’t run directly on the input splits. It is because the input splits contain text but mappers don’t understand the text. Mappers understand (key, value) pairs only. Thus the text in input splits first needs to be converted to (key, value) pairs. This is achieved by Record Readers. Thus we can also say that as many numbers of input splits are there, those many numbers of record readers are there."
},
{
"code": null,
"e": 6867,
"s": 6611,
"text": "In Hadoop terminology, each line in a text is termed as a ‘record’. How record reader converts this text into (key, value) pair depends on the format of the file. In Hadoop, there are four formats of a file. These formats are Predefined Classes in Hadoop."
},
{
"code": null,
"e": 6894,
"s": 6867,
"text": "Four types of formats are:"
},
{
"code": null,
"e": 6985,
"s": 6894,
"text": "TextInputFormatKeyValueTextInputFormatSequenceFileInputFormatSequenceFileAsTextInputFormat"
},
{
"code": null,
"e": 7001,
"s": 6985,
"text": "TextInputFormat"
},
{
"code": null,
"e": 7025,
"s": 7001,
"text": "KeyValueTextInputFormat"
},
{
"code": null,
"e": 7049,
"s": 7025,
"text": "SequenceFileInputFormat"
},
{
"code": null,
"e": 7079,
"s": 7049,
"text": "SequenceFileAsTextInputFormat"
},
{
"code": null,
"e": 7553,
"s": 7079,
"text": "By default, a file is in TextInputFormat. Record reader reads one record(line) at a time. While reading, it doesn’t consider the format of the file. But, it converts each record into (key, value) pair depending upon its format. For the time being, let’s assume that the first input split first.txt is in TextInputFormat. Now, the record reader working on this input split converts the record in the form of (byte offset, entire line). For example first.txt has the content:"
},
{
"code": null,
"e": 7598,
"s": 7553,
"text": "Hello I am GeeksforGeeks\nHow can I help you\n"
},
{
"code": null,
"e": 8333,
"s": 7598,
"text": "So, the output of record reader has two pairs (since two records are there in the file). The first pair looks like (0, Hello I am geeksforgeeks) and the second pair looks like (26, How can I help you). Note that the second pair has the byte offset of 26 because there are 25 characters in the first line and the newline operator (\\n) is also considered a character. Thus, after the record reader as many numbers of records is there, those many numbers of (key, value) pairs are there. Now, the mapper will run once for each of these pairs. Similarly, other mappers are also running for (key, value) pairs of different input splits. Thus in this way, Hadoop breaks a big task into smaller tasks and executes them in parallel execution."
},
{
"code": null,
"e": 9182,
"s": 8333,
"text": "Now, the mapper provides an output corresponding to each (key, value) pair provided by the record reader. Let us take the first input split of first.txt. The two pairs so generated for this file by the record reader are (0, Hello I am GeeksforGeeks) and (26, How can I help you). Now mapper takes one of these pair at a time and produces output like (Hello, 1), (I, 1), (am, 1) and (GeeksforGeeks, 1) for the first pair and (How, 1), (can, 1), (I, 1), (help, 1) and (you, 1) for the second pair. Similarly, we have outputs of all the mappers. Note that this data contains duplicate keys like (I, 1) and further (how, 1) etc. These duplicate keys also need to be taken care of. This data is also called Intermediate Data. Before passing this intermediate data to the reducer, it is first passed through two more stages, called Shuffling and Sorting."
},
{
"code": null,
"e": 9652,
"s": 9182,
"text": "Shuffling Phase: This phase combines all values associated to an identical key. For eg, (Are, 1) is there three times in the input file. So after the shuffling phase, the output will be like (Are, [1,1,1]).Sorting Phase: Once shuffling is done, the output is sent to the sorting phase where all the (key, value) pairs are sorted automatically. In Hadoop sorting is an automatic process because of the presence of an inbuilt interface called WritableComparableInterface."
},
{
"code": null,
"e": 9859,
"s": 9652,
"text": "Shuffling Phase: This phase combines all values associated to an identical key. For eg, (Are, 1) is there three times in the input file. So after the shuffling phase, the output will be like (Are, [1,1,1])."
},
{
"code": null,
"e": 10123,
"s": 9859,
"text": "Sorting Phase: Once shuffling is done, the output is sent to the sorting phase where all the (key, value) pairs are sorted automatically. In Hadoop sorting is an automatic process because of the presence of an inbuilt interface called WritableComparableInterface."
},
{
"code": null,
"e": 10608,
"s": 10123,
"text": "After the completion of the shuffling and sorting phase, the resultant output is then sent to the reducer. Now, if there are n (key, value) pairs after the shuffling and sorting phase, then the reducer runs n times and thus produces the final result in which the final processed output is there. In the above case, the resultant output after the reducer processing will get stored in the directory result.output as specified in the query code written to process the query on the data."
},
{
"code": null,
"e": 10616,
"s": 10608,
"text": "BigData"
},
{
"code": null,
"e": 10623,
"s": 10616,
"text": "Hadoop"
},
{
"code": null,
"e": 10633,
"s": 10623,
"text": "MapReduce"
},
{
"code": null,
"e": 10640,
"s": 10633,
"text": "Hadoop"
},
{
"code": null,
"e": 10647,
"s": 10640,
"text": "Hadoop"
}
] |
Python – API.user_timeline() in Tweepy
|
05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The user_timeline() method of the API class in Tweepy module is used to get the 20 most recent statuses posted from the authenticating user or the user specified.
Syntax : API.user_timeline(parameters)
Parameters :
id : specifies the ID or the screen name of the user.
user_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen name.
screen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user ID.
since_ids : Fetch only the statuses newer than the specified ID.
max_ids : Fetch only the statuses older than or equal to the specified ID.
count : The number of statuses to be fetched, the default value is 20.
Returns : a list of objects of the class Status
Example 1 :
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # screen name of the account to be fetchedscreen_name = "geeksforgeeks" # fetching the statusesstatuses = api.user_timeline(screen_name) print(str(len(statuses)) + " number of statuses have been fetched.")
Output :
20 number of statuses have been fetched.
Example 2: Using the user_timeline() method with the count parameter to fetch only a specified number of statuses.
# screen name of the account to be fetchedscreen_name = "geeksforgeeks" # number of statuses to be fetchedcount = 3 # fetching the statusesstatuses = api.user_timeline(screen_name, count = count) # printing the statusesfor status in statuses: print(status.text, end = "\n\n")
Output :
Hola Geeks!
.
Tell us what did you learned during this lockdown?
.
#MondayMotivation #mondaythoughts #codinglife... https://t.co/1mVLOKdaIL
@ZomatoIN Avoid Errors, not Client calls
#sundayvibes #programmingmemes
Avoid errors, not client calls
.
Geeks, Keep this going...
.
#sundayvibes #programming #programmingmemes #coding https://t.co/JkA5iStofZ
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 428,
"s": 28,
"text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication."
},
{
"code": null,
"e": 591,
"s": 428,
"text": "The user_timeline() method of the API class in Tweepy module is used to get the 20 most recent statuses posted from the authenticating user or the user specified."
},
{
"code": null,
"e": 630,
"s": 591,
"text": "Syntax : API.user_timeline(parameters)"
},
{
"code": null,
"e": 643,
"s": 630,
"text": "Parameters :"
},
{
"code": null,
"e": 697,
"s": 643,
"text": "id : specifies the ID or the screen name of the user."
},
{
"code": null,
"e": 820,
"s": 697,
"text": "user_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen name."
},
{
"code": null,
"e": 950,
"s": 820,
"text": "screen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user ID."
},
{
"code": null,
"e": 1015,
"s": 950,
"text": "since_ids : Fetch only the statuses newer than the specified ID."
},
{
"code": null,
"e": 1090,
"s": 1015,
"text": "max_ids : Fetch only the statuses older than or equal to the specified ID."
},
{
"code": null,
"e": 1161,
"s": 1090,
"text": "count : The number of statuses to be fetched, the default value is 20."
},
{
"code": null,
"e": 1209,
"s": 1161,
"text": "Returns : a list of objects of the class Status"
},
{
"code": null,
"e": 1221,
"s": 1209,
"text": "Example 1 :"
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # screen name of the account to be fetchedscreen_name = \"geeksforgeeks\" # fetching the statusesstatuses = api.user_timeline(screen_name) print(str(len(statuses)) + \" number of statuses have been fetched.\")",
"e": 1836,
"s": 1221,
"text": null
},
{
"code": null,
"e": 1845,
"s": 1836,
"text": "Output :"
},
{
"code": null,
"e": 1887,
"s": 1845,
"text": "20 number of statuses have been fetched.\n"
},
{
"code": null,
"e": 2002,
"s": 1887,
"text": "Example 2: Using the user_timeline() method with the count parameter to fetch only a specified number of statuses."
},
{
"code": "# screen name of the account to be fetchedscreen_name = \"geeksforgeeks\" # number of statuses to be fetchedcount = 3 # fetching the statusesstatuses = api.user_timeline(screen_name, count = count) # printing the statusesfor status in statuses: print(status.text, end = \"\\n\\n\")",
"e": 2284,
"s": 2002,
"text": null
},
{
"code": null,
"e": 2293,
"s": 2284,
"text": "Output :"
},
{
"code": null,
"e": 2645,
"s": 2293,
"text": "Hola Geeks!\n.\nTell us what did you learned during this lockdown?\n.\n#MondayMotivation #mondaythoughts #codinglife... https://t.co/1mVLOKdaIL\n\n@ZomatoIN Avoid Errors, not Client calls\n#sundayvibes #programmingmemes\n\nAvoid errors, not client calls\n.\nGeeks, Keep this going...\n.\n#sundayvibes #programming #programmingmemes #coding https://t.co/JkA5iStofZ\n"
},
{
"code": null,
"e": 2659,
"s": 2645,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 2666,
"s": 2659,
"text": "Python"
}
] |
Python unittest – assertIsNot() function
|
29 Aug, 2020
assertIsNot() in Python is a unittest library function that is used in unit testing to test whether first and second input value don’t evaluate to the same object or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both inputs don’t evaluate to the same object then assertIsNot() will return true else return false.
Syntax: assertIsNot(firstValue, secondValue, message)
Parameters: assertIsNot() accept three parameters which are listed below with explanation:
firstValue variable of any type which is used in the comparison by function
secondValue: variable of any type which is used in the comparison by function
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function def test_negative(self): firstValue = DummyClass() secondValue = firstValue # error message in case if test case got failed message = "First value & second value evaluates to same object !" # assertIs() to check that if first & second don't evaluated to same object self.assertIsNot(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "p1.py", line 15, in test_negative
self.assertIsNot(firstValue, secondValue, message)
AssertionError: unexpectedly identical: <__main__.DummyClass object at 0x7f75c2e33b70>
: First value & second value evaluates to same object!
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
Example 2: Positive Test case
Python3
# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function to test object equality of two value def test_positive(self): firstValue = DummyClass() secondValue = DummyClass() # error message in case if test case got failed message = "First value and second value evaluated to same object !" # assertIs() to check that if first & second don't evaluates to same object self.assertIsNot(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 417,
"s": 28,
"text": "assertIsNot() in Python is a unittest library function that is used in unit testing to test whether first and second input value don’t evaluate to the same object or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both inputs don’t evaluate to the same object then assertIsNot() will return true else return false."
},
{
"code": null,
"e": 471,
"s": 417,
"text": "Syntax: assertIsNot(firstValue, secondValue, message)"
},
{
"code": null,
"e": 562,
"s": 471,
"text": "Parameters: assertIsNot() accept three parameters which are listed below with explanation:"
},
{
"code": null,
"e": 639,
"s": 562,
"text": "firstValue variable of any type which is used in the comparison by function"
},
{
"code": null,
"e": 717,
"s": 639,
"text": "secondValue: variable of any type which is used in the comparison by function"
},
{
"code": null,
"e": 808,
"s": 717,
"text": "message: a string sentence as a message which got displayed when the test case got failed."
},
{
"code": null,
"e": 924,
"s": 808,
"text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:"
},
{
"code": null,
"e": 954,
"s": 924,
"text": "Example 1: Negative Test case"
},
{
"code": null,
"e": 962,
"s": 954,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function def test_negative(self): firstValue = DummyClass() secondValue = firstValue # error message in case if test case got failed message = \"First value & second value evaluates to same object !\" # assertIs() to check that if first & second don't evaluated to same object self.assertIsNot(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()",
"e": 1488,
"s": 962,
"text": null
},
{
"code": null,
"e": 1496,
"s": 1488,
"text": "Output:"
},
{
"code": null,
"e": 2074,
"s": 1496,
"text": "F\n======================================================================\nFAIL: test_negative (__main__.TestMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"p1.py\", line 15, in test_negative\n self.assertIsNot(firstValue, secondValue, message)\nAssertionError: unexpectedly identical: <__main__.DummyClass object at 0x7f75c2e33b70> \n: First value & second value evaluates to same object!\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures=1)\n\n"
},
{
"code": null,
"e": 2104,
"s": 2074,
"text": "Example 2: Positive Test case"
},
{
"code": null,
"e": 2112,
"s": 2104,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function to test object equality of two value def test_positive(self): firstValue = DummyClass() secondValue = DummyClass() # error message in case if test case got failed message = \"First value and second value evaluated to same object !\" # assertIs() to check that if first & second don't evaluates to same object self.assertIsNot(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()",
"e": 2678,
"s": 2112,
"text": null
},
{
"code": null,
"e": 2686,
"s": 2678,
"text": "Output:"
},
{
"code": null,
"e": 2787,
"s": 2686,
"text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n\n\n"
},
{
"code": null,
"e": 2846,
"s": 2787,
"text": "Reference: https://docs.python.org/3/library/unittest.html"
},
{
"code": null,
"e": 2870,
"s": 2846,
"text": "Python unittest-library"
},
{
"code": null,
"e": 2877,
"s": 2870,
"text": "Python"
},
{
"code": null,
"e": 2975,
"s": 2877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3007,
"s": 2975,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3034,
"s": 3007,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3055,
"s": 3034,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3078,
"s": 3055,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3109,
"s": 3078,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3165,
"s": 3109,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3207,
"s": 3165,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3249,
"s": 3207,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3288,
"s": 3249,
"text": "Python | Get unique values from a list"
}
] |
Java Program to Find the Determinant of a Matrix
|
08 Sep, 2021
The Determinant of a Matrix is a real number that can be defined for square matrices only i.e, the number of rows and columns of the matrices must be equal. Moreover, it is helpful in determining the system of the linear equation as well as figuring the inverse of the stated matrix.
Procedure to calculate:
First, we need to calculate the cofactor of all the elements of the matrix in the first row or first column.
Then, multiply each element of the first row or first column with their respective cofactor.
At last, we need to add them up with alternate signs.
Example:
Determinant of 2*2 matrix:
[4, 3]
[2, 3]
= (4*3)-(3*2)
= 12-6
= 6
Determinant of 3*3 matrix:
[1, 3, -2]
[-1, 2, 1]
[1, 0, -2]
= 1(-4-0)-3(2-1)+(-2)(0-2)
= -4-3+4
= -3
Note:
The determinant of 1*1 matrix is the element itself.The Cofactor of any element of the stated matrix can be calculated by eliminating the row and the column of that element from the matrix stated.
The determinant of 1*1 matrix is the element itself.
The Cofactor of any element of the stated matrix can be calculated by eliminating the row and the column of that element from the matrix stated.
Let’s see an example in order to get a clear concept of the above topic.
Example: Using Recursion
Java
// Java program to find// Determinant of a matrixclass GFG { // Dimension of input square matrix static final int N = 2; // Function to get cofactor of // mat[p][q] in temp[][]. n is // current dimension of mat[][] static void getCofactor(int mat[][], int temp[][], int p, int q, int n) { int i = 0, j = 0; // Looping for each element // of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix // only those element which are // not in given row and column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase // row index and reset col index if (j == n - 1) { j = 0; i++; } } } } } /* Recursive function for finding determinant of matrix. n is current dimension of mat[][]. */ static int determinantOfMatrix(int mat[][], int n) { int D = 0; // Initialize result // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors int temp[][] = new int[N][N]; // To store sign multiplier int sign = 1; // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // terms are to be added // with alternate sign sign = -sign; } return D; } /* function for displaying the matrix */ static void display(int mat[][], int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) System.out.print(mat[i][j]); System.out.print("\n"); } } // Driver code public static void main(String[] args) { int mat[][] = { { 4, 3 }, { 2, 3 } }; System.out.print("Determinant " + "of the matrix is : " + determinantOfMatrix(mat, N)); }}
Determinant of the matrix is : 6
Time complexity: O(n3)
Example: Non-recursion Implementation
Java
// Java program to find Determinant of a matrixclass GFG { // Dimension of input square matrix static final int N = 4; // Function to get determinant of matrix static int determinantOfMatrix(int mat[][], int n) { int num1, num2, det = 1, index, total = 1; // Initialize result // temporary array for storing row int[] temp = new int[n + 1]; // loop for traversing the diagonal elements for (int i = 0; i < n; i++) { index = i; // initialize the index // finding the index which has non zero value while (mat[index][i] == 0 && index < n) { index++; } if (index == n) // if there is non zero element { // the determinant of matrix as zero continue; } if (index != i) { // loop for swaping the diagonal element row // and index row for (int j = 0; j < n; j++) { swap(mat, index, j, i, j); } // determinant sign changes when we shift // rows go through determinant properties det = (int)(det * Math.pow(-1, index - i)); } // storing the values of diagonal row elements for (int j = 0; j < n; j++) { temp[j] = mat[i][j]; } // traversing every row below the diagonal // element for (int j = i + 1; j < n; j++) { num1 = temp[i]; // value of diagonal element num2 = mat[j] [i]; // value of next row element // traversing every column of row // and multiplying to every row for (int k = 0; k < n; k++) { // multiplying to make the diagonal // element and next row element equal mat[j][k] = (num1 * mat[j][k]) - (num2 * temp[k]); } total = total * num1; // Det(kA)=kDet(A); } } // multiplying the diagonal elements to get // determinant for (int i = 0; i < n; i++) { det = det * mat[i][i]; } return (det / total); // Det(kA)/k=Det(A); } static int[][] swap(int[][] arr, int i1, int j1, int i2, int j2) { int temp = arr[i1][j1]; arr[i1][j1] = arr[i2][j2]; arr[i2][j2] = temp; return arr; } // Driver code public static void main(String[] args) { int mat[][] = { { 1, 0, 2, -1 }, { 3, 0, 0, 5 }, { 2, 1, 4, -3 }, { 1, 0, 5, 0 } }; // Function call System.out.printf( "Determinant of the matrix is : %d", determinantOfMatrix(mat, N)); }}
Determinant of the matrix is : 30
Time complexity: O(n3)
simranarora5sos
rs1686740
java-basics
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 336,
"s": 52,
"text": "The Determinant of a Matrix is a real number that can be defined for square matrices only i.e, the number of rows and columns of the matrices must be equal. Moreover, it is helpful in determining the system of the linear equation as well as figuring the inverse of the stated matrix."
},
{
"code": null,
"e": 360,
"s": 336,
"text": "Procedure to calculate:"
},
{
"code": null,
"e": 469,
"s": 360,
"text": "First, we need to calculate the cofactor of all the elements of the matrix in the first row or first column."
},
{
"code": null,
"e": 562,
"s": 469,
"text": "Then, multiply each element of the first row or first column with their respective cofactor."
},
{
"code": null,
"e": 616,
"s": 562,
"text": "At last, we need to add them up with alternate signs."
},
{
"code": null,
"e": 625,
"s": 616,
"text": "Example:"
},
{
"code": null,
"e": 652,
"s": 625,
"text": "Determinant of 2*2 matrix:"
},
{
"code": null,
"e": 692,
"s": 652,
"text": "[4, 3]\n[2, 3]\n\n= (4*3)-(3*2)\n= 12-6\n= 6"
},
{
"code": null,
"e": 719,
"s": 692,
"text": "Determinant of 3*3 matrix:"
},
{
"code": null,
"e": 794,
"s": 719,
"text": "[1, 3, -2]\n[-1, 2, 1]\n[1, 0, -2]\n\n= 1(-4-0)-3(2-1)+(-2)(0-2)\n= -4-3+4\n= -3"
},
{
"code": null,
"e": 800,
"s": 794,
"text": "Note:"
},
{
"code": null,
"e": 997,
"s": 800,
"text": "The determinant of 1*1 matrix is the element itself.The Cofactor of any element of the stated matrix can be calculated by eliminating the row and the column of that element from the matrix stated."
},
{
"code": null,
"e": 1050,
"s": 997,
"text": "The determinant of 1*1 matrix is the element itself."
},
{
"code": null,
"e": 1195,
"s": 1050,
"text": "The Cofactor of any element of the stated matrix can be calculated by eliminating the row and the column of that element from the matrix stated."
},
{
"code": null,
"e": 1268,
"s": 1195,
"text": "Let’s see an example in order to get a clear concept of the above topic."
},
{
"code": null,
"e": 1293,
"s": 1268,
"text": "Example: Using Recursion"
},
{
"code": null,
"e": 1298,
"s": 1293,
"text": "Java"
},
{
"code": "// Java program to find// Determinant of a matrixclass GFG { // Dimension of input square matrix static final int N = 2; // Function to get cofactor of // mat[p][q] in temp[][]. n is // current dimension of mat[][] static void getCofactor(int mat[][], int temp[][], int p, int q, int n) { int i = 0, j = 0; // Looping for each element // of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix // only those element which are // not in given row and column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase // row index and reset col index if (j == n - 1) { j = 0; i++; } } } } } /* Recursive function for finding determinant of matrix. n is current dimension of mat[][]. */ static int determinantOfMatrix(int mat[][], int n) { int D = 0; // Initialize result // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors int temp[][] = new int[N][N]; // To store sign multiplier int sign = 1; // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // terms are to be added // with alternate sign sign = -sign; } return D; } /* function for displaying the matrix */ static void display(int mat[][], int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) System.out.print(mat[i][j]); System.out.print(\"\\n\"); } } // Driver code public static void main(String[] args) { int mat[][] = { { 4, 3 }, { 2, 3 } }; System.out.print(\"Determinant \" + \"of the matrix is : \" + determinantOfMatrix(mat, N)); }}",
"e": 3672,
"s": 1298,
"text": null
},
{
"code": null,
"e": 3705,
"s": 3672,
"text": "Determinant of the matrix is : 6"
},
{
"code": null,
"e": 3729,
"s": 3705,
"text": "Time complexity: O(n3) "
},
{
"code": null,
"e": 3768,
"s": 3729,
"text": "Example: Non-recursion Implementation "
},
{
"code": null,
"e": 3773,
"s": 3768,
"text": "Java"
},
{
"code": "// Java program to find Determinant of a matrixclass GFG { // Dimension of input square matrix static final int N = 4; // Function to get determinant of matrix static int determinantOfMatrix(int mat[][], int n) { int num1, num2, det = 1, index, total = 1; // Initialize result // temporary array for storing row int[] temp = new int[n + 1]; // loop for traversing the diagonal elements for (int i = 0; i < n; i++) { index = i; // initialize the index // finding the index which has non zero value while (mat[index][i] == 0 && index < n) { index++; } if (index == n) // if there is non zero element { // the determinant of matrix as zero continue; } if (index != i) { // loop for swaping the diagonal element row // and index row for (int j = 0; j < n; j++) { swap(mat, index, j, i, j); } // determinant sign changes when we shift // rows go through determinant properties det = (int)(det * Math.pow(-1, index - i)); } // storing the values of diagonal row elements for (int j = 0; j < n; j++) { temp[j] = mat[i][j]; } // traversing every row below the diagonal // element for (int j = i + 1; j < n; j++) { num1 = temp[i]; // value of diagonal element num2 = mat[j] [i]; // value of next row element // traversing every column of row // and multiplying to every row for (int k = 0; k < n; k++) { // multiplying to make the diagonal // element and next row element equal mat[j][k] = (num1 * mat[j][k]) - (num2 * temp[k]); } total = total * num1; // Det(kA)=kDet(A); } } // multiplying the diagonal elements to get // determinant for (int i = 0; i < n; i++) { det = det * mat[i][i]; } return (det / total); // Det(kA)/k=Det(A); } static int[][] swap(int[][] arr, int i1, int j1, int i2, int j2) { int temp = arr[i1][j1]; arr[i1][j1] = arr[i2][j2]; arr[i2][j2] = temp; return arr; } // Driver code public static void main(String[] args) { int mat[][] = { { 1, 0, 2, -1 }, { 3, 0, 0, 5 }, { 2, 1, 4, -3 }, { 1, 0, 5, 0 } }; // Function call System.out.printf( \"Determinant of the matrix is : %d\", determinantOfMatrix(mat, N)); }}",
"e": 6701,
"s": 3773,
"text": null
},
{
"code": null,
"e": 6735,
"s": 6701,
"text": "Determinant of the matrix is : 30"
},
{
"code": null,
"e": 6759,
"s": 6735,
"text": "Time complexity: O(n3) "
},
{
"code": null,
"e": 6777,
"s": 6761,
"text": "simranarora5sos"
},
{
"code": null,
"e": 6787,
"s": 6777,
"text": "rs1686740"
},
{
"code": null,
"e": 6799,
"s": 6787,
"text": "java-basics"
},
{
"code": null,
"e": 6804,
"s": 6799,
"text": "Java"
},
{
"code": null,
"e": 6818,
"s": 6804,
"text": "Java Programs"
},
{
"code": null,
"e": 6823,
"s": 6818,
"text": "Java"
}
] |
In Java, Can we call the main() method of a class from another class?
|
14 Feb, 2022
In Java, Can we call the main() method of a class from another class? OR How to call ‘public static void main(String[] args)’ method from our code?These are some questions that usually puzzles a Java programmer. This article aims to provide an answer to these problems in a simple and efficient way.As we know, the main() method for any Java application as the Java Run time environment calls the main() method first. So it is obvious that we don’t need to call the main() method by ourselves as it is already called when the program starts. But what if we want to call the main() method from somewhere in our program? That’s the problem.Solution:Though Java doesn’t prefer main() method called from somewhere else in the program, it does not prohibit one from doing it as well. So, in fact, we can call the main() method whenever and wherever we need to. But calling the main() method from our code is tricky. It can lead to many errors and exceptions, such as:
The main() method must be called from a static method only inside the same class.
Java
// Java method to show that the main() method// must be called from a static method only// inside the same class import java.io.*; class GFG { // The method that calls the main() method // Note that this method is not static void mainCaller() { System.out.println("mainCaller!"); // Calling the main() method main(null); } // main() method public static void main(String[] args) { System.out.println("main"); // Calling the mainCaller() method // so that main() method is called externally mainCaller(); }}
Compilation Error in java code:
prog.java:27: error: non-static method mainCaller()
cannot be referenced
from a static context
mainCaller();
^
1 error
The main() method must be passed the String[] args while calling it from somewhere else.
Java
// Java method to show that the main() method// must be passed the String[] args// while calling it from somewhere else import java.io.*; class GFG { // The method that calls the main() method static void mainCaller() { System.out.println("mainCaller!"); // Calling the main() method // Note that no parameter is passed main(); } // main() method public static void main(String[] args) { System.out.println("main"); // Calling the mainCaller() method // so that main() method is called externally mainCaller(); }}
Compilation Error in java code:
prog.java:17: error: method main in class GFG
cannot be applied to given types;
main();
^
required: String[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Calling the main() method will lead to an infinite loop as the memory stack knows to run only the main() method.
Java
// Java method to show that Calling the main() method// will lead to an infinite loop as the memory stack// knows to run only the main() method import java.io.*; class GFG { // The method that calls the main() method static void mainCaller() { System.out.println("mainCaller!"); // Calling the main() method main(null); } // main() method public static void main(String[] args) { System.out.println("main"); // Calling the mainCaller() method // so that main() method is called externally mainCaller(); }}
RunTime Error in java code:
RunTime Error in java code :-
Exception in thread "main" java.lang.StackOverflowError
mainCaller!
main
mainCaller!
main
mainCaller!
main
.
.
.
The right way to this:Example 1: Calling main() method externally from the same class
Java
// Java method to show Calling main() method// externally from the same class import java.io.*; class GFG { static int count = 0; // The method that calls the main() method static void mainCaller() { System.out.println("mainCaller!"); count++; // Calling the main() only 3 times if (count < 3) { // Calling the main() method main(null); } } // main() method public static void main(String[] args) { System.out.println("main"); // Calling the mainCaller() method // so that main() method is called externally mainCaller(); }}
Output:
main
mainCaller!
main
mainCaller!
main
mainCaller!
Example 1: Calling main() method externally from another class
Java
// Java method to show Calling main() method// externally from another class import java.io.*; class GFG { static int count = 0; // The method that calls the main() method static void mainCaller() { System.out.println("mainCaller!"); count++; // Calling the main() only 3 times if (count < 3) { // Calling the main() method Test.main(null); } }} class Test { // main() method public static void main(String[] args) { System.out.println("main"); // Calling the mainCaller() method // so that main() method is called externally GFG.mainCaller(); }}
Output:
main
mainCaller!
main
mainCaller!
main
mainCaller!
AshokJaiswal
arorakashish0911
main
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 1018,
"s": 54,
"text": "In Java, Can we call the main() method of a class from another class? OR How to call ‘public static void main(String[] args)’ method from our code?These are some questions that usually puzzles a Java programmer. This article aims to provide an answer to these problems in a simple and efficient way.As we know, the main() method for any Java application as the Java Run time environment calls the main() method first. So it is obvious that we don’t need to call the main() method by ourselves as it is already called when the program starts. But what if we want to call the main() method from somewhere in our program? That’s the problem.Solution:Though Java doesn’t prefer main() method called from somewhere else in the program, it does not prohibit one from doing it as well. So, in fact, we can call the main() method whenever and wherever we need to. But calling the main() method from our code is tricky. It can lead to many errors and exceptions, such as: "
},
{
"code": null,
"e": 1100,
"s": 1018,
"text": "The main() method must be called from a static method only inside the same class."
},
{
"code": null,
"e": 1105,
"s": 1100,
"text": "Java"
},
{
"code": "// Java method to show that the main() method// must be called from a static method only// inside the same class import java.io.*; class GFG { // The method that calls the main() method // Note that this method is not static void mainCaller() { System.out.println(\"mainCaller!\"); // Calling the main() method main(null); } // main() method public static void main(String[] args) { System.out.println(\"main\"); // Calling the mainCaller() method // so that main() method is called externally mainCaller(); }}",
"e": 1692,
"s": 1105,
"text": null
},
{
"code": null,
"e": 1724,
"s": 1692,
"text": "Compilation Error in java code:"
},
{
"code": null,
"e": 1901,
"s": 1724,
"text": "prog.java:27: error: non-static method mainCaller()\n cannot be referenced\n from a static context\n mainCaller();\n ^\n1 error"
},
{
"code": null,
"e": 1990,
"s": 1901,
"text": "The main() method must be passed the String[] args while calling it from somewhere else."
},
{
"code": null,
"e": 1995,
"s": 1990,
"text": "Java"
},
{
"code": "// Java method to show that the main() method// must be passed the String[] args// while calling it from somewhere else import java.io.*; class GFG { // The method that calls the main() method static void mainCaller() { System.out.println(\"mainCaller!\"); // Calling the main() method // Note that no parameter is passed main(); } // main() method public static void main(String[] args) { System.out.println(\"main\"); // Calling the mainCaller() method // so that main() method is called externally mainCaller(); }}",
"e": 2593,
"s": 1995,
"text": null
},
{
"code": null,
"e": 2625,
"s": 2593,
"text": "Compilation Error in java code:"
},
{
"code": null,
"e": 2863,
"s": 2625,
"text": "prog.java:17: error: method main in class GFG\n cannot be applied to given types;\n main();\n ^\n required: String[]\n found: no arguments\n reason: actual and formal argument lists differ in length\n1 error"
},
{
"code": null,
"e": 2976,
"s": 2863,
"text": "Calling the main() method will lead to an infinite loop as the memory stack knows to run only the main() method."
},
{
"code": null,
"e": 2981,
"s": 2976,
"text": "Java"
},
{
"code": "// Java method to show that Calling the main() method// will lead to an infinite loop as the memory stack// knows to run only the main() method import java.io.*; class GFG { // The method that calls the main() method static void mainCaller() { System.out.println(\"mainCaller!\"); // Calling the main() method main(null); } // main() method public static void main(String[] args) { System.out.println(\"main\"); // Calling the mainCaller() method // so that main() method is called externally mainCaller(); }}",
"e": 3564,
"s": 2981,
"text": null
},
{
"code": null,
"e": 3592,
"s": 3564,
"text": "RunTime Error in java code:"
},
{
"code": null,
"e": 3737,
"s": 3592,
"text": "RunTime Error in java code :-\n Exception in thread \"main\" java.lang.StackOverflowError\n\nmainCaller!\nmain\nmainCaller!\nmain\nmainCaller!\nmain\n.\n.\n."
},
{
"code": null,
"e": 3824,
"s": 3737,
"text": "The right way to this:Example 1: Calling main() method externally from the same class "
},
{
"code": null,
"e": 3829,
"s": 3824,
"text": "Java"
},
{
"code": "// Java method to show Calling main() method// externally from the same class import java.io.*; class GFG { static int count = 0; // The method that calls the main() method static void mainCaller() { System.out.println(\"mainCaller!\"); count++; // Calling the main() only 3 times if (count < 3) { // Calling the main() method main(null); } } // main() method public static void main(String[] args) { System.out.println(\"main\"); // Calling the mainCaller() method // so that main() method is called externally mainCaller(); }}",
"e": 4473,
"s": 3829,
"text": null
},
{
"code": null,
"e": 4483,
"s": 4473,
"text": "Output: "
},
{
"code": null,
"e": 4534,
"s": 4483,
"text": "main\nmainCaller!\nmain\nmainCaller!\nmain\nmainCaller!"
},
{
"code": null,
"e": 4598,
"s": 4534,
"text": "Example 1: Calling main() method externally from another class "
},
{
"code": null,
"e": 4603,
"s": 4598,
"text": "Java"
},
{
"code": "// Java method to show Calling main() method// externally from another class import java.io.*; class GFG { static int count = 0; // The method that calls the main() method static void mainCaller() { System.out.println(\"mainCaller!\"); count++; // Calling the main() only 3 times if (count < 3) { // Calling the main() method Test.main(null); } }} class Test { // main() method public static void main(String[] args) { System.out.println(\"main\"); // Calling the mainCaller() method // so that main() method is called externally GFG.mainCaller(); }}",
"e": 5269,
"s": 4603,
"text": null
},
{
"code": null,
"e": 5278,
"s": 5269,
"text": "Output: "
},
{
"code": null,
"e": 5329,
"s": 5278,
"text": "main\nmainCaller!\nmain\nmainCaller!\nmain\nmainCaller!"
},
{
"code": null,
"e": 5342,
"s": 5329,
"text": "AshokJaiswal"
},
{
"code": null,
"e": 5359,
"s": 5342,
"text": "arorakashish0911"
},
{
"code": null,
"e": 5364,
"s": 5359,
"text": "main"
},
{
"code": null,
"e": 5369,
"s": 5364,
"text": "Java"
},
{
"code": null,
"e": 5374,
"s": 5369,
"text": "Java"
}
] |
OpenCV – The Gunnar-Farneback optical flow
|
29 Nov, 2021
In this article, we will know about Dense Optical Flow by Gunnar FarneBack technique, it was published in a research paper named ‘Two-Frame Motion Estimation Based on Polynomial Expansion’ by Gunnar Farneback in 2003. Prerequisites: OpenCVOptical Flow: Optical flow is known as the pattern of apparent motion of objects, i.e, it is the motion of objects between every two consecutive frames of the sequence, which is caused by the movement of the object being captured or the camera capturing it. Consider an object with intensity I (x, y, t), after time dt, it moves to by dx and dy, now, the new intensity would be, I (x+dx, y+dy, t+dt).
We, assume that the pixel intensities are constant between the two frames, i.e., I (x, y, t) = I (x+dx, y+dy, t+dt) Taylor approximation is done on the RHS side, resulting in,
On dividing by δt, we obtain the Optical Flow Equation, i.e.,
where, u = dx/dt and v = dy/dt. Also, dI/dx is the image gradient along the horizontal axis, dI/dy is the image gradient along the vertical axis and dI/dt is along the time. Since, we have just one equation to find two unknowns, we use different methods to solve,
Sparse Optical Flow (Lucas Kanade Method)
Dense Optical Flow (Gunnar Farneback Method)
Gunnar Farneback Optical Flow In dense optical flow, we look at all of the points(unlike Lucas Kanade which works only on corner points detected by Shi-Tomasi Algorithm) and detect the pixel intensity changes between the two frames, resulting in an image with highlighted pixels, after converting to hsv format for clear visibility. It computes the magnitude and direction of optical flow from an array of the flow vectors, i.e., (dx/dt, dy/dt). Later it visualizes the angle (direction) of flow by hue and the distance (magnitude) of flow by value of HSV color representation.For visibility to be optimal, strength of HSV is set to 255. OpenCV provides a function cv2.calcOpticalFlowFarneback to look into dense optical flow. Syntax:
cv2.calcOpticalFlowFarneback(prev, next, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags[, flow])
Parameters:
prev : First input image in 8-bit single channel format.
next : Second input image of same type and same size as prev.
pyr_scale : parameter specifying the image scale to build pyramids for each image (scale < 1). A classic pyramid is of generally 0.5 scale, every new layer added, it is halved to the previous one.
levels : levels=1 says, there are no extra layers (only the initial image) . It is the number of pyramid layers including the first image.
winsize : It is the average window size, larger the size, the more robust the algorithm is to noise, and provide fast motion detection, though gives blurred motion fields.
iterations : Number of iterations to be performed at each pyramid level.
poly_n : It is typically 5 or 7, it is the size of the pixel neighbourhood which is used to find polynomial expansion between the pixels.
poly_sigma : standard deviation of the gaussian that is for derivatives to be smooth as the basis of the polynomial expansion. It can be 1.1 for poly= 5 and 1.5 for poly= 7.
flow : computed flow image that has similar size as prev and type to be CV_32FC2.
flags : It can be a combination of- OPTFLOW_USE_INITIAL_FLOW uses input flow as initial approximation. OPTFLOW_FARNEBACK_GAUSSIAN uses gaussian winsize*winsize filter.
Code:
Python3
# Importing librariesimport cv2import numpy as np# Capturing the video file 0 for videocam else you can provide the urlcapture = cv2.VideoCapture("video_file.avi") # Reading the first frame_, frame1 = capture.read()# Convert to gray scaleprvs = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)# Create maskhsv_mask = np.zeros_like(frame1)# Make image saturation to a maximum valuehsv_mask[..., 1] = 255 # Till you scan the videowhile(1): # Capture another frame and convert to gray scale _, frame2 = capture.read() next = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) # Optical flow is now calculated flow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5, 1.2, 0) # Compute magnite and angle of 2D vector mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) # Set image hue value according to the angle of optical flow hsv_mask[..., 0] = ang * 180 / np.pi / 2 # Set value as per the normalized magnitude of optical flow hsv_mask[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) # Convert to rgb rgb_representation = cv2.cvtColor(hsv_mask, cv2.COLOR_HSV2BGR) cv2.imshow('frame2', rgb_representation) kk = cv2.waitKey(20) & 0xff # Press 'e' to exit the video if kk == ord('e'): break # Press 's' to save the video elif kk == ord('s'): cv2.imwrite('Optical_image.png', frame2) cv2.imwrite('HSV_converted_image.png', rgb_representation) prvs = next capture.release()cv2.destroyAllWindows()
Input
Output:
https://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html
surindertarika1234
Image-Processing
OpenCV
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 694,
"s": 52,
"text": "In this article, we will know about Dense Optical Flow by Gunnar FarneBack technique, it was published in a research paper named ‘Two-Frame Motion Estimation Based on Polynomial Expansion’ by Gunnar Farneback in 2003. Prerequisites: OpenCVOptical Flow: Optical flow is known as the pattern of apparent motion of objects, i.e, it is the motion of objects between every two consecutive frames of the sequence, which is caused by the movement of the object being captured or the camera capturing it. Consider an object with intensity I (x, y, t), after time dt, it moves to by dx and dy, now, the new intensity would be, I (x+dx, y+dy, t+dt). "
},
{
"code": null,
"e": 872,
"s": 694,
"text": "We, assume that the pixel intensities are constant between the two frames, i.e., I (x, y, t) = I (x+dx, y+dy, t+dt) Taylor approximation is done on the RHS side, resulting in, "
},
{
"code": null,
"e": 936,
"s": 872,
"text": "On dividing by δt, we obtain the Optical Flow Equation, i.e., "
},
{
"code": null,
"e": 1202,
"s": 936,
"text": "where, u = dx/dt and v = dy/dt. Also, dI/dx is the image gradient along the horizontal axis, dI/dy is the image gradient along the vertical axis and dI/dt is along the time. Since, we have just one equation to find two unknowns, we use different methods to solve, "
},
{
"code": null,
"e": 1244,
"s": 1202,
"text": "Sparse Optical Flow (Lucas Kanade Method)"
},
{
"code": null,
"e": 1289,
"s": 1244,
"text": "Dense Optical Flow (Gunnar Farneback Method)"
},
{
"code": null,
"e": 2025,
"s": 1289,
"text": "Gunnar Farneback Optical Flow In dense optical flow, we look at all of the points(unlike Lucas Kanade which works only on corner points detected by Shi-Tomasi Algorithm) and detect the pixel intensity changes between the two frames, resulting in an image with highlighted pixels, after converting to hsv format for clear visibility. It computes the magnitude and direction of optical flow from an array of the flow vectors, i.e., (dx/dt, dy/dt). Later it visualizes the angle (direction) of flow by hue and the distance (magnitude) of flow by value of HSV color representation.For visibility to be optimal, strength of HSV is set to 255. OpenCV provides a function cv2.calcOpticalFlowFarneback to look into dense optical flow. Syntax: "
},
{
"code": null,
"e": 2142,
"s": 2025,
"text": " cv2.calcOpticalFlowFarneback(prev, next, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags[, flow])"
},
{
"code": null,
"e": 2155,
"s": 2142,
"text": "Parameters: "
},
{
"code": null,
"e": 2212,
"s": 2155,
"text": "prev : First input image in 8-bit single channel format."
},
{
"code": null,
"e": 2274,
"s": 2212,
"text": "next : Second input image of same type and same size as prev."
},
{
"code": null,
"e": 2471,
"s": 2274,
"text": "pyr_scale : parameter specifying the image scale to build pyramids for each image (scale < 1). A classic pyramid is of generally 0.5 scale, every new layer added, it is halved to the previous one."
},
{
"code": null,
"e": 2610,
"s": 2471,
"text": "levels : levels=1 says, there are no extra layers (only the initial image) . It is the number of pyramid layers including the first image."
},
{
"code": null,
"e": 2782,
"s": 2610,
"text": "winsize : It is the average window size, larger the size, the more robust the algorithm is to noise, and provide fast motion detection, though gives blurred motion fields."
},
{
"code": null,
"e": 2855,
"s": 2782,
"text": "iterations : Number of iterations to be performed at each pyramid level."
},
{
"code": null,
"e": 2993,
"s": 2855,
"text": "poly_n : It is typically 5 or 7, it is the size of the pixel neighbourhood which is used to find polynomial expansion between the pixels."
},
{
"code": null,
"e": 3167,
"s": 2993,
"text": "poly_sigma : standard deviation of the gaussian that is for derivatives to be smooth as the basis of the polynomial expansion. It can be 1.1 for poly= 5 and 1.5 for poly= 7."
},
{
"code": null,
"e": 3249,
"s": 3167,
"text": "flow : computed flow image that has similar size as prev and type to be CV_32FC2."
},
{
"code": null,
"e": 3417,
"s": 3249,
"text": "flags : It can be a combination of- OPTFLOW_USE_INITIAL_FLOW uses input flow as initial approximation. OPTFLOW_FARNEBACK_GAUSSIAN uses gaussian winsize*winsize filter."
},
{
"code": null,
"e": 3424,
"s": 3417,
"text": "Code: "
},
{
"code": null,
"e": 3432,
"s": 3424,
"text": "Python3"
},
{
"code": "# Importing librariesimport cv2import numpy as np# Capturing the video file 0 for videocam else you can provide the urlcapture = cv2.VideoCapture(\"video_file.avi\") # Reading the first frame_, frame1 = capture.read()# Convert to gray scaleprvs = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)# Create maskhsv_mask = np.zeros_like(frame1)# Make image saturation to a maximum valuehsv_mask[..., 1] = 255 # Till you scan the videowhile(1): # Capture another frame and convert to gray scale _, frame2 = capture.read() next = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) # Optical flow is now calculated flow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5, 1.2, 0) # Compute magnite and angle of 2D vector mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) # Set image hue value according to the angle of optical flow hsv_mask[..., 0] = ang * 180 / np.pi / 2 # Set value as per the normalized magnitude of optical flow hsv_mask[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) # Convert to rgb rgb_representation = cv2.cvtColor(hsv_mask, cv2.COLOR_HSV2BGR) cv2.imshow('frame2', rgb_representation) kk = cv2.waitKey(20) & 0xff # Press 'e' to exit the video if kk == ord('e'): break # Press 's' to save the video elif kk == ord('s'): cv2.imwrite('Optical_image.png', frame2) cv2.imwrite('HSV_converted_image.png', rgb_representation) prvs = next capture.release()cv2.destroyAllWindows()",
"e": 4923,
"s": 3432,
"text": null
},
{
"code": null,
"e": 4930,
"s": 4923,
"text": "Input "
},
{
"code": null,
"e": 4939,
"s": 4930,
"text": "Output: "
},
{
"code": null,
"e": 5026,
"s": 4939,
"text": "https://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html"
},
{
"code": null,
"e": 5045,
"s": 5026,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5062,
"s": 5045,
"text": "Image-Processing"
},
{
"code": null,
"e": 5069,
"s": 5062,
"text": "OpenCV"
},
{
"code": null,
"e": 5083,
"s": 5069,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 5090,
"s": 5083,
"text": "Python"
}
] |
GATE | GATE-CS-2014-(Set-1) | Question 65
|
04 Aug, 2021
Consider a selective repeat sliding window protocol that uses a frame size of 1 KB to send data on a 1.5 Mbps link with a one-way latency of 50 msec. To achieve a link utilization of 60%, the minimum number of bits required to represent the sequence number field is ________.(A) 3(B) 4(C) 5(D) 6Answer: (C)Explanation:
Transmission delay = Frame Size/bandwidth
= (1*8*1024)/(1.5 * 10^6)=5.33ms
Propagation delay = 50ms
Efficiency = Window Size/(1+2a) = .6
a = Propagation delay/Transmission delay
So, window size = 11.856(approx)
min sequence number = 2*window size = 23.712
bits required in Min sequence number = log2(23.712)
Answer is 4.56
Ceil(4.56) = 5
Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 371,
"s": 52,
"text": "Consider a selective repeat sliding window protocol that uses a frame size of 1 KB to send data on a 1.5 Mbps link with a one-way latency of 50 msec. To achieve a link utilization of 60%, the minimum number of bits required to represent the sequence number field is ________.(A) 3(B) 4(C) 5(D) 6Answer: (C)Explanation:"
},
{
"code": null,
"e": 731,
"s": 371,
"text": "Transmission delay = Frame Size/bandwidth\n = (1*8*1024)/(1.5 * 10^6)=5.33ms\nPropagation delay = 50ms\nEfficiency = Window Size/(1+2a) = .6\n\na = Propagation delay/Transmission delay\nSo, window size = 11.856(approx)\nmin sequence number = 2*window size = 23.712\nbits required in Min sequence number = log2(23.712)\nAnswer is 4.56\n\nCeil(4.56) = 5 "
},
{
"code": null,
"e": 753,
"s": 731,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 774,
"s": 753,
"text": "GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 800,
"s": 774,
"text": "GATE-GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 805,
"s": 800,
"text": "GATE"
}
] |
Software Engineering | Halstead’s Software Metrics
|
05 Aug, 2020
A computer program is an implementation of an algorithm considered to be a collection of tokens which can be classified as either operators or operands. Halstead’s metrics are included in a number of current commercial tools that count software lines of code. By counting the tokens and determining which are operators and which are operands, the following base measures can be collected :
n1 = Number of distinct operators. n2 = Number of distinct operands. N1 = Total number of occurrences of operators. N2 = Total number of occurrences of operands.
In addition to the above, Halstead defines the following :
n1* = Number of potential operators. n2* = Number of potential operands.
Halstead refers to n1* and n2* as the minimum possible number of operators and operands for a module and a program respectively. This minimum number would be embodied in the programming language itself, in which the required operation would already exist (for example, in C language, any program must contain at least the definition of the function main()), possibly as a function or as a procedure: n1* = 2, since at least 2 operators must appear for any function or procedure : 1 for the name of the function and 1 to serve as an assignment or grouping symbol, and n2* represents the number of parameters, without repetition, which would need to be passed on to the function or the procedure.
Halstead metrics are :
Halstead Program Length – The total number of operator occurrences and the total number of operand occurrences. N = N1 + N2 And estimated program length is, N^ = n1log2n1 + n2log2n2 The following alternate expressions have been published to estimate program length: NJ = log2(n1!) + log2(n2!)NB = n1 * log2n2 + n2 * log2n1NC = n1 * sqrt(n1) + n2 * sqrt(n2)NS = (n * log2n) / 2
And estimated program length is, N^ = n1log2n1 + n2log2n2
The following alternate expressions have been published to estimate program length:
NJ = log2(n1!) + log2(n2!)
NB = n1 * log2n2 + n2 * log2n1
NC = n1 * sqrt(n1) + n2 * sqrt(n2)
NS = (n * log2n) / 2
Halstead Vocabulary – The total number of unique operator and unique operand occurrences. n = n1 + n2
Program Volume – Proportional to program size, represents the size, in bits, of space necessary for storing the program. This parameter is dependent on specific algorithm implementation. The properties V, N, and the number of lines in the code are shown to be linearly connected and equally valid for measuring relative program size. V = Size * (log2 vocabulary) = N * log2(n) The unit of measurement of volume is the common unit for size “bits”. It is the actual size of a program if a uniform binary encoding for the vocabulary is used. And error = Volume / 3000
V = Size * (log2 vocabulary) = N * log2(n)
The unit of measurement of volume is the common unit for size “bits”. It is the actual size of a program if a uniform binary encoding for the vocabulary is used. And error = Volume / 3000
Potential Minimum Volume – The potential minimum volume V* is defined as the volume of the most succinct program in which a problem can be coded. V* = (2 + n2*) * log2(2 + n2*) Here, n2* is the count of unique input and output parameters
V* = (2 + n2*) * log2(2 + n2*)
Here, n2* is the count of unique input and output parameters
Program Level – To rank the programming languages, the level of abstraction provided by the programming language, Program Level (L) is considered. The higher the level of a language, the less effort it takes to develop a program using that language. L = V* / V The value of L ranges between zero and one, with L=1 representing a program written at the highest possible level (i.e., with minimum size). And estimated program level is L^ =2 * (n2) / (n1)(N2)
L = V* / V
The value of L ranges between zero and one, with L=1 representing a program written at the highest possible level (i.e., with minimum size). And estimated program level is L^ =2 * (n2) / (n1)(N2)
Program Difficulty – This parameter shows how difficult to handle the program is. D = (n1 / 2) * (N2 / n2) D = 1 / L As the volume of the implementation of a program increases, the program level decreases and the difficulty increases. Thus, programming practices such as redundant usage of operands, or the failure to use higher-level control constructs will tend to increase the volume as well as the difficulty.
Programming Effort – Measures the amount of mental activity needed to translate the existing algorithm into implementation in the specified program language. E = V / L = D * V = Difficulty * Volume
Language Level – Shows the algorithm implementation program language level. The same algorithm demands additional effort if it is written in a low-level program language. For example, it is easier to program in Pascal than in Assembler. L’ = V / D / D lambda = L * V* = L2 * V
Intelligence Content – Determines the amount of intelligence presented (stated) in the program This parameter provides a measurement of program complexity, independently of the program language in which it was implemented. I = V / D
Programming Time – Shows time (in minutes) needed to translate the existing algorithm into implementation in the specified program language. T = E / (f * S) The concept of the processing rate of the human brain, developed by the psychologist John Stroud, is also used. Stoud defined a moment as the time required by the human brain requires to carry out the most elementary decision. The Stoud number S is therefore Stoud’s moments per second with: 5 <= S <= 20. Halstead uses 18. The value of S has been empirically developed from psychological reasoning, and its recommended value for programming applications is 18. Stroud number S = 18 moments / second seconds-to-minutes factor f = 60
The concept of the processing rate of the human brain, developed by the psychologist John Stroud, is also used. Stoud defined a moment as the time required by the human brain requires to carry out the most elementary decision. The Stoud number S is therefore Stoud’s moments per second with: 5 <= S <= 20. Halstead uses 18. The value of S has been empirically developed from psychological reasoning, and its recommended value for programming applications is 18.
Stroud number S = 18 moments / second
seconds-to-minutes factor f = 60
Comments are not considered.The identifier and function declarations are not consideredAll the variables and constants are considered operands.Global variables used in different modules of the same program are counted as multiple occurrences of the same variable.Local variables with the same name in different functions are counted as unique operands.Functions calls are considered as operators.All looping statements e.g., do {...} while ( ), while ( ) {...}, for ( ) {...}, all control statements e.g., if ( ) {...}, if ( ) {...} else {...}, etc. are considered as operators.In control construct switch ( ) {case:...}, switch as well as all the case statements are considered as operators.The reserve words like return, default, continue, break, sizeof, etc., are considered as operators.All the brackets, commas, and terminators are considered as operators.GOTO is counted as an operator and the label is counted as an operand.The unary and binary occurrence of “+” and “-” are dealt separately. Similarly “*” (multiplication operator) are dealt separately.In the array variables such as “array-name [index]” “array-name” and “index” are considered as operands and [ ] is considered as operator.In the structure variables such as “struct-name, member-name” or “struct-name -> member-name”, struct-name, member-name are taken as operands and ‘.’, ‘->’ are taken as operators. Some names of member elements in different structure variables are counted as unique operands.All the hash directive are ignored.
Comments are not considered.
The identifier and function declarations are not considered
All the variables and constants are considered operands.
Global variables used in different modules of the same program are counted as multiple occurrences of the same variable.
Local variables with the same name in different functions are counted as unique operands.
Functions calls are considered as operators.
All looping statements e.g., do {...} while ( ), while ( ) {...}, for ( ) {...}, all control statements e.g., if ( ) {...}, if ( ) {...} else {...}, etc. are considered as operators.
In control construct switch ( ) {case:...}, switch as well as all the case statements are considered as operators.
The reserve words like return, default, continue, break, sizeof, etc., are considered as operators.
All the brackets, commas, and terminators are considered as operators.
GOTO is counted as an operator and the label is counted as an operand.
The unary and binary occurrence of “+” and “-” are dealt separately. Similarly “*” (multiplication operator) are dealt separately.
In the array variables such as “array-name [index]” “array-name” and “index” are considered as operands and [ ] is considered as operator.
In the structure variables such as “struct-name, member-name” or “struct-name -> member-name”, struct-name, member-name are taken as operands and ‘.’, ‘->’ are taken as operators. Some names of member elements in different structure variables are counted as unique operands.
All the hash directive are ignored.
Example – List out the operators and operands and also calculate the values of software science measures like
int sort (int x[ ], int n)
{
int i, j, save, im1;
/*This function sorts array x in ascending order */
If (n< 2) return 1;
for (i=2; i< =n; i++)
{
im1=i-1;
for (j=1; j< =im1; j++)
if (x[i] < x[j])
{
Save = x[i];
x[i] = x[j];
x[j] = save;
}
}
return 0;
}
Explanation –
Therefore,
N = 91
n = 24
V = 417.23 bits
N^ = 86.51
n2* = 3 (x:array holding integer
to be sorted. This is used both
as input and output)
V* = 11.6
L = 0.027
D = 37.03
L^ = 0.038
T = 610 seconds
It is simple to calculate.
It measures overall quality of the programs.
It predicts the rate of error.
It predicts maintenance effort.
It does not require the full analysis of programming structure.
It is useful in scheduling and reporting projects.
It can be used for any programming language.
It depends on the complete code.
It has no use as a predictive estimating model.
Reference – Halstead complexity measures – Wikipedia ristancase
This article is contributed by Shivani Virmani. 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.
rishabhsingh1304
pp_pankaj
itskawal2000
Articles
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
SQL | DROP, TRUNCATE
Difference Between Object And Class
Implementation of LinkedList in Javascript
Types of Software Testing
Differences between Black Box Testing vs White Box Testing
Functional vs Non Functional Requirements
Software Engineering | COCOMO Model
Differences between Verification and Validation
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Aug, 2020"
},
{
"code": null,
"e": 445,
"s": 54,
"text": "A computer program is an implementation of an algorithm considered to be a collection of tokens which can be classified as either operators or operands. Halstead’s metrics are included in a number of current commercial tools that count software lines of code. By counting the tokens and determining which are operators and which are operands, the following base measures can be collected : "
},
{
"code": null,
"e": 608,
"s": 445,
"text": "n1 = Number of distinct operators. n2 = Number of distinct operands. N1 = Total number of occurrences of operators. N2 = Total number of occurrences of operands. "
},
{
"code": null,
"e": 668,
"s": 608,
"text": "In addition to the above, Halstead defines the following : "
},
{
"code": null,
"e": 742,
"s": 668,
"text": "n1* = Number of potential operators. n2* = Number of potential operands. "
},
{
"code": null,
"e": 1438,
"s": 742,
"text": "Halstead refers to n1* and n2* as the minimum possible number of operators and operands for a module and a program respectively. This minimum number would be embodied in the programming language itself, in which the required operation would already exist (for example, in C language, any program must contain at least the definition of the function main()), possibly as a function or as a procedure: n1* = 2, since at least 2 operators must appear for any function or procedure : 1 for the name of the function and 1 to serve as an assignment or grouping symbol, and n2* represents the number of parameters, without repetition, which would need to be passed on to the function or the procedure. "
},
{
"code": null,
"e": 1464,
"s": 1440,
"text": "Halstead metrics are : "
},
{
"code": null,
"e": 1843,
"s": 1466,
"text": "Halstead Program Length – The total number of operator occurrences and the total number of operand occurrences. N = N1 + N2 And estimated program length is, N^ = n1log2n1 + n2log2n2 The following alternate expressions have been published to estimate program length: NJ = log2(n1!) + log2(n2!)NB = n1 * log2n2 + n2 * log2n1NC = n1 * sqrt(n1) + n2 * sqrt(n2)NS = (n * log2n) / 2"
},
{
"code": null,
"e": 1902,
"s": 1843,
"text": "And estimated program length is, N^ = n1log2n1 + n2log2n2 "
},
{
"code": null,
"e": 1987,
"s": 1902,
"text": "The following alternate expressions have been published to estimate program length: "
},
{
"code": null,
"e": 2014,
"s": 1987,
"text": "NJ = log2(n1!) + log2(n2!)"
},
{
"code": null,
"e": 2045,
"s": 2014,
"text": "NB = n1 * log2n2 + n2 * log2n1"
},
{
"code": null,
"e": 2080,
"s": 2045,
"text": "NC = n1 * sqrt(n1) + n2 * sqrt(n2)"
},
{
"code": null,
"e": 2101,
"s": 2080,
"text": "NS = (n * log2n) / 2"
},
{
"code": null,
"e": 2203,
"s": 2101,
"text": "Halstead Vocabulary – The total number of unique operator and unique operand occurrences. n = n1 + n2"
},
{
"code": null,
"e": 2768,
"s": 2203,
"text": "Program Volume – Proportional to program size, represents the size, in bits, of space necessary for storing the program. This parameter is dependent on specific algorithm implementation. The properties V, N, and the number of lines in the code are shown to be linearly connected and equally valid for measuring relative program size. V = Size * (log2 vocabulary) = N * log2(n) The unit of measurement of volume is the common unit for size “bits”. It is the actual size of a program if a uniform binary encoding for the vocabulary is used. And error = Volume / 3000"
},
{
"code": null,
"e": 2812,
"s": 2768,
"text": "V = Size * (log2 vocabulary) = N * log2(n) "
},
{
"code": null,
"e": 3000,
"s": 2812,
"text": "The unit of measurement of volume is the common unit for size “bits”. It is the actual size of a program if a uniform binary encoding for the vocabulary is used. And error = Volume / 3000"
},
{
"code": null,
"e": 3238,
"s": 3000,
"text": "Potential Minimum Volume – The potential minimum volume V* is defined as the volume of the most succinct program in which a problem can be coded. V* = (2 + n2*) * log2(2 + n2*) Here, n2* is the count of unique input and output parameters"
},
{
"code": null,
"e": 3270,
"s": 3238,
"text": "V* = (2 + n2*) * log2(2 + n2*) "
},
{
"code": null,
"e": 3331,
"s": 3270,
"text": "Here, n2* is the count of unique input and output parameters"
},
{
"code": null,
"e": 3788,
"s": 3331,
"text": "Program Level – To rank the programming languages, the level of abstraction provided by the programming language, Program Level (L) is considered. The higher the level of a language, the less effort it takes to develop a program using that language. L = V* / V The value of L ranges between zero and one, with L=1 representing a program written at the highest possible level (i.e., with minimum size). And estimated program level is L^ =2 * (n2) / (n1)(N2)"
},
{
"code": null,
"e": 3800,
"s": 3788,
"text": "L = V* / V "
},
{
"code": null,
"e": 3996,
"s": 3800,
"text": "The value of L ranges between zero and one, with L=1 representing a program written at the highest possible level (i.e., with minimum size). And estimated program level is L^ =2 * (n2) / (n1)(N2)"
},
{
"code": null,
"e": 4410,
"s": 3996,
"text": "Program Difficulty – This parameter shows how difficult to handle the program is. D = (n1 / 2) * (N2 / n2) D = 1 / L As the volume of the implementation of a program increases, the program level decreases and the difficulty increases. Thus, programming practices such as redundant usage of operands, or the failure to use higher-level control constructs will tend to increase the volume as well as the difficulty."
},
{
"code": null,
"e": 4610,
"s": 4410,
"text": "Programming Effort – Measures the amount of mental activity needed to translate the existing algorithm into implementation in the specified program language. E = V / L = D * V = Difficulty * Volume "
},
{
"code": null,
"e": 4889,
"s": 4610,
"text": "Language Level – Shows the algorithm implementation program language level. The same algorithm demands additional effort if it is written in a low-level program language. For example, it is easier to program in Pascal than in Assembler. L’ = V / D / D lambda = L * V* = L2 * V "
},
{
"code": null,
"e": 5124,
"s": 4891,
"text": "Intelligence Content – Determines the amount of intelligence presented (stated) in the program This parameter provides a measurement of program complexity, independently of the program language in which it was implemented. I = V / D"
},
{
"code": null,
"e": 5816,
"s": 5124,
"text": "Programming Time – Shows time (in minutes) needed to translate the existing algorithm into implementation in the specified program language. T = E / (f * S) The concept of the processing rate of the human brain, developed by the psychologist John Stroud, is also used. Stoud defined a moment as the time required by the human brain requires to carry out the most elementary decision. The Stoud number S is therefore Stoud’s moments per second with: 5 <= S <= 20. Halstead uses 18. The value of S has been empirically developed from psychological reasoning, and its recommended value for programming applications is 18. Stroud number S = 18 moments / second seconds-to-minutes factor f = 60 "
},
{
"code": null,
"e": 6279,
"s": 5816,
"text": "The concept of the processing rate of the human brain, developed by the psychologist John Stroud, is also used. Stoud defined a moment as the time required by the human brain requires to carry out the most elementary decision. The Stoud number S is therefore Stoud’s moments per second with: 5 <= S <= 20. Halstead uses 18. The value of S has been empirically developed from psychological reasoning, and its recommended value for programming applications is 18. "
},
{
"code": null,
"e": 6318,
"s": 6279,
"text": "Stroud number S = 18 moments / second "
},
{
"code": null,
"e": 6353,
"s": 6318,
"text": "seconds-to-minutes factor f = 60 "
},
{
"code": null,
"e": 7866,
"s": 6357,
"text": "Comments are not considered.The identifier and function declarations are not consideredAll the variables and constants are considered operands.Global variables used in different modules of the same program are counted as multiple occurrences of the same variable.Local variables with the same name in different functions are counted as unique operands.Functions calls are considered as operators.All looping statements e.g., do {...} while ( ), while ( ) {...}, for ( ) {...}, all control statements e.g., if ( ) {...}, if ( ) {...} else {...}, etc. are considered as operators.In control construct switch ( ) {case:...}, switch as well as all the case statements are considered as operators.The reserve words like return, default, continue, break, sizeof, etc., are considered as operators.All the brackets, commas, and terminators are considered as operators.GOTO is counted as an operator and the label is counted as an operand.The unary and binary occurrence of “+” and “-” are dealt separately. Similarly “*” (multiplication operator) are dealt separately.In the array variables such as “array-name [index]” “array-name” and “index” are considered as operands and [ ] is considered as operator.In the structure variables such as “struct-name, member-name” or “struct-name -> member-name”, struct-name, member-name are taken as operands and ‘.’, ‘->’ are taken as operators. Some names of member elements in different structure variables are counted as unique operands.All the hash directive are ignored."
},
{
"code": null,
"e": 7895,
"s": 7866,
"text": "Comments are not considered."
},
{
"code": null,
"e": 7955,
"s": 7895,
"text": "The identifier and function declarations are not considered"
},
{
"code": null,
"e": 8012,
"s": 7955,
"text": "All the variables and constants are considered operands."
},
{
"code": null,
"e": 8133,
"s": 8012,
"text": "Global variables used in different modules of the same program are counted as multiple occurrences of the same variable."
},
{
"code": null,
"e": 8223,
"s": 8133,
"text": "Local variables with the same name in different functions are counted as unique operands."
},
{
"code": null,
"e": 8268,
"s": 8223,
"text": "Functions calls are considered as operators."
},
{
"code": null,
"e": 8451,
"s": 8268,
"text": "All looping statements e.g., do {...} while ( ), while ( ) {...}, for ( ) {...}, all control statements e.g., if ( ) {...}, if ( ) {...} else {...}, etc. are considered as operators."
},
{
"code": null,
"e": 8566,
"s": 8451,
"text": "In control construct switch ( ) {case:...}, switch as well as all the case statements are considered as operators."
},
{
"code": null,
"e": 8666,
"s": 8566,
"text": "The reserve words like return, default, continue, break, sizeof, etc., are considered as operators."
},
{
"code": null,
"e": 8737,
"s": 8666,
"text": "All the brackets, commas, and terminators are considered as operators."
},
{
"code": null,
"e": 8808,
"s": 8737,
"text": "GOTO is counted as an operator and the label is counted as an operand."
},
{
"code": null,
"e": 8939,
"s": 8808,
"text": "The unary and binary occurrence of “+” and “-” are dealt separately. Similarly “*” (multiplication operator) are dealt separately."
},
{
"code": null,
"e": 9078,
"s": 8939,
"text": "In the array variables such as “array-name [index]” “array-name” and “index” are considered as operands and [ ] is considered as operator."
},
{
"code": null,
"e": 9353,
"s": 9078,
"text": "In the structure variables such as “struct-name, member-name” or “struct-name -> member-name”, struct-name, member-name are taken as operands and ‘.’, ‘->’ are taken as operators. Some names of member elements in different structure variables are counted as unique operands."
},
{
"code": null,
"e": 9389,
"s": 9353,
"text": "All the hash directive are ignored."
},
{
"code": null,
"e": 9500,
"s": 9389,
"text": "Example – List out the operators and operands and also calculate the values of software science measures like "
},
{
"code": null,
"e": 9886,
"s": 9502,
"text": "int sort (int x[ ], int n)\n\n{\n int i, j, save, im1;\n /*This function sorts array x in ascending order */\n If (n< 2) return 1;\n for (i=2; i< =n; i++)\n {\n im1=i-1;\n for (j=1; j< =im1; j++)\n if (x[i] < x[j])\n {\n Save = x[i];\n x[i] = x[j];\n x[j] = save;\n }\n }\n return 0;\n}\n\n"
},
{
"code": null,
"e": 9902,
"s": 9886,
"text": "Explanation – "
},
{
"code": null,
"e": 10102,
"s": 9904,
"text": "Therefore,\nN = 91\nn = 24\nV = 417.23 bits\nN^ = 86.51\nn2* = 3 (x:array holding integer \nto be sorted. This is used both\nas input and output)\nV* = 11.6\nL = 0.027\nD = 37.03\nL^ = 0.038\nT = 610 seconds\n\n"
},
{
"code": null,
"e": 10129,
"s": 10102,
"text": "It is simple to calculate."
},
{
"code": null,
"e": 10174,
"s": 10129,
"text": "It measures overall quality of the programs."
},
{
"code": null,
"e": 10205,
"s": 10174,
"text": "It predicts the rate of error."
},
{
"code": null,
"e": 10237,
"s": 10205,
"text": "It predicts maintenance effort."
},
{
"code": null,
"e": 10301,
"s": 10237,
"text": "It does not require the full analysis of programming structure."
},
{
"code": null,
"e": 10352,
"s": 10301,
"text": "It is useful in scheduling and reporting projects."
},
{
"code": null,
"e": 10397,
"s": 10352,
"text": "It can be used for any programming language."
},
{
"code": null,
"e": 10430,
"s": 10397,
"text": "It depends on the complete code."
},
{
"code": null,
"e": 10478,
"s": 10430,
"text": "It has no use as a predictive estimating model."
},
{
"code": null,
"e": 10543,
"s": 10478,
"text": "Reference – Halstead complexity measures – Wikipedia ristancase "
},
{
"code": null,
"e": 10847,
"s": 10543,
"text": "This article is contributed by Shivani Virmani. 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": 10973,
"s": 10847,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10992,
"s": 10975,
"text": "rishabhsingh1304"
},
{
"code": null,
"e": 11002,
"s": 10992,
"text": "pp_pankaj"
},
{
"code": null,
"e": 11015,
"s": 11002,
"text": "itskawal2000"
},
{
"code": null,
"e": 11024,
"s": 11015,
"text": "Articles"
},
{
"code": null,
"e": 11045,
"s": 11024,
"text": "Software Engineering"
},
{
"code": null,
"e": 11143,
"s": 11045,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11169,
"s": 11143,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 11216,
"s": 11169,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 11237,
"s": 11216,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 11273,
"s": 11237,
"text": "Difference Between Object And Class"
},
{
"code": null,
"e": 11316,
"s": 11273,
"text": "Implementation of LinkedList in Javascript"
},
{
"code": null,
"e": 11342,
"s": 11316,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 11401,
"s": 11342,
"text": "Differences between Black Box Testing vs White Box Testing"
},
{
"code": null,
"e": 11443,
"s": 11401,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 11479,
"s": 11443,
"text": "Software Engineering | COCOMO Model"
}
] |
Word Break - Part 2 | Practice | GeeksforGeeks
|
Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences.
Follow examples for better understanding.
Example 1:
Input: s = "catsanddog", n = 5
dict = {"cats", "cat", "and", "sand", "dog"}
Output: (cats and dog)(cat sand dog)
Explanation: All the words in the given
sentences are present in the dictionary.
Example 2:
Input: s = "catsandog", n = 5
dict = {"cats", "cat", "and", "sand", "dog"}
Output: Empty
Explanation: There is no possible breaking
of the string s where all the words are present
in dict.
Your Task:
You do not need to read input or print anything. Your task is to complete the function wordBreak() which takes n, dict and s as input parameters and returns a list of possible sentences. If no sentence is possible it returns an empty list.
Expected Time Complexity: O(N2*n) where N = |s|
Expected Auxiliary Space: O(N2)
Constraints:
1 ≤ n ≤ 20
1 ≤ dict[i] ≤ 15
1 ≤ |s| ≤ 500
+1
arkoghoshdastidar3920006 days ago
C++ Solution :
class Solution{
public:
bool presentInDict(vector<string> const &dict, int n, string s)
{
for(int i=0; i<n; i++)
{
if(dict[i] == s)
{
return true;
}
}
return false;
}
void wordBreak(int n, vector<string> &dict, string s, string smallOutput, vector<string> &output)
{
if(s.size() == 0)
{
output.push_back(smallOutput);
return;
}
string temp;
for(int i=0; i<s.size(); i++)
{
temp += s[i];
if(presentInDict(dict, n, temp))
{
if(!smallOutput.size())
{
wordBreak(n, dict, s.substr(i+1), temp, output);
}
else
{
wordBreak(n, dict, s.substr(i+1), smallOutput+" "+temp, output);
}
}
}
}
vector<string> wordBreak(int n, vector<string>& dict, string s)
{
vector<string> output;
string smallOutput;
wordBreak(n, dict, s, smallOutput, output);
return output;
}
};
+2
abhishekfarswan1 week ago
Using BackTracking in C++
class Solution{ public: vector<string> solution; bool wordAvailable(string tmp,vector<string>& dict,int n){ for(int i=0;i<n;i++){ if(dict[i]==tmp){ return true; } } return false; } void breakingWords(int n, vector<string>& dict,string s,int start,string sub){ if(start == s.length()){ solution.push_back(sub.substr(0,sub.length()-1)); return; } string tmp=""; for(int i=start;i<s.length();i++){ tmp+=s[i]; if(wordAvailable(tmp,dict,n)){ breakingWords(n,dict,s,i+1,sub+tmp+" "); } } } vector<string> wordBreak(int n, vector<string>& dict, string s) { breakingWords(n,dict,s,0,""); return solution; }};
0
wjyjobs1 week ago
def wordBreak(self, n, dict, s):
@lru_cache(None)
def brk(s, i):
ret = []
if s[i:] in dict:
ret.append(s[i:])
for j in range(i+1, len(s)):
if s[i:j] in dict:
r = brk(s, j)
for sentence in r:
ret.append(s[i:j] + " " + sentence)
return ret
return brk(s, 0)
0
disaster2 weeks ago
class Solution{
vector<string> res;
map<string, bool> hash;
public:
void rec(int ind, string curr, string s, vector<string>& dict){
if(ind == s.size()) res.push_back(curr);
for(int i=ind;i<s.length();i++){
string sub = s.substr(ind, i-ind+1);
if(hash.find(sub) != hash.end()){
string ne;
if(curr == "") ne = sub;
else ne = curr+" "+sub;
rec(i+1, ne, s, dict);
}
}
}
vector<string> wordBreak(int n, vector<string>& dict, string s)
{
// code here
for(auto word: dict) hash[word] = true;
rec(0, "", s, dict);
return res;
}
};
+1
harsh63102 weeks ago
Easy and Short solution. ( 0.01s )
vector<string> getAns(string& s, unordered_set<string>& dict,unordered_map<string, vector<string>>& map){
if(map.count(s))
return map[s] ;
vector<string> ans ;
string back, front=s ;
if(dict.find(front) != dict.end())
ans.push_back(front) ;
for(int i=(int)s.size()-1 ; i>=0 ; i--){
front.pop_back() ;
back = s[i]+back ;
if(dict.find(back) == dict.end())
continue ;
vector<string> temp = getAns(front,dict,map) ;
for(auto &str: temp)
ans.push_back(str + " " + back) ;
}
return map[s] = ans ;
}
vector<string> wordBreak(int n, vector<string>& dict, string& s){
unordered_map<string, vector<string>> map ;
unordered_set<string> dic(dict.begin(), dict.end()) ;
return getAns(s,dic,map) ;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 468,
"s": 238,
"text": "Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences."
},
{
"code": null,
"e": 510,
"s": 468,
"text": "Follow examples for better understanding."
},
{
"code": null,
"e": 521,
"s": 510,
"text": "Example 1:"
},
{
"code": null,
"e": 717,
"s": 521,
"text": "Input: s = \"catsanddog\", n = 5 \ndict = {\"cats\", \"cat\", \"and\", \"sand\", \"dog\"}\nOutput: (cats and dog)(cat sand dog)\nExplanation: All the words in the given \nsentences are present in the dictionary."
},
{
"code": null,
"e": 728,
"s": 717,
"text": "Example 2:"
},
{
"code": null,
"e": 919,
"s": 728,
"text": "Input: s = \"catsandog\", n = 5\ndict = {\"cats\", \"cat\", \"and\", \"sand\", \"dog\"}\nOutput: Empty\nExplanation: There is no possible breaking \nof the string s where all the words are present \nin dict."
},
{
"code": null,
"e": 1170,
"s": 919,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function wordBreak() which takes n, dict and s as input parameters and returns a list of possible sentences. If no sentence is possible it returns an empty list."
},
{
"code": null,
"e": 1250,
"s": 1170,
"text": "Expected Time Complexity: O(N2*n) where N = |s|\nExpected Auxiliary Space: O(N2)"
},
{
"code": null,
"e": 1306,
"s": 1250,
"text": "Constraints:\n1 ≤ n ≤ 20\n1 ≤ dict[i] ≤ 15\n1 ≤ |s| ≤ 500 "
},
{
"code": null,
"e": 1309,
"s": 1306,
"text": "+1"
},
{
"code": null,
"e": 1343,
"s": 1309,
"text": "arkoghoshdastidar3920006 days ago"
},
{
"code": null,
"e": 1358,
"s": 1343,
"text": "C++ Solution :"
},
{
"code": null,
"e": 2547,
"s": 1360,
"text": "class Solution{\npublic:\n bool presentInDict(vector<string> const \t\t\t\t\t\t&dict, int n, string s)\n {\n for(int i=0; i<n; i++)\n {\n if(dict[i] == s)\n {\n return true;\n }\n }\n return false;\n }\n \n void wordBreak(int n, vector<string> &dict, string s, string smallOutput, vector<string> &output)\n {\n if(s.size() == 0)\n {\n output.push_back(smallOutput);\n return;\n }\n string temp;\n for(int i=0; i<s.size(); i++)\n {\n temp += s[i];\n if(presentInDict(dict, n, temp))\n {\n if(!smallOutput.size())\n {\n wordBreak(n, dict, s.substr(i+1), temp, output);\n }\n else\n {\n wordBreak(n, dict, s.substr(i+1), smallOutput+\" \"+temp, output);\n }\n }\n }\n }\n \n vector<string> wordBreak(int n, vector<string>& dict, string s)\n {\n vector<string> output;\n string smallOutput;\n wordBreak(n, dict, s, smallOutput, output);\n return output;\n }\n};"
},
{
"code": null,
"e": 2550,
"s": 2547,
"text": "+2"
},
{
"code": null,
"e": 2576,
"s": 2550,
"text": "abhishekfarswan1 week ago"
},
{
"code": null,
"e": 2602,
"s": 2576,
"text": "Using BackTracking in C++"
},
{
"code": null,
"e": 3388,
"s": 2602,
"text": "class Solution{ public: vector<string> solution; bool wordAvailable(string tmp,vector<string>& dict,int n){ for(int i=0;i<n;i++){ if(dict[i]==tmp){ return true; } } return false; } void breakingWords(int n, vector<string>& dict,string s,int start,string sub){ if(start == s.length()){ solution.push_back(sub.substr(0,sub.length()-1)); return; } string tmp=\"\"; for(int i=start;i<s.length();i++){ tmp+=s[i]; if(wordAvailable(tmp,dict,n)){ breakingWords(n,dict,s,i+1,sub+tmp+\" \"); } } } vector<string> wordBreak(int n, vector<string>& dict, string s) { breakingWords(n,dict,s,0,\"\"); return solution; }};"
},
{
"code": null,
"e": 3390,
"s": 3388,
"text": "0"
},
{
"code": null,
"e": 3408,
"s": 3390,
"text": "wjyjobs1 week ago"
},
{
"code": null,
"e": 3870,
"s": 3408,
"text": " def wordBreak(self, n, dict, s):\n \n @lru_cache(None)\n def brk(s, i):\n ret = []\n if s[i:] in dict:\n ret.append(s[i:])\n \n for j in range(i+1, len(s)):\n if s[i:j] in dict:\n r = brk(s, j)\n for sentence in r:\n ret.append(s[i:j] + \" \" + sentence)\n return ret\n \n return brk(s, 0)"
},
{
"code": null,
"e": 3872,
"s": 3870,
"text": "0"
},
{
"code": null,
"e": 3892,
"s": 3872,
"text": "disaster2 weeks ago"
},
{
"code": null,
"e": 4621,
"s": 3892,
"text": "class Solution{\n vector<string> res;\n map<string, bool> hash;\npublic:\n void rec(int ind, string curr, string s, vector<string>& dict){\n if(ind == s.size()) res.push_back(curr);\n \n for(int i=ind;i<s.length();i++){\n string sub = s.substr(ind, i-ind+1);\n if(hash.find(sub) != hash.end()){\n string ne;\n if(curr == \"\") ne = sub;\n else ne = curr+\" \"+sub;\n rec(i+1, ne, s, dict);\n }\n }\n }\n vector<string> wordBreak(int n, vector<string>& dict, string s)\n {\n // code here\n for(auto word: dict) hash[word] = true;\n rec(0, \"\", s, dict); \n return res;\n }\n};"
},
{
"code": null,
"e": 4624,
"s": 4621,
"text": "+1"
},
{
"code": null,
"e": 4645,
"s": 4624,
"text": "harsh63102 weeks ago"
},
{
"code": null,
"e": 4680,
"s": 4645,
"text": "Easy and Short solution. ( 0.01s )"
},
{
"code": null,
"e": 5498,
"s": 4680,
"text": "vector<string> getAns(string& s, unordered_set<string>& dict,unordered_map<string, vector<string>>& map){\n if(map.count(s))\n return map[s] ;\n \n vector<string> ans ;\n string back, front=s ;\n if(dict.find(front) != dict.end())\n ans.push_back(front) ;\n\n for(int i=(int)s.size()-1 ; i>=0 ; i--){\n front.pop_back() ;\n back = s[i]+back ;\n if(dict.find(back) == dict.end())\n continue ;\n vector<string> temp = getAns(front,dict,map) ;\n for(auto &str: temp)\n ans.push_back(str + \" \" + back) ;\n }\n \n return map[s] = ans ;\n}\n\nvector<string> wordBreak(int n, vector<string>& dict, string& s){\n unordered_map<string, vector<string>> map ;\n unordered_set<string> dic(dict.begin(), dict.end()) ;\n return getAns(s,dic,map) ;\n}"
},
{
"code": null,
"e": 5644,
"s": 5498,
"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": 5680,
"s": 5644,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5690,
"s": 5680,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5700,
"s": 5690,
"text": "\nContest\n"
},
{
"code": null,
"e": 5763,
"s": 5700,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5948,
"s": 5763,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6232,
"s": 5948,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 6378,
"s": 6232,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 6455,
"s": 6378,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6496,
"s": 6455,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6524,
"s": 6496,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6595,
"s": 6524,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 6782,
"s": 6595,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Sum of all the prime divisors of a number
|
23 May, 2022
Given a number N. The task is to find the sum of all the prime divisors of N.
Examples:
Input: 60
Output: 10
2, 3, 5 are prime divisors of 60
Input: 39
Output: 16
3, 13 are prime divisors of 39
A naive approach will be to iterate for all numbers till N and check if the number divides N. If the number divides N, check if that number is prime or not. Add all the prime numbers till N which divides N.
Below is the implementation of the above approach:
C++
C
Java
C#
Python3
PHP
Javascript
// CPP program to find sum of// prime divisors of N#include <bits/stdc++.h>using namespace std;#define N 1000005 // Function to check if the// number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find sum of prime// divisors of Nint SumOfPrimeDivisors(int n){ int sum = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum;}// Driver codeint main(){ int n = 60; cout << "Sum of prime divisors of 60 is " << SumOfPrimeDivisors(n) << endl;}
// C program to find sum of// prime divisors of N#include <stdio.h>#include <stdbool.h> #define N 1000005 // Function to check if the// number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find sum of prime// divisors of Nint SumOfPrimeDivisors(int n){ int sum = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum;} // Driver codeint main(){ int n = 60; printf("Sum of prime divisors of 60 is %d\n",SumOfPrimeDivisors(n));} // This code is contributed by kothavvsaakash.
// Java program to find sum// of prime divisors of Nimport java.io.*;import java.util.*; class GFG{// Function to check if the// number is prime or not.static boolean isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that // we can skip middle five // numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find// sum of prime// divisors of Nstatic int SumOfPrimeDivisors(int n){ int sum = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum;} // Driver codepublic static void main(String args[]){ int n = 60; System.out.print("Sum of prime divisors of 60 is " + SumOfPrimeDivisors(n) + "\n");}}
// C# program to find sum// of prime divisors of Nusing System;class GFG{ // Function to check if the// number is prime or not.static bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that // we can skip middle five // numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find// sum of prime// divisors of Nstatic int SumOfPrimeDivisors(int n){ int sum = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum;} // Driver codepublic static void Main(){ int n = 60; Console.WriteLine("Sum of prime divisors of 60 is " + SumOfPrimeDivisors(n) + "\n");}} // This code is contributed// by inder_verma.
# Python 3 program to find# sum of prime divisors of NN = 1000005 # Function to check if the# number is prime or not.def isPrime(n): # Corner cases if n <= 1: return False if n <= 3: return True # This is checked so that # we can skip middle five # numbers in below loop if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if (n % i == 0 or n % (i + 2) == 0): return False i = i + 6 return True # function to find sum# of prime divisors of Ndef SumOfPrimeDivisors(n): sum = 0 for i in range(1, n + 1) : if n % i == 0 : if isPrime(i): sum += i return sum # Driver coden = 60print("Sum of prime divisors of 60 is " + str(SumOfPrimeDivisors(n))) # This code is contributed# by ChitraNayal
<?php// PHP program to find sum// of prime divisors of N$N = 1000005; // Function to check if the// number is prime or not.function isPrime($n){ global $N; // Corner cases if ($n <= 1) return false; if ($n <= 3) return true; // This is checked so that // we can skip middle five // numbers in below loop if ($n % 2 == 0 || $n % 3 == 0) return false; for ($i = 5; $i * $i <= $n; $i = $i + 6) if ($n % $i == 0 || $n % ($i + 2) == 0) return false; return true;} // function to find sum// of prime divisors of Nfunction SumOfPrimeDivisors($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) { if ($n % $i == 0) { if (isPrime($i)) $sum += $i; } } return $sum;} // Driver code$n = 60;echo "Sum of prime divisors of 60 is " . SumOfPrimeDivisors($n); // This code is contributed// by ChitraNayal?>
<script>// Javascript program to find sum of// prime divisors of N let N = 1000005; // Function to check if the // number is prime or not. function isPrime(n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // function to find sum of prime // divisors of N function SumOfPrimeDivisors(n) { let sum = 0; for (let i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum; } // Driver code let n = 60; document.write("Sum of prime divisors of 60 is "+SumOfPrimeDivisors(n)); // This code is contributed by avanitrachhadiya2155</script>
Sum of prime divisors of 60 is 10
Time Complexity: O(N * sqrt(N))
Efficient Approach: The complexity can be reduced using Sieve of Eratosthenes with some modifications. The modifications are as follows:
Take an array of size N and substitute zero in all the indexes(initially consider all the numbers are prime).
Iterate for all the numbers whose indexes have zero(i.e., it is prime numbers).
Add this number to all it’s multiples less than N
Return the array[N] value which has the sum stored in it.
Below is the implementation of the above approach.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find prime divisors of// all numbers from 1 to n#include <bits/stdc++.h>using namespace std; // function to find prime divisors of// all numbers from 1 to nint Sum(int N){ int SumOfPrimeDivisors[N+1] = { 0 }; for (int i = 2; i <= N; ++i) { // if the number is prime if (!SumOfPrimeDivisors[i]) { // add this prime to all it's multiples for (int j = i; j <= N; j += i) { SumOfPrimeDivisors[j] += i; } } } return SumOfPrimeDivisors[N];} // Driver codeint main(){ int N = 60; cout << "Sum of prime divisors of 60 is " << Sum(N) << endl;}
// Java program to find// prime divisors of// all numbers from 1 to nimport java.io.*;import java.util.*; class GFG{ // function to find prime// divisors of all numbers// from 1 to nstatic int Sum(int N){ int SumOfPrimeDivisors[] = new int[N + 1]; for (int i = 2; i <= N; ++i) { // if the number is prime if (SumOfPrimeDivisors[i] == 0) { // add this prime to // all it's multiples for (int j = i; j <= N; j += i) { SumOfPrimeDivisors[j] += i; } } } return SumOfPrimeDivisors[N];} // Driver codepublic static void main(String args[]){ int N = 60; System.out.print("Sum of prime " + "divisors of 60 is " + Sum(N) + "\n");}}
# Python 3 program to find# prime divisors of# all numbers from 1 to n # function to find prime# divisors of all numbers# from 1 to ndef Sum(N): SumOfPrimeDivisors = [0] * (N + 1) for i in range(2, N + 1) : # if the number is prime if (SumOfPrimeDivisors[i] == 0) : # add this prime to # all it's multiples for j in range(i, N + 1, i) : SumOfPrimeDivisors[j] += i return SumOfPrimeDivisors[N] # Driver codeN = 60print("Sum of prime" , "divisors of 60 is", Sum(N)); # This code is contributed# by Smitha
// C# program to find// prime divisors of// all numbers from 1 to nusing System; class GFG{ // function to find prime// divisors of all numbers// from 1 to nstatic int Sum(int N){ int []SumOfPrimeDivisors = new int[N + 1]; for (int i = 2; i <= N; ++i) { // if the number is prime if (SumOfPrimeDivisors[i] == 0) { // add this prime to // all it's multiples for (int j = i; j <= N; j += i) { SumOfPrimeDivisors[j] += i; } } } return SumOfPrimeDivisors[N];} // Driver codepublic static void Main(){ int N = 60; Console.Write("Sum of prime " + "divisors of 60 is " + Sum(N) + "\n");}} // This code is contributed// by Smitha
<?php// PHP program to find prime// divisors of all numbers// from 1 to n // function to find prime// divisors of all numbers// from 1 to nfunction Sum($N){ for($i = 0; $i <= $N; $i++) $SumOfPrimeDivisors[$i] = 0; for ($i = 2; $i <= $N; ++$i) { // if the number is prime if (!$SumOfPrimeDivisors[$i]) { // add this prime to // all it's multiples for ($j = $i; $j <= $N; $j += $i) { $SumOfPrimeDivisors[$j] += $i; } } } return $SumOfPrimeDivisors[$N];} // Driver code$N = 60;echo "Sum of prime divisors of 60 is " . Sum($N); // This code is contributed by Mahadev99?>
<script> // Javascript program to find// prime divisors of// all numbers from 1 to n // function to find prime // divisors of all numbers // from 1 to n function Sum(N) { let SumOfPrimeDivisors = new Array(N+1); for(let i=0;i<SumOfPrimeDivisors.length;i++) { SumOfPrimeDivisors[i]=0; } for (let i = 2; i <= N; ++i) { // if the number is prime if (SumOfPrimeDivisors[i] == 0) { // add this prime to // all it's multiples for (let j = i; j <= N; j += i) { SumOfPrimeDivisors[j] += i; } } } return SumOfPrimeDivisors[N]; } // Driver code let N = 60; document.write("Sum of prime " + "divisors of 60 is " + Sum(N) + "<br>"); // This code is contributed by rag2127 </script>
Sum of prime divisors of 60 is 10
Time Complexity: O(N * log N)
Time complexity can be reduced by finding all the factors efficiently.
Below approach describe how to find all the factors efficiently.
If we look carefully, all the divisors are present in pairs. For example if n = 100, then the various pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10)
Using this fact we could speed up our program significantly.
We, however, have to be careful if there are two equal divisors as in the case of (10, 10). In such case, we’d take only one of them.
Below is the implementation of the above approach.
C++
C
Java
Python3
C#
Javascript
// C++ program to find sum of// prime divisors of N#include <bits/stdc++.h>using namespace std; // Function to check if the// number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find sum of prime// divisors of Nint SumOfPrimeDivisors(int n){ int sum = 0; // return type of sqrt function // if float int root_n = (int)sqrt(n); for (int i = 1; i <= root_n; i++) { if (n % i == 0) { // both factors are same if (i == n / i && isPrime(i)) { sum += i; } else { // both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(n / i)) { sum += (n / i); } } } } return sum;}// Driver codeint main(){ int n = 60; cout << "Sum of prime divisors of 60 is " << SumOfPrimeDivisors(n) << endl;}// This code is contributed by hemantraj712
// C program to find sum of// prime divisors of N#include <stdio.h>#include <stdbool.h>#include <math.h> // Function to check if the// number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find sum of prime// divisors of Nint SumOfPrimeDivisors(int n){ int sum = 0; // return type of sqrt function // if float int root_n = (int)sqrt(n); for (int i = 1; i <= root_n; i++) { if (n % i == 0) { // both factors are same if (i == n / i && isPrime(i)) { sum += i; } else { // both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(n / i)) { sum += (n / i); } } } } return sum;}// Driver codeint main(){ int n = 60; printf("Sum of prime divisors of 60 is %d\n",SumOfPrimeDivisors(n));}// This code is contributed by hemantraj712
// Java program to find sum of// prime divisors of Nclass GFG{ // Function to check if the// number is prime or not.static boolean isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find sum of prime// divisors of Nstatic int SumOfPrimeDivisors(int n){ int sum = 0; // Return type of sqrt function // if float int root_n = (int)Math.sqrt(n); for(int i = 1; i <= root_n; i++) { if (n % i == 0) { // Both factors are same if (i == n / i && isPrime(i)) { sum += i; } else { // Both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(n / i)) { sum += (n / i); } } } } return sum;} // Driver codepublic static void main(String[] args){ int n = 60; System.out.println("Sum of prime divisors of 60 is " + SumOfPrimeDivisors(n));}} // This code is contributed by divyeshrabadiya07
# Python3 program to find sum of# prime divisors of Nimport math # Function to check if the# number is prime or not.def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while i * i <= n : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True # function to find sum of prime# divisors of Ndef SumOfPrimeDivisors(n) : Sum = 0 # return type of sqrt function # if float root_n = (int)(math.sqrt(n)) for i in range(1, root_n + 1) : if (n % i == 0) : # both factors are same if (i == (int)(n / i) and isPrime(i)) : Sum += i else : # both factors are # not same ( i and n/i ) if (isPrime(i)) : Sum += i if (isPrime((int)(n / i))) : Sum += (int)(n / i) return Sum n = 60print("Sum of prime divisors of 60 is", SumOfPrimeDivisors(n)) # This code is contributed by rameshtravel07
// C# program to find sum of// prime divisors of Nusing System;class GFG { // Function to check if the // number is prime or not. static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // function to find sum of prime // divisors of N static int SumOfPrimeDivisors(int n) { int sum = 0; // return type of sqrt function // if float int root_n = (int)Math.Sqrt(n); for (int i = 1; i <= root_n; i++) { if (n % i == 0) { // both factors are same if (i == n / i && isPrime(i)) { sum += i; } else { // both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(n / i)) { sum += (n / i); } } } } return sum; } static void Main() { int n = 60; Console.WriteLine("Sum of prime divisors of 60 is " + SumOfPrimeDivisors(n)); }} // This code is contributed by suresh07.
<script> // Javascript program to find sum of // prime divisors of N // Function to check if the // number is prime or not. function isPrime(n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // function to find sum of prime // divisors of N function SumOfPrimeDivisors(n) { let sum = 0; // return type of sqrt function // if float let root_n = parseInt(Math.sqrt(n), 10); for (let i = 1; i <= root_n; i++) { if (n % i == 0) { // both factors are same if (i == parseInt(n / i, 10) && isPrime(i)) { sum += i; } else { // both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(parseInt(n / i, 10))) { sum += (parseInt(n / i, 10)); } } } } return sum; } let n = 60; document.write("Sum of prime divisors of 60 is " + SumOfPrimeDivisors(n) + "</br>"); // This code is contributed by muksh07.</script>
Sum of prime divisors of 60 is 10
Time Complexity: O(sqrt(N) * sqrt(N))
inderDuMCA
Smitha Dinesh Semwal
Mahadev99
ukasp
avanitrachhadiya2155
rag2127
hemantraj712
mukesh07
suresh07
divyeshrabadiya07
rameshtravel07
kothavvsaakash
divisors
Prime Number
sieve
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Modulo 10^9+7 (1000000007)
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number
Program to find sum of elements in a given array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 May, 2022"
},
{
"code": null,
"e": 133,
"s": 54,
"text": "Given a number N. The task is to find the sum of all the prime divisors of N. "
},
{
"code": null,
"e": 144,
"s": 133,
"text": "Examples: "
},
{
"code": null,
"e": 251,
"s": 144,
"text": "Input: 60\nOutput: 10\n2, 3, 5 are prime divisors of 60\n\nInput: 39\nOutput: 16\n3, 13 are prime divisors of 39"
},
{
"code": null,
"e": 459,
"s": 251,
"text": "A naive approach will be to iterate for all numbers till N and check if the number divides N. If the number divides N, check if that number is prime or not. Add all the prime numbers till N which divides N. "
},
{
"code": null,
"e": 512,
"s": 459,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 516,
"s": 512,
"text": "C++"
},
{
"code": null,
"e": 518,
"s": 516,
"text": "C"
},
{
"code": null,
"e": 523,
"s": 518,
"text": "Java"
},
{
"code": null,
"e": 526,
"s": 523,
"text": "C#"
},
{
"code": null,
"e": 534,
"s": 526,
"text": "Python3"
},
{
"code": null,
"e": 538,
"s": 534,
"text": "PHP"
},
{
"code": null,
"e": 549,
"s": 538,
"text": "Javascript"
},
{
"code": "// CPP program to find sum of// prime divisors of N#include <bits/stdc++.h>using namespace std;#define N 1000005 // Function to check if the// number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find sum of prime// divisors of Nint SumOfPrimeDivisors(int n){ int sum = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum;}// Driver codeint main(){ int n = 60; cout << \"Sum of prime divisors of 60 is \" << SumOfPrimeDivisors(n) << endl;}",
"e": 1448,
"s": 549,
"text": null
},
{
"code": "// C program to find sum of// prime divisors of N#include <stdio.h>#include <stdbool.h> #define N 1000005 // Function to check if the// number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find sum of prime// divisors of Nint SumOfPrimeDivisors(int n){ int sum = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum;} // Driver codeint main(){ int n = 60; printf(\"Sum of prime divisors of 60 is %d\\n\",SumOfPrimeDivisors(n));} // This code is contributed by kothavvsaakash.",
"e": 2381,
"s": 1448,
"text": null
},
{
"code": "// Java program to find sum// of prime divisors of Nimport java.io.*;import java.util.*; class GFG{// Function to check if the// number is prime or not.static boolean isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that // we can skip middle five // numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find// sum of prime// divisors of Nstatic int SumOfPrimeDivisors(int n){ int sum = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum;} // Driver codepublic static void main(String args[]){ int n = 60; System.out.print(\"Sum of prime divisors of 60 is \" + SumOfPrimeDivisors(n) + \"\\n\");}}",
"e": 3399,
"s": 2381,
"text": null
},
{
"code": "// C# program to find sum// of prime divisors of Nusing System;class GFG{ // Function to check if the// number is prime or not.static bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that // we can skip middle five // numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find// sum of prime// divisors of Nstatic int SumOfPrimeDivisors(int n){ int sum = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum;} // Driver codepublic static void Main(){ int n = 60; Console.WriteLine(\"Sum of prime divisors of 60 is \" + SumOfPrimeDivisors(n) + \"\\n\");}} // This code is contributed// by inder_verma.",
"e": 4424,
"s": 3399,
"text": null
},
{
"code": "# Python 3 program to find# sum of prime divisors of NN = 1000005 # Function to check if the# number is prime or not.def isPrime(n): # Corner cases if n <= 1: return False if n <= 3: return True # This is checked so that # we can skip middle five # numbers in below loop if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if (n % i == 0 or n % (i + 2) == 0): return False i = i + 6 return True # function to find sum# of prime divisors of Ndef SumOfPrimeDivisors(n): sum = 0 for i in range(1, n + 1) : if n % i == 0 : if isPrime(i): sum += i return sum # Driver coden = 60print(\"Sum of prime divisors of 60 is \" + str(SumOfPrimeDivisors(n))) # This code is contributed# by ChitraNayal",
"e": 5280,
"s": 4424,
"text": null
},
{
"code": "<?php// PHP program to find sum// of prime divisors of N$N = 1000005; // Function to check if the// number is prime or not.function isPrime($n){ global $N; // Corner cases if ($n <= 1) return false; if ($n <= 3) return true; // This is checked so that // we can skip middle five // numbers in below loop if ($n % 2 == 0 || $n % 3 == 0) return false; for ($i = 5; $i * $i <= $n; $i = $i + 6) if ($n % $i == 0 || $n % ($i + 2) == 0) return false; return true;} // function to find sum// of prime divisors of Nfunction SumOfPrimeDivisors($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) { if ($n % $i == 0) { if (isPrime($i)) $sum += $i; } } return $sum;} // Driver code$n = 60;echo \"Sum of prime divisors of 60 is \" . SumOfPrimeDivisors($n); // This code is contributed// by ChitraNayal?>",
"e": 6239,
"s": 5280,
"text": null
},
{
"code": "<script>// Javascript program to find sum of// prime divisors of N let N = 1000005; // Function to check if the // number is prime or not. function isPrime(n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // function to find sum of prime // divisors of N function SumOfPrimeDivisors(n) { let sum = 0; for (let i = 1; i <= n; i++) { if (n % i == 0) { if (isPrime(i)) sum += i; } } return sum; } // Driver code let n = 60; document.write(\"Sum of prime divisors of 60 is \"+SumOfPrimeDivisors(n)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 7243,
"s": 6239,
"text": null
},
{
"code": null,
"e": 7277,
"s": 7243,
"text": "Sum of prime divisors of 60 is 10"
},
{
"code": null,
"e": 7310,
"s": 7277,
"text": "Time Complexity: O(N * sqrt(N)) "
},
{
"code": null,
"e": 7449,
"s": 7310,
"text": "Efficient Approach: The complexity can be reduced using Sieve of Eratosthenes with some modifications. The modifications are as follows: "
},
{
"code": null,
"e": 7559,
"s": 7449,
"text": "Take an array of size N and substitute zero in all the indexes(initially consider all the numbers are prime)."
},
{
"code": null,
"e": 7639,
"s": 7559,
"text": "Iterate for all the numbers whose indexes have zero(i.e., it is prime numbers)."
},
{
"code": null,
"e": 7689,
"s": 7639,
"text": "Add this number to all it’s multiples less than N"
},
{
"code": null,
"e": 7747,
"s": 7689,
"text": "Return the array[N] value which has the sum stored in it."
},
{
"code": null,
"e": 7800,
"s": 7747,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 7804,
"s": 7800,
"text": "C++"
},
{
"code": null,
"e": 7809,
"s": 7804,
"text": "Java"
},
{
"code": null,
"e": 7817,
"s": 7809,
"text": "Python3"
},
{
"code": null,
"e": 7820,
"s": 7817,
"text": "C#"
},
{
"code": null,
"e": 7824,
"s": 7820,
"text": "PHP"
},
{
"code": null,
"e": 7835,
"s": 7824,
"text": "Javascript"
},
{
"code": "// CPP program to find prime divisors of// all numbers from 1 to n#include <bits/stdc++.h>using namespace std; // function to find prime divisors of// all numbers from 1 to nint Sum(int N){ int SumOfPrimeDivisors[N+1] = { 0 }; for (int i = 2; i <= N; ++i) { // if the number is prime if (!SumOfPrimeDivisors[i]) { // add this prime to all it's multiples for (int j = i; j <= N; j += i) { SumOfPrimeDivisors[j] += i; } } } return SumOfPrimeDivisors[N];} // Driver codeint main(){ int N = 60; cout << \"Sum of prime divisors of 60 is \" << Sum(N) << endl;}",
"e": 8487,
"s": 7835,
"text": null
},
{
"code": "// Java program to find// prime divisors of// all numbers from 1 to nimport java.io.*;import java.util.*; class GFG{ // function to find prime// divisors of all numbers// from 1 to nstatic int Sum(int N){ int SumOfPrimeDivisors[] = new int[N + 1]; for (int i = 2; i <= N; ++i) { // if the number is prime if (SumOfPrimeDivisors[i] == 0) { // add this prime to // all it's multiples for (int j = i; j <= N; j += i) { SumOfPrimeDivisors[j] += i; } } } return SumOfPrimeDivisors[N];} // Driver codepublic static void main(String args[]){ int N = 60; System.out.print(\"Sum of prime \" + \"divisors of 60 is \" + Sum(N) + \"\\n\");}}",
"e": 9279,
"s": 8487,
"text": null
},
{
"code": "# Python 3 program to find# prime divisors of# all numbers from 1 to n # function to find prime# divisors of all numbers# from 1 to ndef Sum(N): SumOfPrimeDivisors = [0] * (N + 1) for i in range(2, N + 1) : # if the number is prime if (SumOfPrimeDivisors[i] == 0) : # add this prime to # all it's multiples for j in range(i, N + 1, i) : SumOfPrimeDivisors[j] += i return SumOfPrimeDivisors[N] # Driver codeN = 60print(\"Sum of prime\" , \"divisors of 60 is\", Sum(N)); # This code is contributed# by Smitha",
"e": 9946,
"s": 9279,
"text": null
},
{
"code": "// C# program to find// prime divisors of// all numbers from 1 to nusing System; class GFG{ // function to find prime// divisors of all numbers// from 1 to nstatic int Sum(int N){ int []SumOfPrimeDivisors = new int[N + 1]; for (int i = 2; i <= N; ++i) { // if the number is prime if (SumOfPrimeDivisors[i] == 0) { // add this prime to // all it's multiples for (int j = i; j <= N; j += i) { SumOfPrimeDivisors[j] += i; } } } return SumOfPrimeDivisors[N];} // Driver codepublic static void Main(){ int N = 60; Console.Write(\"Sum of prime \" + \"divisors of 60 is \" + Sum(N) + \"\\n\");}} // This code is contributed// by Smitha",
"e": 10767,
"s": 9946,
"text": null
},
{
"code": "<?php// PHP program to find prime// divisors of all numbers// from 1 to n // function to find prime// divisors of all numbers// from 1 to nfunction Sum($N){ for($i = 0; $i <= $N; $i++) $SumOfPrimeDivisors[$i] = 0; for ($i = 2; $i <= $N; ++$i) { // if the number is prime if (!$SumOfPrimeDivisors[$i]) { // add this prime to // all it's multiples for ($j = $i; $j <= $N; $j += $i) { $SumOfPrimeDivisors[$j] += $i; } } } return $SumOfPrimeDivisors[$N];} // Driver code$N = 60;echo \"Sum of prime divisors of 60 is \" . Sum($N); // This code is contributed by Mahadev99?>",
"e": 11458,
"s": 10767,
"text": null
},
{
"code": "<script> // Javascript program to find// prime divisors of// all numbers from 1 to n // function to find prime // divisors of all numbers // from 1 to n function Sum(N) { let SumOfPrimeDivisors = new Array(N+1); for(let i=0;i<SumOfPrimeDivisors.length;i++) { SumOfPrimeDivisors[i]=0; } for (let i = 2; i <= N; ++i) { // if the number is prime if (SumOfPrimeDivisors[i] == 0) { // add this prime to // all it's multiples for (let j = i; j <= N; j += i) { SumOfPrimeDivisors[j] += i; } } } return SumOfPrimeDivisors[N]; } // Driver code let N = 60; document.write(\"Sum of prime \" + \"divisors of 60 is \" + Sum(N) + \"<br>\"); // This code is contributed by rag2127 </script>",
"e": 12425,
"s": 11458,
"text": null
},
{
"code": null,
"e": 12459,
"s": 12425,
"text": "Sum of prime divisors of 60 is 10"
},
{
"code": null,
"e": 12490,
"s": 12459,
"text": "Time Complexity: O(N * log N) "
},
{
"code": null,
"e": 12561,
"s": 12490,
"text": "Time complexity can be reduced by finding all the factors efficiently."
},
{
"code": null,
"e": 12627,
"s": 12561,
"text": "Below approach describe how to find all the factors efficiently. "
},
{
"code": null,
"e": 12793,
"s": 12627,
"text": "If we look carefully, all the divisors are present in pairs. For example if n = 100, then the various pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10)"
},
{
"code": null,
"e": 12856,
"s": 12793,
"text": "Using this fact we could speed up our program significantly. "
},
{
"code": null,
"e": 12991,
"s": 12856,
"text": "We, however, have to be careful if there are two equal divisors as in the case of (10, 10). In such case, we’d take only one of them. "
},
{
"code": null,
"e": 13043,
"s": 12991,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 13047,
"s": 13043,
"text": "C++"
},
{
"code": null,
"e": 13049,
"s": 13047,
"text": "C"
},
{
"code": null,
"e": 13054,
"s": 13049,
"text": "Java"
},
{
"code": null,
"e": 13062,
"s": 13054,
"text": "Python3"
},
{
"code": null,
"e": 13065,
"s": 13062,
"text": "C#"
},
{
"code": null,
"e": 13076,
"s": 13065,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of// prime divisors of N#include <bits/stdc++.h>using namespace std; // Function to check if the// number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find sum of prime// divisors of Nint SumOfPrimeDivisors(int n){ int sum = 0; // return type of sqrt function // if float int root_n = (int)sqrt(n); for (int i = 1; i <= root_n; i++) { if (n % i == 0) { // both factors are same if (i == n / i && isPrime(i)) { sum += i; } else { // both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(n / i)) { sum += (n / i); } } } } return sum;}// Driver codeint main(){ int n = 60; cout << \"Sum of prime divisors of 60 is \" << SumOfPrimeDivisors(n) << endl;}// This code is contributed by hemantraj712",
"e": 14434,
"s": 13076,
"text": null
},
{
"code": "// C program to find sum of// prime divisors of N#include <stdio.h>#include <stdbool.h>#include <math.h> // Function to check if the// number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // function to find sum of prime// divisors of Nint SumOfPrimeDivisors(int n){ int sum = 0; // return type of sqrt function // if float int root_n = (int)sqrt(n); for (int i = 1; i <= root_n; i++) { if (n % i == 0) { // both factors are same if (i == n / i && isPrime(i)) { sum += i; } else { // both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(n / i)) { sum += (n / i); } } } } return sum;}// Driver codeint main(){ int n = 60; printf(\"Sum of prime divisors of 60 is %d\\n\",SumOfPrimeDivisors(n));}// This code is contributed by hemantraj712",
"e": 15786,
"s": 14434,
"text": null
},
{
"code": "// Java program to find sum of// prime divisors of Nclass GFG{ // Function to check if the// number is prime or not.static boolean isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find sum of prime// divisors of Nstatic int SumOfPrimeDivisors(int n){ int sum = 0; // Return type of sqrt function // if float int root_n = (int)Math.sqrt(n); for(int i = 1; i <= root_n; i++) { if (n % i == 0) { // Both factors are same if (i == n / i && isPrime(i)) { sum += i; } else { // Both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(n / i)) { sum += (n / i); } } } } return sum;} // Driver codepublic static void main(String[] args){ int n = 60; System.out.println(\"Sum of prime divisors of 60 is \" + SumOfPrimeDivisors(n));}} // This code is contributed by divyeshrabadiya07",
"e": 17294,
"s": 15786,
"text": null
},
{
"code": "# Python3 program to find sum of# prime divisors of Nimport math # Function to check if the# number is prime or not.def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while i * i <= n : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True # function to find sum of prime# divisors of Ndef SumOfPrimeDivisors(n) : Sum = 0 # return type of sqrt function # if float root_n = (int)(math.sqrt(n)) for i in range(1, root_n + 1) : if (n % i == 0) : # both factors are same if (i == (int)(n / i) and isPrime(i)) : Sum += i else : # both factors are # not same ( i and n/i ) if (isPrime(i)) : Sum += i if (isPrime((int)(n / i))) : Sum += (int)(n / i) return Sum n = 60print(\"Sum of prime divisors of 60 is\", SumOfPrimeDivisors(n)) # This code is contributed by rameshtravel07",
"e": 18566,
"s": 17294,
"text": null
},
{
"code": "// C# program to find sum of// prime divisors of Nusing System;class GFG { // Function to check if the // number is prime or not. static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // function to find sum of prime // divisors of N static int SumOfPrimeDivisors(int n) { int sum = 0; // return type of sqrt function // if float int root_n = (int)Math.Sqrt(n); for (int i = 1; i <= root_n; i++) { if (n % i == 0) { // both factors are same if (i == n / i && isPrime(i)) { sum += i; } else { // both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(n / i)) { sum += (n / i); } } } } return sum; } static void Main() { int n = 60; Console.WriteLine(\"Sum of prime divisors of 60 is \" + SumOfPrimeDivisors(n)); }} // This code is contributed by suresh07.",
"e": 20123,
"s": 18566,
"text": null
},
{
"code": "<script> // Javascript program to find sum of // prime divisors of N // Function to check if the // number is prime or not. function isPrime(n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // function to find sum of prime // divisors of N function SumOfPrimeDivisors(n) { let sum = 0; // return type of sqrt function // if float let root_n = parseInt(Math.sqrt(n), 10); for (let i = 1; i <= root_n; i++) { if (n % i == 0) { // both factors are same if (i == parseInt(n / i, 10) && isPrime(i)) { sum += i; } else { // both factors are // not same ( i and n/i ) if (isPrime(i)) { sum += i; } if (isPrime(parseInt(n / i, 10))) { sum += (parseInt(n / i, 10)); } } } } return sum; } let n = 60; document.write(\"Sum of prime divisors of 60 is \" + SumOfPrimeDivisors(n) + \"</br>\"); // This code is contributed by muksh07.</script>",
"e": 21701,
"s": 20123,
"text": null
},
{
"code": null,
"e": 21735,
"s": 21701,
"text": "Sum of prime divisors of 60 is 10"
},
{
"code": null,
"e": 21775,
"s": 21735,
"text": "Time Complexity: O(sqrt(N) * sqrt(N)) "
},
{
"code": null,
"e": 21786,
"s": 21775,
"text": "inderDuMCA"
},
{
"code": null,
"e": 21807,
"s": 21786,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 21817,
"s": 21807,
"text": "Mahadev99"
},
{
"code": null,
"e": 21823,
"s": 21817,
"text": "ukasp"
},
{
"code": null,
"e": 21844,
"s": 21823,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 21852,
"s": 21844,
"text": "rag2127"
},
{
"code": null,
"e": 21865,
"s": 21852,
"text": "hemantraj712"
},
{
"code": null,
"e": 21874,
"s": 21865,
"text": "mukesh07"
},
{
"code": null,
"e": 21883,
"s": 21874,
"text": "suresh07"
},
{
"code": null,
"e": 21901,
"s": 21883,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 21916,
"s": 21901,
"text": "rameshtravel07"
},
{
"code": null,
"e": 21931,
"s": 21916,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 21940,
"s": 21931,
"text": "divisors"
},
{
"code": null,
"e": 21953,
"s": 21940,
"text": "Prime Number"
},
{
"code": null,
"e": 21959,
"s": 21953,
"text": "sieve"
},
{
"code": null,
"e": 21972,
"s": 21959,
"text": "Mathematical"
},
{
"code": null,
"e": 21985,
"s": 21972,
"text": "Mathematical"
},
{
"code": null,
"e": 21998,
"s": 21985,
"text": "Prime Number"
},
{
"code": null,
"e": 22004,
"s": 21998,
"text": "sieve"
},
{
"code": null,
"e": 22102,
"s": 22004,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22123,
"s": 22102,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 22137,
"s": 22123,
"text": "Prime Numbers"
},
{
"code": null,
"e": 22190,
"s": 22137,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 22217,
"s": 22190,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 22254,
"s": 22217,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 22286,
"s": 22254,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 22329,
"s": 22286,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 22372,
"s": 22329,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 22406,
"s": 22372,
"text": "Program for factorial of a number"
}
] |
autoconf command in Linux with examples
|
27 Jan, 2022
autoconf command is used in Linux to generate configuration scripts. Generate a configuration script from a TEMPLATE-FILE if given, or from ‘configure.ac’ if present, or ‘configure.in’. The output is sent to the standard output if TEMPLATE-FILE is given, otherwise, it is sent into ‘configure’. To use autoconf we must install the this on the Linux terminal as follows:
sudo apt-get install autoconf
Synopsis:
user/bin/autoconf [OPTION] ... [TEMPLATE-FILE]
Options:
-h, –help: Display the help message and then exits.autoconf -h or autoconf --help
autoconf -h or autoconf --help
-V, –version: Shows the version number and then exits.autoconf -V or autoconf --version
autoconf -V or autoconf --version
-v, –verbose: Gives the verbosely report processing.autoconf -v filename or autoconf --verbose filename
autoconf -v filename or autoconf --verbose filename
-d, –debug: Makes sure to not remove any files that are temporary.autoconf -d filename or autoconf --debug filename
autoconf -d filename or autoconf --debug filename
-o, –option: Saves the output in the FILE(stdout is default).autoconf -o filename or autoconf --option filename
autoconf -o filename or autoconf --option filename
-w, –warnings: Reports the warnings falling in the categoriesautoconf -w category or autoconf --warnings categoryThe other warning categories are:
autoconf -w category or autoconf --warnings category
The other warning categories are:
andreaskaratzas8
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 398,
"s": 28,
"text": "autoconf command is used in Linux to generate configuration scripts. Generate a configuration script from a TEMPLATE-FILE if given, or from ‘configure.ac’ if present, or ‘configure.in’. The output is sent to the standard output if TEMPLATE-FILE is given, otherwise, it is sent into ‘configure’. To use autoconf we must install the this on the Linux terminal as follows:"
},
{
"code": null,
"e": 428,
"s": 398,
"text": "sudo apt-get install autoconf"
},
{
"code": null,
"e": 438,
"s": 428,
"text": "Synopsis:"
},
{
"code": null,
"e": 485,
"s": 438,
"text": "user/bin/autoconf [OPTION] ... [TEMPLATE-FILE]"
},
{
"code": null,
"e": 494,
"s": 485,
"text": "Options:"
},
{
"code": null,
"e": 576,
"s": 494,
"text": "-h, –help: Display the help message and then exits.autoconf -h or autoconf --help"
},
{
"code": null,
"e": 607,
"s": 576,
"text": "autoconf -h or autoconf --help"
},
{
"code": null,
"e": 695,
"s": 607,
"text": "-V, –version: Shows the version number and then exits.autoconf -V or autoconf --version"
},
{
"code": null,
"e": 729,
"s": 695,
"text": "autoconf -V or autoconf --version"
},
{
"code": null,
"e": 833,
"s": 729,
"text": "-v, –verbose: Gives the verbosely report processing.autoconf -v filename or autoconf --verbose filename"
},
{
"code": null,
"e": 885,
"s": 833,
"text": "autoconf -v filename or autoconf --verbose filename"
},
{
"code": null,
"e": 1001,
"s": 885,
"text": "-d, –debug: Makes sure to not remove any files that are temporary.autoconf -d filename or autoconf --debug filename"
},
{
"code": null,
"e": 1051,
"s": 1001,
"text": "autoconf -d filename or autoconf --debug filename"
},
{
"code": null,
"e": 1163,
"s": 1051,
"text": "-o, –option: Saves the output in the FILE(stdout is default).autoconf -o filename or autoconf --option filename"
},
{
"code": null,
"e": 1214,
"s": 1163,
"text": "autoconf -o filename or autoconf --option filename"
},
{
"code": null,
"e": 1361,
"s": 1214,
"text": "-w, –warnings: Reports the warnings falling in the categoriesautoconf -w category or autoconf --warnings categoryThe other warning categories are:"
},
{
"code": null,
"e": 1414,
"s": 1361,
"text": "autoconf -w category or autoconf --warnings category"
},
{
"code": null,
"e": 1448,
"s": 1414,
"text": "The other warning categories are:"
},
{
"code": null,
"e": 1465,
"s": 1448,
"text": "andreaskaratzas8"
},
{
"code": null,
"e": 1479,
"s": 1465,
"text": "linux-command"
},
{
"code": null,
"e": 1499,
"s": 1479,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 1506,
"s": 1499,
"text": "Picked"
},
{
"code": null,
"e": 1517,
"s": 1506,
"text": "Linux-Unix"
}
] |
How to work with Node.js and JSON file ?
|
29 Sep, 2021
Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging data.Creating a Script: Node.js scripts are created with the js file extension. Below is an example script stored as app.js file. It is a common convention to write your main executable file as app.js.
javascript
console.log('Hello Node.js!');
Running a Script: We can run a Node.js script using the node app.js command. Open a terminal window and navigate to the directory where the script exists.
Output:
Hello Node.js
Importing Node.js Core Modules: Node.js contains some built-in modules. These modules are comes with Node, so no installation is required for them. One of the most used module is file system or fs module. The fs module provides an API for interacting with the file system or basically it provides functions that we can use to manipulate the file system. For importing any module, we make use of the require() function. The script uses writeFileSync to write a message to demo.txt. After running the script, we will find the demo.txt file with the data written the same as the given parameter in writeFileSync function. If the ‘demo.txt’ file doesn’t exist in the directory a new file with the same name is created.
javascript
const fs = require('fs') // Writing to a filefs.writeFileSync('demo.txt', 'geeks')
Exporting from Files: The module.exports is an object which comes inbuilt with node package. To use any function in another file, we must export it from the file that has its definition and import it in the file where we wish to use it.
javascript
// File Name: index.jsconst demo = () => { console.log('This Functions uses' + ' ES6 arrow operator');} // We can export multiple functions// by exporting an object of functions// instead of a simple function module.exports = check
Importing our Own Files: The require function can also be used to load our own JavaScript files. We have to provide a relative path to the file that we want to load script.
javascript
// File Name : app.js // This index variable can be used// to access all the exported methods// of index.js in this file.const index = require('./index.js'); // Executes all the functions// contained in index.jsindex(); // For any specific function use:// Imported_variable.function_name()index.check();
Writing and reading JSON file: JavaScript provides two methods for working with JSON. The first is JSON.stringify and the second is JSON.parse. The JSON.stringify converts a JavaScript object into a JSON string, while JSON.parse converts a JSON string into a JavaScript object. Since JSON is nothing more than a string, it can be used to store data in a text file.Below code works only if data.json file exists as writeFileSync doesn’t create a JSON file if it does not exists. It creates a file if it does not exists in the case of a text file only.
javascript
// Importing 'fs' moduleconst fs = require("fs"); const geeksData = { title: "Node", article: "geeksforgeeks" }; // Covert JavaScript object into JSON stringconst geeksJSON = JSON.stringify(geeksData); // Covert JSON string into objectconst geeksObject = JSON.parse(geeksJSON);console.log(geeksObject.article); // Adding more properties to JSON objectgeeksObject.stack = "js";geeksObject.difficulty = 1; // Converting js object into JSON string// and writing to data.json fileconst dataJSON = JSON.stringify(geeksObject);fs.writeFileSync("data.json", dataJSON);console.log(geeksObject);
Command to run the code:
node app.js
Output:
geeksforgeeks {
title: 'Node',
article: 'geeksforgeeks',
stack: 'js',
difficulty: 1
}
sooda367
khushboogoyal499
JSON
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 555,
"s": 53,
"text": "Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging data.Creating a Script: Node.js scripts are created with the js file extension. Below is an example script stored as app.js file. It is a common convention to write your main executable file as app.js. "
},
{
"code": null,
"e": 566,
"s": 555,
"text": "javascript"
},
{
"code": "console.log('Hello Node.js!');",
"e": 597,
"s": 566,
"text": null
},
{
"code": null,
"e": 754,
"s": 597,
"text": "Running a Script: We can run a Node.js script using the node app.js command. Open a terminal window and navigate to the directory where the script exists. "
},
{
"code": null,
"e": 764,
"s": 754,
"text": "Output: "
},
{
"code": null,
"e": 778,
"s": 764,
"text": "Hello Node.js"
},
{
"code": null,
"e": 1495,
"s": 778,
"text": "Importing Node.js Core Modules: Node.js contains some built-in modules. These modules are comes with Node, so no installation is required for them. One of the most used module is file system or fs module. The fs module provides an API for interacting with the file system or basically it provides functions that we can use to manipulate the file system. For importing any module, we make use of the require() function. The script uses writeFileSync to write a message to demo.txt. After running the script, we will find the demo.txt file with the data written the same as the given parameter in writeFileSync function. If the ‘demo.txt’ file doesn’t exist in the directory a new file with the same name is created. "
},
{
"code": null,
"e": 1506,
"s": 1495,
"text": "javascript"
},
{
"code": "const fs = require('fs') // Writing to a filefs.writeFileSync('demo.txt', 'geeks')",
"e": 1590,
"s": 1506,
"text": null
},
{
"code": null,
"e": 1828,
"s": 1590,
"text": "Exporting from Files: The module.exports is an object which comes inbuilt with node package. To use any function in another file, we must export it from the file that has its definition and import it in the file where we wish to use it. "
},
{
"code": null,
"e": 1839,
"s": 1828,
"text": "javascript"
},
{
"code": "// File Name: index.jsconst demo = () => { console.log('This Functions uses' + ' ES6 arrow operator');} // We can export multiple functions// by exporting an object of functions// instead of a simple function module.exports = check",
"e": 2081,
"s": 1839,
"text": null
},
{
"code": null,
"e": 2255,
"s": 2081,
"text": "Importing our Own Files: The require function can also be used to load our own JavaScript files. We have to provide a relative path to the file that we want to load script. "
},
{
"code": null,
"e": 2266,
"s": 2255,
"text": "javascript"
},
{
"code": "// File Name : app.js // This index variable can be used// to access all the exported methods// of index.js in this file.const index = require('./index.js'); // Executes all the functions// contained in index.jsindex(); // For any specific function use:// Imported_variable.function_name()index.check();",
"e": 2570,
"s": 2266,
"text": null
},
{
"code": null,
"e": 3122,
"s": 2570,
"text": "Writing and reading JSON file: JavaScript provides two methods for working with JSON. The first is JSON.stringify and the second is JSON.parse. The JSON.stringify converts a JavaScript object into a JSON string, while JSON.parse converts a JSON string into a JavaScript object. Since JSON is nothing more than a string, it can be used to store data in a text file.Below code works only if data.json file exists as writeFileSync doesn’t create a JSON file if it does not exists. It creates a file if it does not exists in the case of a text file only. "
},
{
"code": null,
"e": 3133,
"s": 3122,
"text": "javascript"
},
{
"code": "// Importing 'fs' moduleconst fs = require(\"fs\"); const geeksData = { title: \"Node\", article: \"geeksforgeeks\" }; // Covert JavaScript object into JSON stringconst geeksJSON = JSON.stringify(geeksData); // Covert JSON string into objectconst geeksObject = JSON.parse(geeksJSON);console.log(geeksObject.article); // Adding more properties to JSON objectgeeksObject.stack = \"js\";geeksObject.difficulty = 1; // Converting js object into JSON string// and writing to data.json fileconst dataJSON = JSON.stringify(geeksObject);fs.writeFileSync(\"data.json\", dataJSON);console.log(geeksObject);",
"e": 3727,
"s": 3133,
"text": null
},
{
"code": null,
"e": 3753,
"s": 3727,
"text": "Command to run the code: "
},
{
"code": null,
"e": 3765,
"s": 3753,
"text": "node app.js"
},
{
"code": null,
"e": 3775,
"s": 3765,
"text": "Output: "
},
{
"code": null,
"e": 3883,
"s": 3775,
"text": "geeksforgeeks { \n title: 'Node', \n article: 'geeksforgeeks', \n stack: 'js', \n difficulty: 1 \n} "
},
{
"code": null,
"e": 3892,
"s": 3883,
"text": "sooda367"
},
{
"code": null,
"e": 3909,
"s": 3892,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 3914,
"s": 3909,
"text": "JSON"
},
{
"code": null,
"e": 3927,
"s": 3914,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 3935,
"s": 3927,
"text": "Node.js"
},
{
"code": null,
"e": 3952,
"s": 3935,
"text": "Web Technologies"
}
] |
Python | Pandas Index.get_loc()
|
17 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.get_loc() function return integer location, slice or boolean mask for requested label. The function works with both sorted as well as unsorted Indexes. It provides various options if the passed value is not present in the Index. you may choose to return the previous value or the next value to the passed value only if the Index labels are sorted.
Syntax: Index.get_loc(key, method=None, tolerance=None)
Parameters:key : labelmethod : {None, ‘pad’/’ffill’, ‘backfill’/’bfill’, ‘nearest’}, optional-> default: exact matches only.-> pad / ffill: find the PREVIOUS index value if no exact match.-> backfill / bfill: use NEXT index value if no exact match-> nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value.
Returns : loc : int if unique index, slice if monotonic index, else mask
Example #1: Use Index.get_loc() function to find the location of the passed value.
# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Indexidx
Output :
let’s find out the location of ‘Lhasa’ in the Index.
# Print the location of the passed value..idx.get_loc('Lhasa)
Output :As we can see in the output, the Index.get_loc() function has returned 3 indicating that the passed value is present at this location in the Index. Example #2: Use Index.get_loc() function to find the location of the passed value. If the passed value is not present in the Index then return the location of previous value that is just smaller than the passed value.
# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index([1, 2, 3, 14, 25, 37, 48, 69, 100]) # Print the Indexidx
Output :
Let’s find the position of the value 33 in the Index.
# Find the position of 33 in the index.# If it is not present then we forward # fill and return the position of previous value.idx.get_loc(33, method ='ffill')
Output :
As we can see the function has returned the output 3. As 33 is not present in the Index but in the sorted order the value that is just smaller than 33 is 25 and its location is 4. So, the output is 4. we do not set method parameter then it will result into error if the value is not present.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 603,
"s": 242,
"text": "Pandas Index.get_loc() function return integer location, slice or boolean mask for requested label. The function works with both sorted as well as unsorted Indexes. It provides various options if the passed value is not present in the Index. you may choose to return the previous value or the next value to the passed value only if the Index labels are sorted."
},
{
"code": null,
"e": 659,
"s": 603,
"text": "Syntax: Index.get_loc(key, method=None, tolerance=None)"
},
{
"code": null,
"e": 1029,
"s": 659,
"text": "Parameters:key : labelmethod : {None, ‘pad’/’ffill’, ‘backfill’/’bfill’, ‘nearest’}, optional-> default: exact matches only.-> pad / ffill: find the PREVIOUS index value if no exact match.-> backfill / bfill: use NEXT index value if no exact match-> nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value."
},
{
"code": null,
"e": 1102,
"s": 1029,
"text": "Returns : loc : int if unique index, slice if monotonic index, else mask"
},
{
"code": null,
"e": 1185,
"s": 1102,
"text": "Example #1: Use Index.get_loc() function to find the location of the passed value."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Indexidx",
"e": 1371,
"s": 1185,
"text": null
},
{
"code": null,
"e": 1380,
"s": 1371,
"text": "Output :"
},
{
"code": null,
"e": 1433,
"s": 1380,
"text": "let’s find out the location of ‘Lhasa’ in the Index."
},
{
"code": "# Print the location of the passed value..idx.get_loc('Lhasa)",
"e": 1495,
"s": 1433,
"text": null
},
{
"code": null,
"e": 1869,
"s": 1495,
"text": "Output :As we can see in the output, the Index.get_loc() function has returned 3 indicating that the passed value is present at this location in the Index. Example #2: Use Index.get_loc() function to find the location of the passed value. If the passed value is not present in the Index then return the location of previous value that is just smaller than the passed value."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index([1, 2, 3, 14, 25, 37, 48, 69, 100]) # Print the Indexidx",
"e": 2007,
"s": 1869,
"text": null
},
{
"code": null,
"e": 2016,
"s": 2007,
"text": "Output :"
},
{
"code": null,
"e": 2070,
"s": 2016,
"text": "Let’s find the position of the value 33 in the Index."
},
{
"code": "# Find the position of 33 in the index.# If it is not present then we forward # fill and return the position of previous value.idx.get_loc(33, method ='ffill')",
"e": 2230,
"s": 2070,
"text": null
},
{
"code": null,
"e": 2239,
"s": 2230,
"text": "Output :"
},
{
"code": null,
"e": 2531,
"s": 2239,
"text": "As we can see the function has returned the output 3. As 33 is not present in the Index but in the sorted order the value that is just smaller than 33 is 25 and its location is 4. So, the output is 4. we do not set method parameter then it will result into error if the value is not present."
},
{
"code": null,
"e": 2554,
"s": 2531,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 2568,
"s": 2554,
"text": "Python-pandas"
},
{
"code": null,
"e": 2575,
"s": 2568,
"text": "Python"
}
] |
Find pair with maximum GCD in an array in C++
|
Suppose we have an array of positive integers. Our task is to find pair of integers from the array, where the GCD value is maximum. Let A = {1, 2, 3, 4, 5}, then the output is 2. The pair (2, 4) has GCD 2, other GCD values are less than 2.
To solve this problem, we will maintain a count array to store the count of divisors of each element. The process of counting divisors will take O(sqrt(arr[i])) amount of time. After whole traversal, we can traverse the count array from last index to first index, then if we find some value where the element is greater than 1, then, this means that it is the divisor of 2 elements and also the max GCD.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int getMaxGCD(int arr[], int n) {
int high = 0;
for (int i = 0; i < n; i++)
high = max(high, arr[i]);
int divisors[high + 1] = { 0 }; //array to store all gcd values
for (int i = 0; i < n; i++) {
for (int j = 1; j <= sqrt(arr[i]); j++) {
if (arr[i] % j == 0) {
divisors[j]++;
if (j != arr[i] / j)
divisors[arr[i] / j]++;
}
}
}
for (int i = high; i >= 1; i--)
if (divisors[i] > 1)
return i;
}
int main() {
int arr[] = { 1, 2, 4, 8, 12 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Max GCD: " << getMaxGCD(arr,n);
}
Max GCD: 4
|
[
{
"code": null,
"e": 1302,
"s": 1062,
"text": "Suppose we have an array of positive integers. Our task is to find pair of integers from the array, where the GCD value is maximum. Let A = {1, 2, 3, 4, 5}, then the output is 2. The pair (2, 4) has GCD 2, other GCD values are less than 2."
},
{
"code": null,
"e": 1706,
"s": 1302,
"text": "To solve this problem, we will maintain a count array to store the count of divisors of each element. The process of counting divisors will take O(sqrt(arr[i])) amount of time. After whole traversal, we can traverse the count array from last index to first index, then if we find some value where the element is greater than 1, then, this means that it is the divisor of 2 elements and also the max GCD."
},
{
"code": null,
"e": 1717,
"s": 1706,
"text": " Live Demo"
},
{
"code": null,
"e": 2392,
"s": 1717,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint getMaxGCD(int arr[], int n) {\n int high = 0;\n for (int i = 0; i < n; i++)\n high = max(high, arr[i]);\n int divisors[high + 1] = { 0 }; //array to store all gcd values\n for (int i = 0; i < n; i++) {\n for (int j = 1; j <= sqrt(arr[i]); j++) {\n if (arr[i] % j == 0) {\n divisors[j]++;\n if (j != arr[i] / j)\n divisors[arr[i] / j]++;\n }\n }\n }\n for (int i = high; i >= 1; i--)\n if (divisors[i] > 1)\n return i;\n}\nint main() {\n int arr[] = { 1, 2, 4, 8, 12 };\n int n = sizeof(arr) / sizeof(arr[0]);\n cout << \"Max GCD: \" << getMaxGCD(arr,n);\n}"
},
{
"code": null,
"e": 2403,
"s": 2392,
"text": "Max GCD: 4"
}
] |
C# Program to Convert Fahrenheit to Celsius
|
Firstly, set the Fahrenheit temperature −
double fahrenheit = 97;
Console.WriteLine("Fahrenheit: " + fahrenheit);
Now convert it into Celsius −
celsius = (fahrenheit - 32) * 5 / 9;
You can try to run the following code to convert Fahrenheit to Celsius.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
double celsius;
double fahrenheit = 97;
Console.WriteLine("Fahrenheit: " + fahrenheit);
celsius = (fahrenheit - 32) * 5 / 9;
Console.WriteLine("Celsius: " + celsius);
Console.ReadLine();
}
}
}
Fahrenheit: 97
Celsius: 36.1111111111111
|
[
{
"code": null,
"e": 1104,
"s": 1062,
"text": "Firstly, set the Fahrenheit temperature −"
},
{
"code": null,
"e": 1176,
"s": 1104,
"text": "double fahrenheit = 97;\nConsole.WriteLine(\"Fahrenheit: \" + fahrenheit);"
},
{
"code": null,
"e": 1206,
"s": 1176,
"text": "Now convert it into Celsius −"
},
{
"code": null,
"e": 1243,
"s": 1206,
"text": "celsius = (fahrenheit - 32) * 5 / 9;"
},
{
"code": null,
"e": 1315,
"s": 1243,
"text": "You can try to run the following code to convert Fahrenheit to Celsius."
},
{
"code": null,
"e": 1325,
"s": 1315,
"text": "Live Demo"
},
{
"code": null,
"e": 1749,
"s": 1325,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n double celsius;\n double fahrenheit = 97;\n Console.WriteLine(\"Fahrenheit: \" + fahrenheit);\n celsius = (fahrenheit - 32) * 5 / 9;\n Console.WriteLine(\"Celsius: \" + celsius);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1790,
"s": 1749,
"text": "Fahrenheit: 97\nCelsius: 36.1111111111111"
}
] |
Python Pandas - Plot multiple data columns in a DataFrame?
|
To plot multiple columns, we will be plotting a Bar Graph. Use the plot() method and set the kind parameter to bar for Bar Graph. Let us first import the required libraries −
import pandas as pd
import matplotlib.pyplot as mp
Following is our data with Team Records −
data = [["Australia", 2500, 2021],["Bangladesh", 1000, 2021],["England", 2000, 2021],["India", 3000, 2021],["Srilanka", 1500, 2021]]
Set the data as Pandas DataFrame and add columns −
dataFrame = pd.DataFrame(data, columns=["Team","Rank_Points", "Year"])
Plot multiple columns in a bar graph. We have set the “kind” parameter as “bar” for this −
dataFrame.plot(x="Team", y=["Rank_Points","Year" ], kind="bar", figsize=(10, 9))
Following is the code −
import pandas as pd
import matplotlib.pyplot as mp
# our data
data = [["Australia", 2500, 2021],["Bangladesh", 1000, 2021],["England", 2000, 2021],["India", 3000, 2021],["Srilanka", 1500, 2021]]
# dataframe
dataFrame = pd.DataFrame(data, columns=["Team","Rank_Points", "Year"])
# plotting multiple columns in a bar Graph
dataFrame.plot(x="Team", y=["Rank_Points","Year" ], kind="bar", figsize=(10, 9))
# displaying bar graph
mp.show()
This will produce the following output −
|
[
{
"code": null,
"e": 1237,
"s": 1062,
"text": "To plot multiple columns, we will be plotting a Bar Graph. Use the plot() method and set the kind parameter to bar for Bar Graph. Let us first import the required libraries −"
},
{
"code": null,
"e": 1288,
"s": 1237,
"text": "import pandas as pd\nimport matplotlib.pyplot as mp"
},
{
"code": null,
"e": 1330,
"s": 1288,
"text": "Following is our data with Team Records −"
},
{
"code": null,
"e": 1463,
"s": 1330,
"text": "data = [[\"Australia\", 2500, 2021],[\"Bangladesh\", 1000, 2021],[\"England\", 2000, 2021],[\"India\", 3000, 2021],[\"Srilanka\", 1500, 2021]]"
},
{
"code": null,
"e": 1514,
"s": 1463,
"text": "Set the data as Pandas DataFrame and add columns −"
},
{
"code": null,
"e": 1586,
"s": 1514,
"text": "dataFrame = pd.DataFrame(data, columns=[\"Team\",\"Rank_Points\", \"Year\"])\n"
},
{
"code": null,
"e": 1677,
"s": 1586,
"text": "Plot multiple columns in a bar graph. We have set the “kind” parameter as “bar” for this −"
},
{
"code": null,
"e": 1758,
"s": 1677,
"text": "dataFrame.plot(x=\"Team\", y=[\"Rank_Points\",\"Year\" ], kind=\"bar\", figsize=(10, 9))"
},
{
"code": null,
"e": 1782,
"s": 1758,
"text": "Following is the code −"
},
{
"code": null,
"e": 2221,
"s": 1782,
"text": "import pandas as pd\nimport matplotlib.pyplot as mp\n\n# our data\ndata = [[\"Australia\", 2500, 2021],[\"Bangladesh\", 1000, 2021],[\"England\", 2000, 2021],[\"India\", 3000, 2021],[\"Srilanka\", 1500, 2021]]\n\n# dataframe\ndataFrame = pd.DataFrame(data, columns=[\"Team\",\"Rank_Points\", \"Year\"])\n\n# plotting multiple columns in a bar Graph\ndataFrame.plot(x=\"Team\", y=[\"Rank_Points\",\"Year\" ], kind=\"bar\", figsize=(10, 9))\n\n# displaying bar graph\nmp.show()"
},
{
"code": null,
"e": 2262,
"s": 2221,
"text": "This will produce the following output −"
}
] |
cp - Unix, Linux Command
|
cp - To copy one or more files to another location.
cp [options]... Source Dest
cp [options]... Source... Directory
By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files.
The backup suffix is >, unless set with SIMPLE_BACKUP_SUFFIX. The version control can be set with VERSION_CONTROL, values are: t, numbered make numbered backups nil, existing numbered if numbered backups exist, simple otherwise never, simple always make simple backups. As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file.
Copy sample.txt to sample.bak.
$ cat sample.txt
This is a sample file
$ cp sample.txt sample.bak
$ cat sample.bak
This is a sample file
Copy sample directory to home directory
$ cp -f /user/sample/* >
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": 10629,
"s": 10577,
"text": "cp - To copy one or more files to another location."
},
{
"code": null,
"e": 10693,
"s": 10629,
"text": "cp [options]... Source Dest\ncp [options]... Source... Directory"
},
{
"code": null,
"e": 11044,
"s": 10693,
"text": "By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files."
},
{
"code": null,
"e": 11474,
"s": 11044,
"text": "The backup suffix is >, unless set with SIMPLE_BACKUP_SUFFIX. The version control can be set with VERSION_CONTROL, values are: t, numbered make numbered backups nil, existing numbered if numbered backups exist, simple otherwise never, simple always make simple backups. As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file."
},
{
"code": null,
"e": 11505,
"s": 11474,
"text": "Copy sample.txt to sample.bak."
},
{
"code": null,
"e": 11611,
"s": 11505,
"text": "$ cat sample.txt\nThis is a sample file\n$ cp sample.txt sample.bak\n$ cat sample.bak\nThis is a sample file\n"
},
{
"code": null,
"e": 11651,
"s": 11611,
"text": "Copy sample directory to home directory"
},
{
"code": null,
"e": 11677,
"s": 11651,
"text": "$ cp -f /user/sample/* >\n"
},
{
"code": null,
"e": 11712,
"s": 11677,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 11740,
"s": 11712,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 11774,
"s": 11740,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11791,
"s": 11774,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11824,
"s": 11791,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11835,
"s": 11824,
"text": " Pradeep D"
},
{
"code": null,
"e": 11870,
"s": 11835,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11886,
"s": 11870,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 11919,
"s": 11886,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11931,
"s": 11919,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 11963,
"s": 11931,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11971,
"s": 11963,
"text": " Uplatz"
},
{
"code": null,
"e": 11978,
"s": 11971,
"text": " Print"
},
{
"code": null,
"e": 11989,
"s": 11978,
"text": " Add Notes"
}
] |
How to make back button twice to close an activity in Android?
|
Sometimes we click back button unintentionally, When you click on a back button it will close your application or will go back to another activity. To avoid this problem, This example demonstrates how to make back button twice to close an activity.
Step 1 - Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 - Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/parent"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:gravity = "center"
android:background = "#33FFFF00"
android:orientation = "vertical">
<TextView
android:id = "@+id/text"
android:textSize = "18sp"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
Step 3 - Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
private static final int TIME_INTERVAL = 2000;
private long mBackPressed;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
}
@Override
public void onBackPressed() {
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
Toast.makeText(getBaseContext(), "Click two times to close an activity", Toast.LENGTH_SHORT).show();
}
mBackPressed = System.currentTimeMillis();
}
}
When a user clicks on the back button it will call onBackpressed(). it going to check two time-pressed or not as shown below -
@Override
public void onBackPressed() {
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
Toast.makeText(getBaseContext(), "Click two times to close an activity", Toast.LENGTH_SHORT).show(); }
mBackPressed = System.currentTimeMillis();
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -
Once you click on a back button it will show screen as shown above. Now click on twice it will close an application.
Click here to download the project code
|
[
{
"code": null,
"e": 1311,
"s": 1062,
"text": "Sometimes we click back button unintentionally, When you click on a back button it will close your application or will go back to another activity. To avoid this problem, This example demonstrates how to make back button twice to close an activity."
},
{
"code": null,
"e": 1440,
"s": 1311,
"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": 1505,
"s": 1440,
"text": "Step 2 - Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2110,
"s": 1505,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:gravity = \"center\"\n android:background = \"#33FFFF00\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"18sp\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2167,
"s": 2110,
"text": "Step 3 - Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3439,
"s": 2167,
"text": "package com.example.andy.myapplication;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.VibrationEffect;\nimport android.os.Vibrator;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n private static final int TIME_INTERVAL = 2000;\n private long mBackPressed;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n }\n @Override\n public void onBackPressed() {\n if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {\n super.onBackPressed();\n return;\n } else {\n Toast.makeText(getBaseContext(), \"Click two times to close an activity\", Toast.LENGTH_SHORT).show();\n }\n mBackPressed = System.currentTimeMillis();\n }\n}"
},
{
"code": null,
"e": 3566,
"s": 3439,
"text": "When a user clicks on the back button it will call onBackpressed(). it going to check two time-pressed or not as shown below -"
},
{
"code": null,
"e": 3894,
"s": 3566,
"text": "@Override\npublic void onBackPressed() {\n if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {\n super.onBackPressed();\n return;\n } else {\n Toast.makeText(getBaseContext(), \"Click two times to close an activity\", Toast.LENGTH_SHORT).show(); }\n mBackPressed = System.currentTimeMillis();\n }\n}"
},
{
"code": null,
"e": 4241,
"s": 3894,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -"
},
{
"code": null,
"e": 4358,
"s": 4241,
"text": "Once you click on a back button it will show screen as shown above. Now click on twice it will close an application."
},
{
"code": null,
"e": 4398,
"s": 4358,
"text": "Click here to download the project code"
}
] |
Add new Variables to a Data Frame using Existing Variables in R Programming - mutate() Function - GeeksforGeeks
|
19 Jun, 2020
mutate() function in R Language is used to add new variables in a data frame which are formed by performing operation on existing variables.
Syntax: mutate(x, expr)
Parameters:x: Data Frameexpr: operation on variables
Example 1:
# R program to add new variables# in a data frame # Loading library library(dplyr) # Create a data framed <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c("yes", "yes", "no", "no") ) # Calculating a variable x3 which is sum of height # and age printing with ht and age mutate(d, x3 = ht + age)
Output:
name age ht school x3
1 Abhi 7 46 yes 53
2 Bhavesh 5 NA yes NA
3 Chaman 9 NA no NA
4 Dimri 16 69 no 85
Example 2:
# R program to add new variables# in a data frame # Loading library library(dplyr) # Create a data framed <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c("yes", "yes", "no", "no") ) # Calculating a variable x3 which is product of height # and age printing with ht and age mutate(d, x3 = ht * age)
Output:
name age ht school x3
1 Abhi 7 46 yes 322
2 Bhavesh 5 NA yes NA
3 Chaman 9 NA no NA
4 Dimri 16 69 no 1104
R DataFrame-Function
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": "\n19 Jun, 2020"
},
{
"code": null,
"e": 25383,
"s": 25242,
"text": "mutate() function in R Language is used to add new variables in a data frame which are formed by performing operation on existing variables."
},
{
"code": null,
"e": 25407,
"s": 25383,
"text": "Syntax: mutate(x, expr)"
},
{
"code": null,
"e": 25460,
"s": 25407,
"text": "Parameters:x: Data Frameexpr: operation on variables"
},
{
"code": null,
"e": 25471,
"s": 25460,
"text": "Example 1:"
},
{
"code": "# R program to add new variables# in a data frame # Loading library library(dplyr) # Create a data framed <- data.frame( name = c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c(\"yes\", \"yes\", \"no\", \"no\") ) # Calculating a variable x3 which is sum of height # and age printing with ht and age mutate(d, x3 = ht + age) ",
"e": 25899,
"s": 25471,
"text": null
},
{
"code": null,
"e": 25907,
"s": 25899,
"text": "Output:"
},
{
"code": null,
"e": 26043,
"s": 25907,
"text": " name age ht school x3\n1 Abhi 7 46 yes 53\n2 Bhavesh 5 NA yes NA\n3 Chaman 9 NA no NA\n4 Dimri 16 69 no 85\n"
},
{
"code": null,
"e": 26054,
"s": 26043,
"text": "Example 2:"
},
{
"code": "# R program to add new variables# in a data frame # Loading library library(dplyr) # Create a data framed <- data.frame( name = c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c(\"yes\", \"yes\", \"no\", \"no\") ) # Calculating a variable x3 which is product of height # and age printing with ht and age mutate(d, x3 = ht * age) ",
"e": 26486,
"s": 26054,
"text": null
},
{
"code": null,
"e": 26494,
"s": 26486,
"text": "Output:"
},
{
"code": null,
"e": 26640,
"s": 26494,
"text": " name age ht school x3\n1 Abhi 7 46 yes 322\n2 Bhavesh 5 NA yes NA\n3 Chaman 9 NA no NA\n4 Dimri 16 69 no 1104\n"
},
{
"code": null,
"e": 26661,
"s": 26640,
"text": "R DataFrame-Function"
},
{
"code": null,
"e": 26672,
"s": 26661,
"text": "R Language"
},
{
"code": null,
"e": 26770,
"s": 26672,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26822,
"s": 26770,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26860,
"s": 26822,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26895,
"s": 26860,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26953,
"s": 26895,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27002,
"s": 26953,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27039,
"s": 27002,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 27089,
"s": 27039,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27132,
"s": 27089,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27158,
"s": 27132,
"text": "Time Series Analysis in R"
}
] |
Find the profit and loss in the given Excel sheet using Pandas - GeeksforGeeks
|
05 Sep, 2020
In these articles, we will discuss how to extract data from the Excel file and find the profit and loss at the given data. Suppose our Excel file looks like then we have to extract the Selling Price and Cost Price from the column and find the profit and loss and store it into a new DataFrame column.
To get the excel file used click here.
So, Let’s discuss the approach:
Step 1: Import the required module and read data from excel.
Python3
# importing module import pandas as pd; # Creating df# Reading data from Exceldata = pd.read_excel("excel_work/book_sample.xlsx"); print("Original DataFrame")data
Output :
Step 2: Create a new column in DataFrame for store Profit and Loss
Python3
# Create column for profit and lossdata['Profit']= Nonedata['Loss']= None data
Output :
Step 3: Set Index for Selling price, Cost price, Profit, and loss for accessing the DataFrame columns
Python3
# set indexindex_selling = data.columns.get_loc('Selling Price')index_cost = data.columns.get_loc('Cost price')index_profit = data.columns.get_loc('Profit')index_loss = data.columns.get_loc('Loss') print(index_selling, index_cost, index_profit, index_loss)
Output :
2 3 4 5
Step 4: Compute profit and loss according to there each column index.
Profit = Selling price - Cost price
Loss = Cost price - Selling price
Python3
# Loop for accessing every index in DataFrame# and compute Profit and loss# and store into new column in DataFramefor row in range(0, len(data)): if data.iat[row, index_selling] > data.iat[row, index_cost]: data.iat[row, index_profit] = data.iat[row, index_selling] - data.iat[row, index_cost] else: data.iat[row, index_loss] = data.iat[row, index_cost]-data.iat[row, index_selling]data
Output :
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Python | os.path.join() method
Defaultdict in Python
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": "\n05 Sep, 2020"
},
{
"code": null,
"e": 24593,
"s": 24292,
"text": "In these articles, we will discuss how to extract data from the Excel file and find the profit and loss at the given data. Suppose our Excel file looks like then we have to extract the Selling Price and Cost Price from the column and find the profit and loss and store it into a new DataFrame column."
},
{
"code": null,
"e": 24632,
"s": 24593,
"text": "To get the excel file used click here."
},
{
"code": null,
"e": 24664,
"s": 24632,
"text": "So, Let’s discuss the approach:"
},
{
"code": null,
"e": 24725,
"s": 24664,
"text": "Step 1: Import the required module and read data from excel."
},
{
"code": null,
"e": 24733,
"s": 24725,
"text": "Python3"
},
{
"code": "# importing module import pandas as pd; # Creating df# Reading data from Exceldata = pd.read_excel(\"excel_work/book_sample.xlsx\"); print(\"Original DataFrame\")data",
"e": 24899,
"s": 24733,
"text": null
},
{
"code": null,
"e": 24908,
"s": 24899,
"text": "Output :"
},
{
"code": null,
"e": 24975,
"s": 24908,
"text": "Step 2: Create a new column in DataFrame for store Profit and Loss"
},
{
"code": null,
"e": 24983,
"s": 24975,
"text": "Python3"
},
{
"code": "# Create column for profit and lossdata['Profit']= Nonedata['Loss']= None data",
"e": 25063,
"s": 24983,
"text": null
},
{
"code": null,
"e": 25072,
"s": 25063,
"text": "Output :"
},
{
"code": null,
"e": 25174,
"s": 25072,
"text": "Step 3: Set Index for Selling price, Cost price, Profit, and loss for accessing the DataFrame columns"
},
{
"code": null,
"e": 25182,
"s": 25174,
"text": "Python3"
},
{
"code": "# set indexindex_selling = data.columns.get_loc('Selling Price')index_cost = data.columns.get_loc('Cost price')index_profit = data.columns.get_loc('Profit')index_loss = data.columns.get_loc('Loss') print(index_selling, index_cost, index_profit, index_loss)",
"e": 25440,
"s": 25182,
"text": null
},
{
"code": null,
"e": 25449,
"s": 25440,
"text": "Output :"
},
{
"code": null,
"e": 25458,
"s": 25449,
"text": "2 3 4 5\n"
},
{
"code": null,
"e": 25528,
"s": 25458,
"text": "Step 4: Compute profit and loss according to there each column index."
},
{
"code": null,
"e": 25598,
"s": 25528,
"text": "Profit = Selling price - Cost price\nLoss = Cost price - Selling price"
},
{
"code": null,
"e": 25606,
"s": 25598,
"text": "Python3"
},
{
"code": "# Loop for accessing every index in DataFrame# and compute Profit and loss# and store into new column in DataFramefor row in range(0, len(data)): if data.iat[row, index_selling] > data.iat[row, index_cost]: data.iat[row, index_profit] = data.iat[row, index_selling] - data.iat[row, index_cost] else: data.iat[row, index_loss] = data.iat[row, index_cost]-data.iat[row, index_selling]data",
"e": 26103,
"s": 25606,
"text": null
},
{
"code": null,
"e": 26112,
"s": 26103,
"text": "Output :"
},
{
"code": null,
"e": 26135,
"s": 26112,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 26149,
"s": 26135,
"text": "Python-pandas"
},
{
"code": null,
"e": 26156,
"s": 26149,
"text": "Python"
},
{
"code": null,
"e": 26254,
"s": 26156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26286,
"s": 26254,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26328,
"s": 26286,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26384,
"s": 26328,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26426,
"s": 26384,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26457,
"s": 26426,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26479,
"s": 26457,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26534,
"s": 26479,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26573,
"s": 26534,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26602,
"s": 26573,
"text": "Create a directory in Python"
}
] |
PL/SQL - Data Types
|
In this chapter, we will discuss the Data Types in PL/SQL. The PL/SQL variables, constants and parameters must have a valid data type, which specifies a storage format, constraints, and a valid range of values. We will focus on the SCALAR and the LOB data types in this chapter. The other two data types will be covered in other chapters.
Scalar
Single values with no internal components, such as a NUMBER, DATE, or BOOLEAN.
Large Object (LOB)
Pointers to large objects that are stored separately from other data items, such as text, graphic images, video clips, and sound waveforms.
Composite
Data items that have internal components that can be accessed individually. For example, collections and records.
Reference
Pointers to other data items.
PL/SQL Scalar Data Types and Subtypes come under the following categories −
Numeric
Numeric values on which arithmetic operations are performed.
Character
Alphanumeric values that represent single characters or strings of characters.
Boolean
Logical values on which logical operations are performed.
Datetime
Dates and times.
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype called INTEGER. You can use the subtypes in your PL/SQL program to make the data types compatible with data types in other programs while embedding the PL/SQL code in another program, such as a Java program.
Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −
PLS_INTEGER
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
BINARY_INTEGER
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
BINARY_FLOAT
Single-precision IEEE 754-format floating-point number
BINARY_DOUBLE
Double-precision IEEE 754-format floating-point number
NUMBER(prec, scale)
Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including) 1.0E126. A NUMBER variable can also represent 0
DEC(prec, scale)
ANSI specific fixed-point type with maximum precision of 38 decimal digits
DECIMAL(prec, scale)
IBM specific fixed-point type with maximum precision of 38 decimal digits
NUMERIC(pre, secale)
Floating type with maximum precision of 38 decimal digits
DOUBLE PRECISION
ANSI specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)
FLOAT
ANSI and IBM specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)
INT
ANSI specific integer type with maximum precision of 38 decimal digits
INTEGER
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
SMALLINT
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
REAL
Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits)
Following is a valid declaration −
DECLARE
num1 INTEGER;
num2 REAL;
num3 DOUBLE PRECISION;
BEGIN
null;
END;
/
When the above code is compiled and executed, it produces the following result −
PL/SQL procedure successfully completed
Following is the detail of PL/SQL pre-defined character data types and their sub-types −
CHAR
Fixed-length character string with maximum size of 32,767 bytes
VARCHAR2
Variable-length character string with maximum size of 32,767 bytes
RAW
Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted by PL/SQL
NCHAR
Fixed-length national character string with maximum size of 32,767 bytes
NVARCHAR2
Variable-length national character string with maximum size of 32,767 bytes
LONG
Variable-length character string with maximum size of 32,760 bytes
LONG RAW
Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by PL/SQL
ROWID
Physical row identifier, the address of a row in an ordinary table
UROWID
Universal row identifier (physical, logical, or foreign row identifier)
The BOOLEAN data type stores logical values that are used in logical operations. The logical values are the Boolean values TRUE and FALSE and the value NULL.
However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values cannot be used in −
SQL statements
Built-in SQL functions (such as TO_CHAR)
PL/SQL functions invoked from SQL statements
The DATE datatype is used to store fixed-length datetimes, which include the time of day in seconds since midnight. Valid dates range from January 1, 4712 BC to December 31, 9999 AD.
The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT. For example, the default might be 'DD-MON-YY', which includes a two-digit number for the day of the month, an abbreviation of the month name, and the last two digits of the year. For example, 01-OCT-12.
Each DATE includes the century, year, month, day, hour, minute, and second. The following table shows the valid values for each field −
Large Object (LOB) data types refer to large data items such as text, graphic images, video clips, and sound waveforms. LOB data types allow efficient, random, piecewise access to this data. Following are the predefined PL/SQL LOB data types −
A subtype is a subset of another data type, which is called its base type. A subtype has the same valid operations as its base type, but only a subset of its valid values.
PL/SQL predefines several subtypes in package STANDARD. For example, PL/SQL predefines the subtypes CHARACTER and INTEGER as follows −
SUBTYPE CHARACTER IS CHAR;
SUBTYPE INTEGER IS NUMBER(38,0);
You can define and use your own subtypes. The following program illustrates defining and using a user-defined subtype −
DECLARE
SUBTYPE name IS char(20);
SUBTYPE message IS varchar2(100);
salutation name;
greetings message;
BEGIN
salutation := 'Reader ';
greetings := 'Welcome to the World of PL/SQL';
dbms_output.put_line('Hello ' || salutation || greetings);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Hello Reader Welcome to the World of PL/SQL
PL/SQL procedure successfully completed.
PL/SQL NULL values represent missing or unknown data and they are not an integer, a character, or any other specific data type. Note that NULL is not the same as an empty data string or the null character value '\0'. A null can be assigned but it cannot be equated with anything, including itself.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2404,
"s": 2065,
"text": "In this chapter, we will discuss the Data Types in PL/SQL. The PL/SQL variables, constants and parameters must have a valid data type, which specifies a storage format, constraints, and a valid range of values. We will focus on the SCALAR and the LOB data types in this chapter. The other two data types will be covered in other chapters."
},
{
"code": null,
"e": 2411,
"s": 2404,
"text": "Scalar"
},
{
"code": null,
"e": 2490,
"s": 2411,
"text": "Single values with no internal components, such as a NUMBER, DATE, or BOOLEAN."
},
{
"code": null,
"e": 2509,
"s": 2490,
"text": "Large Object (LOB)"
},
{
"code": null,
"e": 2649,
"s": 2509,
"text": "Pointers to large objects that are stored separately from other data items, such as text, graphic images, video clips, and sound waveforms."
},
{
"code": null,
"e": 2659,
"s": 2649,
"text": "Composite"
},
{
"code": null,
"e": 2773,
"s": 2659,
"text": "Data items that have internal components that can be accessed individually. For example, collections and records."
},
{
"code": null,
"e": 2783,
"s": 2773,
"text": "Reference"
},
{
"code": null,
"e": 2813,
"s": 2783,
"text": "Pointers to other data items."
},
{
"code": null,
"e": 2889,
"s": 2813,
"text": "PL/SQL Scalar Data Types and Subtypes come under the following categories −"
},
{
"code": null,
"e": 2897,
"s": 2889,
"text": "Numeric"
},
{
"code": null,
"e": 2958,
"s": 2897,
"text": "Numeric values on which arithmetic operations are performed."
},
{
"code": null,
"e": 2968,
"s": 2958,
"text": "Character"
},
{
"code": null,
"e": 3047,
"s": 2968,
"text": "Alphanumeric values that represent single characters or strings of characters."
},
{
"code": null,
"e": 3055,
"s": 3047,
"text": "Boolean"
},
{
"code": null,
"e": 3113,
"s": 3055,
"text": "Logical values on which logical operations are performed."
},
{
"code": null,
"e": 3122,
"s": 3113,
"text": "Datetime"
},
{
"code": null,
"e": 3139,
"s": 3122,
"text": "Dates and times."
},
{
"code": null,
"e": 3435,
"s": 3139,
"text": "PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype called INTEGER. You can use the subtypes in your PL/SQL program to make the data types compatible with data types in other programs while embedding the PL/SQL code in another program, such as a Java program."
},
{
"code": null,
"e": 3525,
"s": 3435,
"text": "Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −"
},
{
"code": null,
"e": 3537,
"s": 3525,
"text": "PLS_INTEGER"
},
{
"code": null,
"e": 3622,
"s": 3537,
"text": "Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits"
},
{
"code": null,
"e": 3637,
"s": 3622,
"text": "BINARY_INTEGER"
},
{
"code": null,
"e": 3722,
"s": 3637,
"text": "Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits"
},
{
"code": null,
"e": 3735,
"s": 3722,
"text": "BINARY_FLOAT"
},
{
"code": null,
"e": 3790,
"s": 3735,
"text": "Single-precision IEEE 754-format floating-point number"
},
{
"code": null,
"e": 3804,
"s": 3790,
"text": "BINARY_DOUBLE"
},
{
"code": null,
"e": 3859,
"s": 3804,
"text": "Double-precision IEEE 754-format floating-point number"
},
{
"code": null,
"e": 3879,
"s": 3859,
"text": "NUMBER(prec, scale)"
},
{
"code": null,
"e": 4023,
"s": 3879,
"text": "Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including) 1.0E126. A NUMBER variable can also represent 0"
},
{
"code": null,
"e": 4040,
"s": 4023,
"text": "DEC(prec, scale)"
},
{
"code": null,
"e": 4115,
"s": 4040,
"text": "ANSI specific fixed-point type with maximum precision of 38 decimal digits"
},
{
"code": null,
"e": 4136,
"s": 4115,
"text": "DECIMAL(prec, scale)"
},
{
"code": null,
"e": 4210,
"s": 4136,
"text": "IBM specific fixed-point type with maximum precision of 38 decimal digits"
},
{
"code": null,
"e": 4231,
"s": 4210,
"text": "NUMERIC(pre, secale)"
},
{
"code": null,
"e": 4289,
"s": 4231,
"text": "Floating type with maximum precision of 38 decimal digits"
},
{
"code": null,
"e": 4306,
"s": 4289,
"text": "DOUBLE PRECISION"
},
{
"code": null,
"e": 4418,
"s": 4306,
"text": "ANSI specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)"
},
{
"code": null,
"e": 4424,
"s": 4418,
"text": "FLOAT"
},
{
"code": null,
"e": 4544,
"s": 4424,
"text": "ANSI and IBM specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)"
},
{
"code": null,
"e": 4548,
"s": 4544,
"text": "INT"
},
{
"code": null,
"e": 4619,
"s": 4548,
"text": "ANSI specific integer type with maximum precision of 38 decimal digits"
},
{
"code": null,
"e": 4627,
"s": 4619,
"text": "INTEGER"
},
{
"code": null,
"e": 4706,
"s": 4627,
"text": "ANSI and IBM specific integer type with maximum precision of 38 decimal digits"
},
{
"code": null,
"e": 4715,
"s": 4706,
"text": "SMALLINT"
},
{
"code": null,
"e": 4794,
"s": 4715,
"text": "ANSI and IBM specific integer type with maximum precision of 38 decimal digits"
},
{
"code": null,
"e": 4799,
"s": 4794,
"text": "REAL"
},
{
"code": null,
"e": 4896,
"s": 4799,
"text": "Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits)"
},
{
"code": null,
"e": 4931,
"s": 4896,
"text": "Following is a valid declaration −"
},
{
"code": null,
"e": 5026,
"s": 4931,
"text": "DECLARE \n num1 INTEGER; \n num2 REAL; \n num3 DOUBLE PRECISION; \nBEGIN \n null; \nEND; \n/ "
},
{
"code": null,
"e": 5107,
"s": 5026,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5148,
"s": 5107,
"text": "PL/SQL procedure successfully completed "
},
{
"code": null,
"e": 5237,
"s": 5148,
"text": "Following is the detail of PL/SQL pre-defined character data types and their sub-types −"
},
{
"code": null,
"e": 5242,
"s": 5237,
"text": "CHAR"
},
{
"code": null,
"e": 5306,
"s": 5242,
"text": "Fixed-length character string with maximum size of 32,767 bytes"
},
{
"code": null,
"e": 5315,
"s": 5306,
"text": "VARCHAR2"
},
{
"code": null,
"e": 5382,
"s": 5315,
"text": "Variable-length character string with maximum size of 32,767 bytes"
},
{
"code": null,
"e": 5386,
"s": 5382,
"text": "RAW"
},
{
"code": null,
"e": 5485,
"s": 5386,
"text": "Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted by PL/SQL"
},
{
"code": null,
"e": 5491,
"s": 5485,
"text": "NCHAR"
},
{
"code": null,
"e": 5564,
"s": 5491,
"text": "Fixed-length national character string with maximum size of 32,767 bytes"
},
{
"code": null,
"e": 5574,
"s": 5564,
"text": "NVARCHAR2"
},
{
"code": null,
"e": 5650,
"s": 5574,
"text": "Variable-length national character string with maximum size of 32,767 bytes"
},
{
"code": null,
"e": 5655,
"s": 5650,
"text": "LONG"
},
{
"code": null,
"e": 5722,
"s": 5655,
"text": "Variable-length character string with maximum size of 32,760 bytes"
},
{
"code": null,
"e": 5731,
"s": 5722,
"text": "LONG RAW"
},
{
"code": null,
"e": 5830,
"s": 5731,
"text": "Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by PL/SQL"
},
{
"code": null,
"e": 5836,
"s": 5830,
"text": "ROWID"
},
{
"code": null,
"e": 5903,
"s": 5836,
"text": "Physical row identifier, the address of a row in an ordinary table"
},
{
"code": null,
"e": 5910,
"s": 5903,
"text": "UROWID"
},
{
"code": null,
"e": 5982,
"s": 5910,
"text": "Universal row identifier (physical, logical, or foreign row identifier)"
},
{
"code": null,
"e": 6140,
"s": 5982,
"text": "The BOOLEAN data type stores logical values that are used in logical operations. The logical values are the Boolean values TRUE and FALSE and the value NULL."
},
{
"code": null,
"e": 6240,
"s": 6140,
"text": "However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values cannot be used in − "
},
{
"code": null,
"e": 6255,
"s": 6240,
"text": "SQL statements"
},
{
"code": null,
"e": 6296,
"s": 6255,
"text": "Built-in SQL functions (such as TO_CHAR)"
},
{
"code": null,
"e": 6341,
"s": 6296,
"text": "PL/SQL functions invoked from SQL statements"
},
{
"code": null,
"e": 6524,
"s": 6341,
"text": "The DATE datatype is used to store fixed-length datetimes, which include the time of day in seconds since midnight. Valid dates range from January 1, 4712 BC to December 31, 9999 AD."
},
{
"code": null,
"e": 6814,
"s": 6524,
"text": "The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT. For example, the default might be 'DD-MON-YY', which includes a two-digit number for the day of the month, an abbreviation of the month name, and the last two digits of the year. For example, 01-OCT-12."
},
{
"code": null,
"e": 6950,
"s": 6814,
"text": "Each DATE includes the century, year, month, day, hour, minute, and second. The following table shows the valid values for each field −"
},
{
"code": null,
"e": 7194,
"s": 6950,
"text": "Large Object (LOB) data types refer to large data items such as text, graphic images, video clips, and sound waveforms. LOB data types allow efficient, random, piecewise access to this data. Following are the predefined PL/SQL LOB data types −"
},
{
"code": null,
"e": 7366,
"s": 7194,
"text": "A subtype is a subset of another data type, which is called its base type. A subtype has the same valid operations as its base type, but only a subset of its valid values."
},
{
"code": null,
"e": 7501,
"s": 7366,
"text": "PL/SQL predefines several subtypes in package STANDARD. For example, PL/SQL predefines the subtypes CHARACTER and INTEGER as follows −"
},
{
"code": null,
"e": 7563,
"s": 7501,
"text": "SUBTYPE CHARACTER IS CHAR; \nSUBTYPE INTEGER IS NUMBER(38,0);\n"
},
{
"code": null,
"e": 7683,
"s": 7563,
"text": "You can define and use your own subtypes. The following program illustrates defining and using a user-defined subtype −"
},
{
"code": null,
"e": 7963,
"s": 7683,
"text": "DECLARE \n SUBTYPE name IS char(20); \n SUBTYPE message IS varchar2(100); \n salutation name; \n greetings message; \nBEGIN \n salutation := 'Reader '; \n greetings := 'Welcome to the World of PL/SQL'; \n dbms_output.put_line('Hello ' || salutation || greetings); \nEND; \n/ "
},
{
"code": null,
"e": 8049,
"s": 7963,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 8139,
"s": 8049,
"text": "Hello Reader Welcome to the World of PL/SQL \n \nPL/SQL procedure successfully completed. \n"
},
{
"code": null,
"e": 8437,
"s": 8139,
"text": "PL/SQL NULL values represent missing or unknown data and they are not an integer, a character, or any other specific data type. Note that NULL is not the same as an empty data string or the null character value '\\0'. A null can be assigned but it cannot be equated with anything, including itself."
},
{
"code": null,
"e": 8444,
"s": 8437,
"text": " Print"
},
{
"code": null,
"e": 8455,
"s": 8444,
"text": " Add Notes"
}
] |
Check if a graph is Strongly, Unilaterally or Weakly connected - GeeksforGeeks
|
29 May, 2021
Given an unweighted directed graph G as a path matrix, the task is to find out if the graph is Strongly Connected or Unilaterally Connected or Weakly Connected.
Strongly Connected: A graph is said to be strongly connected if every pair of vertices(u, v) in the graph contains a path between each other. In an unweighted directed graph G, every pair of vertices u and v should have a path in each direction between them i.e., bidirectional path. The elements of the path matrix of such a graph will contain all 1’s.Unilaterally Connected: A graph is said to be unilaterally connected if it contains a directed path from u to v OR a directed path from v to u for every pair of vertices u, v. Hence, at least for any pair of vertices, one vertex should be reachable form the other. Such a path matrix would rather have upper triangle elements containing 1’s OR lower triangle elements containing 1’s.Weakly Connected: A graph is said to be weakly connected if there doesn’t exist any path between any two pairs of vertices. Hence, if a graph G doesn’t contain a directed path (from u to v or from v to u for every pair of vertices u, v) then it is weakly connected. The elements of such a path matrix of this graph would be random.
Examples:
Input: Below is the given graph with path matrix:
Output: Strongly Connected Graph Input: Below is the given graph with path matrix:
Output: Unilaterally Connected GraphInput: Below is the given graph with path matrix:
Output: Weakly Connected Graph
Approach:
For the graph to be Strongly Connected, traverse the given path matrix using the approach discussed in this article check whether all the values in the cell are 1 or not. If yes then print “Strongly Connected Graph” else check for the other two graphs.For the graph to be Unilaterally Connected, traverse the given path matrix using the approach discussed in this article and check the following: If all the values above the main diagonal are 1s and all the values other than that are 0s.If all the values below the main diagonal are 1s and all the values other than that are 0s.If one of the above two conditions satisfies then the given graph is Unilaterally Connected else the graph is Weakly Connected Graph.
For the graph to be Strongly Connected, traverse the given path matrix using the approach discussed in this article check whether all the values in the cell are 1 or not. If yes then print “Strongly Connected Graph” else check for the other two graphs.
For the graph to be Unilaterally Connected, traverse the given path matrix using the approach discussed in this article and check the following: If all the values above the main diagonal are 1s and all the values other than that are 0s.If all the values below the main diagonal are 1s and all the values other than that are 0s.
If all the values above the main diagonal are 1s and all the values other than that are 0s.
If all the values below the main diagonal are 1s and all the values other than that are 0s.
If one of the above two conditions satisfies then the given graph is Unilaterally Connected else the graph is Weakly Connected Graph.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define V 3 // Function to find the characteristic// of the given graphint checkConnected(int graph[][V], int n){ // Check whether the graph is // strongly connected or not bool strongly = true; // Traverse the path matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If all the elements are // not equal then the graph // is not strongly connected if (graph[i][j] != graph[j][i]) { strongly = false; break; } } // Break out of the loop if false if (!strongly) { break; } } // If true then print strongly // connected and return if (strongly) { cout << "Strongly Connected"; return 0; } // Check whether the graph is // Unilaterally connected by // checking Upper Triangle element bool uppertri = true; // Traverse the path matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If uppertriangle elements // are 0 then break out of the // loop and check the elements // of lowertriangle matrix if (i > j && graph[i][j] == 0) { uppertri = false; break; } } // Break out of the loop if false if (!uppertri) { break; } } // If true then print unilaterally // connected and return if (uppertri) { cout << "Unilaterally Connected"; return 0; } // Check lowertraingle elements bool lowertri = true; // Traverse the path matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If lowertraingle elements // are 0 then break cause // 1's are expected if (i < j && graph[i][j] == 0) { lowertri = false; break; } } // Break out of the loop if false if (!lowertri) { break; } } // If true then print unilaterally // connected and return if (lowertri) { cout << "Unilaterally Connected"; return 0; } // If elements are in random order // unsynchronized then print weakly // connected and return else { cout << "Weakly Connected"; } return 0;} // Driver Codeint main(){ // Number of nodes int n = 3; // Given Path Matrix int graph[V][V] = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, 0, 0 }, }; // Function Call checkConnected(graph, n); return 0;}
// Java implementation of the above approachimport java.util.*; class GFG{ static final int V = 3; // Function to find the characteristic// of the given graphstatic int checkConnected(int graph[][], int n){ // Check whether the graph is // strongly connected or not boolean strongly = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If all the elements are // not equal then the graph // is not strongly connected if (graph[i][j] != graph[j][i]) { strongly = false; break; } } // Break out of the loop if false if (!strongly) { break; } } // If true then print strongly // connected and return if (strongly) { System.out.print("Strongly Connected"); return 0; } // Check whether the graph is // Unilaterally connected by // checking Upper Triangle element boolean uppertri = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If uppertriangle elements // are 0 then break out of the // loop and check the elements // of lowertriangle matrix if (i > j && graph[i][j] == 0) { uppertri = false; break; } } // Break out of the loop if false if (!uppertri) { break; } } // If true then print unilaterally // connected and return if (uppertri) { System.out.print("Unilaterally Connected"); return 0; } // Check lowertraingle elements boolean lowertri = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If lowertraingle elements // are 0 then break cause // 1's are expected if (i < j && graph[i][j] == 0) { lowertri = false; break; } } // Break out of the loop if false if (!lowertri) { break; } } // If true then print unilaterally // connected and return if (lowertri) { System.out.print("Unilaterally Connected"); return 0; } // If elements are in random order // unsynchronized then print weakly // connected and return else { System.out.print("Weakly Connected"); } return 0;} // Driver Codepublic static void main(String[] args){ // Number of nodes int n = 3; // Given Path Matrix int graph[][] = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, 0, 0 } }; // Function call checkConnected(graph, n);}} // This code is contributed by 29AjayKumar
# Python3 implementation of# the above approachV = 3 # Function to find the# characteristic of the# given graphdef checkConnected(graph, n): # Check whether the graph is # strongly connected or not strongly = True; # Traverse the path # matrix for i in range(n): for j in range(n): # If all the elements are # not equal then the graph # is not strongly connected if (graph[i][j] != graph[j][i]): strongly = False; break # Break out of the # loop if false if not strongly: break; # If true then print # strongly connected and return if (strongly): print("Strongly Connected"); exit() # Check whether the graph is # Unilaterally connected by # checking Upper Triangle element uppertri = True; # Traverse the path matrix for i in range(n): for j in range(n): # If uppertriangle elements # are 0 then break out of the # loop and check the elements # of lowertriangle matrix if (i > j and graph[i][j] == 0): uppertri = False; break; # Break out of the # loop if false if not uppertri: break; # If true then print # unilaterally connected # and return if uppertri: print("Unilaterally Connected"); exit() # Check lowertraingle elements lowertri = True; # Traverse the path matrix for i in range(n): for j in range(n): # If lowertraingle elements # are 0 then break cause # 1's are expected if (i < j and graph[i][j] == 0): lowertri = False; break; # Break out of the # loop if false if not lowertri: break; # If true then print # unilaterally connected # and return if lowertri: print("Unilaterally Connected") exit() # If elements are in random order # unsynchronized then print weakly # connected and return else: print("Weakly Connected") exit() if __name__ == "__main__": # Number of nodes n = 3; # Given Path Matrix graph = [[0, 1, 1], [0, 0, 1], [0, 0, 0]]; # Function Call checkConnected(graph, n); # This code is contributed by rutvik_56
// C# implementation of the above approachusing System; class GFG{ //static readonly int V = 3; // Function to find the characteristic// of the given graphstatic int checkConnected(int [,]graph, int n){ // Check whether the graph is // strongly connected or not bool strongly = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If all the elements are // not equal then the graph // is not strongly connected if (graph[i, j] != graph[j, i]) { strongly = false; break; } } // Break out of the loop if false if (!strongly) { break; } } // If true then print strongly // connected and return if (strongly) { Console.Write("Strongly Connected"); return 0; } // Check whether the graph is // Unilaterally connected by // checking Upper Triangle element bool uppertri = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If uppertriangle elements // are 0 then break out of the // loop and check the elements // of lowertriangle matrix if (i > j && graph[i, j] == 0) { uppertri = false; break; } } // Break out of the loop if false if (!uppertri) { break; } } // If true then print unilaterally // connected and return if (uppertri) { Console.Write("Unilaterally Connected"); return 0; } // Check lowertraingle elements bool lowertri = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If lowertraingle elements // are 0 then break cause // 1's are expected if (i < j && graph[i, j] == 0) { lowertri = false; break; } } // Break out of the loop if false if (!lowertri) { break; } } // If true then print unilaterally // connected and return if (lowertri) { Console.Write("Unilaterally Connected"); return 0; } // If elements are in random order // unsynchronized then print weakly // connected and return else { Console.Write("Weakly Connected"); } return 0;} // Driver Codepublic static void Main(String[] args){ // Number of nodes int n = 3; // Given Path Matrix int [,]graph = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, 0, 0 } }; // Function call checkConnected(graph, n);}} // This code is contributed by 29AjayKumar
<script>// Javascript implementation of the above approach let V = 3; // Function to find the characteristic// of the given graphfunction checkConnected(graph, n){ // Check whether the graph is // strongly connected or not let strongly = true; // Traverse the path matrix for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // If all the elements are // not equal then the graph // is not strongly connected if (graph[i][j] != graph[j][i]) { strongly = false; break; } } // Break out of the loop if false if (!strongly) { break; } } // If true then print strongly // connected and return if (strongly) { document.write("Strongly Connected"); return 0; } // Check whether the graph is // Unilaterally connected by // checking Upper Triangle element let uppertri = true; // Traverse the path matrix for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // If uppertriangle elements // are 0 then break out of the // loop and check the elements // of lowertriangle matrix if (i > j && graph[i][j] == 0) { uppertri = false; break; } } // Break out of the loop if false if (!uppertri) { break; } } // If true then print unilaterally // connected and return if (uppertri) { document.write("Unilaterally Connected"); return 0; } // Check lowertraingle elements let lowertri = true; // Traverse the path matrix for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // If lowertraingle elements // are 0 then break cause // 1's are expected if (i < j && graph[i][j] == 0) { lowertri = false; break; } } // Break out of the loop if false if (!lowertri) { break; } } // If true then print unilaterally // connected and return if (lowertri) { document.write("Unilaterally Connected"); return 0; } // If elements are in random order // unsynchronized then print weakly // connected and return else { document.write("Weakly Connected"); } return 0;} // Driver Code // Number of nodes let n = 3; // Given Path Matrix let graph = [[ 0, 1, 1 ], [ 0, 0, 1 ], [ 0, 0, 0 ]]; // Function call checkConnected(graph, n); // This code is contributed by susmitakundugoaldanga.</script>
Unilaterally Connected
Time Complexity: O(N2) Auxiliary Space: O(1)
29AjayKumar
Akanksha_Rai
rutvik_56
susmitakundugoaldanga
ankita_saini
Algorithms
Arrays
Graph
Mathematical
Matrix
Arrays
Mathematical
Matrix
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
How to write a Pseudo Code?
Difference between Informed and Uninformed Search in AI
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Largest Sum Contiguous Subarray
|
[
{
"code": null,
"e": 24593,
"s": 24565,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 24755,
"s": 24593,
"text": "Given an unweighted directed graph G as a path matrix, the task is to find out if the graph is Strongly Connected or Unilaterally Connected or Weakly Connected. "
},
{
"code": null,
"e": 25823,
"s": 24755,
"text": "Strongly Connected: A graph is said to be strongly connected if every pair of vertices(u, v) in the graph contains a path between each other. In an unweighted directed graph G, every pair of vertices u and v should have a path in each direction between them i.e., bidirectional path. The elements of the path matrix of such a graph will contain all 1’s.Unilaterally Connected: A graph is said to be unilaterally connected if it contains a directed path from u to v OR a directed path from v to u for every pair of vertices u, v. Hence, at least for any pair of vertices, one vertex should be reachable form the other. Such a path matrix would rather have upper triangle elements containing 1’s OR lower triangle elements containing 1’s.Weakly Connected: A graph is said to be weakly connected if there doesn’t exist any path between any two pairs of vertices. Hence, if a graph G doesn’t contain a directed path (from u to v or from v to u for every pair of vertices u, v) then it is weakly connected. The elements of such a path matrix of this graph would be random."
},
{
"code": null,
"e": 25834,
"s": 25823,
"text": "Examples: "
},
{
"code": null,
"e": 25886,
"s": 25834,
"text": "Input: Below is the given graph with path matrix: "
},
{
"code": null,
"e": 25971,
"s": 25886,
"text": "Output: Strongly Connected Graph Input: Below is the given graph with path matrix: "
},
{
"code": null,
"e": 26059,
"s": 25971,
"text": "Output: Unilaterally Connected GraphInput: Below is the given graph with path matrix: "
},
{
"code": null,
"e": 26092,
"s": 26059,
"text": "Output: Weakly Connected Graph "
},
{
"code": null,
"e": 26103,
"s": 26092,
"text": "Approach: "
},
{
"code": null,
"e": 26816,
"s": 26103,
"text": "For the graph to be Strongly Connected, traverse the given path matrix using the approach discussed in this article check whether all the values in the cell are 1 or not. If yes then print “Strongly Connected Graph” else check for the other two graphs.For the graph to be Unilaterally Connected, traverse the given path matrix using the approach discussed in this article and check the following: If all the values above the main diagonal are 1s and all the values other than that are 0s.If all the values below the main diagonal are 1s and all the values other than that are 0s.If one of the above two conditions satisfies then the given graph is Unilaterally Connected else the graph is Weakly Connected Graph."
},
{
"code": null,
"e": 27069,
"s": 26816,
"text": "For the graph to be Strongly Connected, traverse the given path matrix using the approach discussed in this article check whether all the values in the cell are 1 or not. If yes then print “Strongly Connected Graph” else check for the other two graphs."
},
{
"code": null,
"e": 27397,
"s": 27069,
"text": "For the graph to be Unilaterally Connected, traverse the given path matrix using the approach discussed in this article and check the following: If all the values above the main diagonal are 1s and all the values other than that are 0s.If all the values below the main diagonal are 1s and all the values other than that are 0s."
},
{
"code": null,
"e": 27489,
"s": 27397,
"text": "If all the values above the main diagonal are 1s and all the values other than that are 0s."
},
{
"code": null,
"e": 27581,
"s": 27489,
"text": "If all the values below the main diagonal are 1s and all the values other than that are 0s."
},
{
"code": null,
"e": 27715,
"s": 27581,
"text": "If one of the above two conditions satisfies then the given graph is Unilaterally Connected else the graph is Weakly Connected Graph."
},
{
"code": null,
"e": 27767,
"s": 27715,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27771,
"s": 27767,
"text": "C++"
},
{
"code": null,
"e": 27776,
"s": 27771,
"text": "Java"
},
{
"code": null,
"e": 27784,
"s": 27776,
"text": "Python3"
},
{
"code": null,
"e": 27787,
"s": 27784,
"text": "C#"
},
{
"code": null,
"e": 27798,
"s": 27787,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std;#define V 3 // Function to find the characteristic// of the given graphint checkConnected(int graph[][V], int n){ // Check whether the graph is // strongly connected or not bool strongly = true; // Traverse the path matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If all the elements are // not equal then the graph // is not strongly connected if (graph[i][j] != graph[j][i]) { strongly = false; break; } } // Break out of the loop if false if (!strongly) { break; } } // If true then print strongly // connected and return if (strongly) { cout << \"Strongly Connected\"; return 0; } // Check whether the graph is // Unilaterally connected by // checking Upper Triangle element bool uppertri = true; // Traverse the path matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If uppertriangle elements // are 0 then break out of the // loop and check the elements // of lowertriangle matrix if (i > j && graph[i][j] == 0) { uppertri = false; break; } } // Break out of the loop if false if (!uppertri) { break; } } // If true then print unilaterally // connected and return if (uppertri) { cout << \"Unilaterally Connected\"; return 0; } // Check lowertraingle elements bool lowertri = true; // Traverse the path matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If lowertraingle elements // are 0 then break cause // 1's are expected if (i < j && graph[i][j] == 0) { lowertri = false; break; } } // Break out of the loop if false if (!lowertri) { break; } } // If true then print unilaterally // connected and return if (lowertri) { cout << \"Unilaterally Connected\"; return 0; } // If elements are in random order // unsynchronized then print weakly // connected and return else { cout << \"Weakly Connected\"; } return 0;} // Driver Codeint main(){ // Number of nodes int n = 3; // Given Path Matrix int graph[V][V] = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, 0, 0 }, }; // Function Call checkConnected(graph, n); return 0;}",
"e": 30477,
"s": 27798,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*; class GFG{ static final int V = 3; // Function to find the characteristic// of the given graphstatic int checkConnected(int graph[][], int n){ // Check whether the graph is // strongly connected or not boolean strongly = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If all the elements are // not equal then the graph // is not strongly connected if (graph[i][j] != graph[j][i]) { strongly = false; break; } } // Break out of the loop if false if (!strongly) { break; } } // If true then print strongly // connected and return if (strongly) { System.out.print(\"Strongly Connected\"); return 0; } // Check whether the graph is // Unilaterally connected by // checking Upper Triangle element boolean uppertri = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If uppertriangle elements // are 0 then break out of the // loop and check the elements // of lowertriangle matrix if (i > j && graph[i][j] == 0) { uppertri = false; break; } } // Break out of the loop if false if (!uppertri) { break; } } // If true then print unilaterally // connected and return if (uppertri) { System.out.print(\"Unilaterally Connected\"); return 0; } // Check lowertraingle elements boolean lowertri = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If lowertraingle elements // are 0 then break cause // 1's are expected if (i < j && graph[i][j] == 0) { lowertri = false; break; } } // Break out of the loop if false if (!lowertri) { break; } } // If true then print unilaterally // connected and return if (lowertri) { System.out.print(\"Unilaterally Connected\"); return 0; } // If elements are in random order // unsynchronized then print weakly // connected and return else { System.out.print(\"Weakly Connected\"); } return 0;} // Driver Codepublic static void main(String[] args){ // Number of nodes int n = 3; // Given Path Matrix int graph[][] = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, 0, 0 } }; // Function call checkConnected(graph, n);}} // This code is contributed by 29AjayKumar",
"e": 33470,
"s": 30477,
"text": null
},
{
"code": "# Python3 implementation of# the above approachV = 3 # Function to find the# characteristic of the# given graphdef checkConnected(graph, n): # Check whether the graph is # strongly connected or not strongly = True; # Traverse the path # matrix for i in range(n): for j in range(n): # If all the elements are # not equal then the graph # is not strongly connected if (graph[i][j] != graph[j][i]): strongly = False; break # Break out of the # loop if false if not strongly: break; # If true then print # strongly connected and return if (strongly): print(\"Strongly Connected\"); exit() # Check whether the graph is # Unilaterally connected by # checking Upper Triangle element uppertri = True; # Traverse the path matrix for i in range(n): for j in range(n): # If uppertriangle elements # are 0 then break out of the # loop and check the elements # of lowertriangle matrix if (i > j and graph[i][j] == 0): uppertri = False; break; # Break out of the # loop if false if not uppertri: break; # If true then print # unilaterally connected # and return if uppertri: print(\"Unilaterally Connected\"); exit() # Check lowertraingle elements lowertri = True; # Traverse the path matrix for i in range(n): for j in range(n): # If lowertraingle elements # are 0 then break cause # 1's are expected if (i < j and graph[i][j] == 0): lowertri = False; break; # Break out of the # loop if false if not lowertri: break; # If true then print # unilaterally connected # and return if lowertri: print(\"Unilaterally Connected\") exit() # If elements are in random order # unsynchronized then print weakly # connected and return else: print(\"Weakly Connected\") exit() if __name__ == \"__main__\": # Number of nodes n = 3; # Given Path Matrix graph = [[0, 1, 1], [0, 0, 1], [0, 0, 0]]; # Function Call checkConnected(graph, n); # This code is contributed by rutvik_56",
"e": 35931,
"s": 33470,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ //static readonly int V = 3; // Function to find the characteristic// of the given graphstatic int checkConnected(int [,]graph, int n){ // Check whether the graph is // strongly connected or not bool strongly = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If all the elements are // not equal then the graph // is not strongly connected if (graph[i, j] != graph[j, i]) { strongly = false; break; } } // Break out of the loop if false if (!strongly) { break; } } // If true then print strongly // connected and return if (strongly) { Console.Write(\"Strongly Connected\"); return 0; } // Check whether the graph is // Unilaterally connected by // checking Upper Triangle element bool uppertri = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If uppertriangle elements // are 0 then break out of the // loop and check the elements // of lowertriangle matrix if (i > j && graph[i, j] == 0) { uppertri = false; break; } } // Break out of the loop if false if (!uppertri) { break; } } // If true then print unilaterally // connected and return if (uppertri) { Console.Write(\"Unilaterally Connected\"); return 0; } // Check lowertraingle elements bool lowertri = true; // Traverse the path matrix for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If lowertraingle elements // are 0 then break cause // 1's are expected if (i < j && graph[i, j] == 0) { lowertri = false; break; } } // Break out of the loop if false if (!lowertri) { break; } } // If true then print unilaterally // connected and return if (lowertri) { Console.Write(\"Unilaterally Connected\"); return 0; } // If elements are in random order // unsynchronized then print weakly // connected and return else { Console.Write(\"Weakly Connected\"); } return 0;} // Driver Codepublic static void Main(String[] args){ // Number of nodes int n = 3; // Given Path Matrix int [,]graph = { { 0, 1, 1 }, { 0, 0, 1 }, { 0, 0, 0 } }; // Function call checkConnected(graph, n);}} // This code is contributed by 29AjayKumar",
"e": 38905,
"s": 35931,
"text": null
},
{
"code": "<script>// Javascript implementation of the above approach let V = 3; // Function to find the characteristic// of the given graphfunction checkConnected(graph, n){ // Check whether the graph is // strongly connected or not let strongly = true; // Traverse the path matrix for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // If all the elements are // not equal then the graph // is not strongly connected if (graph[i][j] != graph[j][i]) { strongly = false; break; } } // Break out of the loop if false if (!strongly) { break; } } // If true then print strongly // connected and return if (strongly) { document.write(\"Strongly Connected\"); return 0; } // Check whether the graph is // Unilaterally connected by // checking Upper Triangle element let uppertri = true; // Traverse the path matrix for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // If uppertriangle elements // are 0 then break out of the // loop and check the elements // of lowertriangle matrix if (i > j && graph[i][j] == 0) { uppertri = false; break; } } // Break out of the loop if false if (!uppertri) { break; } } // If true then print unilaterally // connected and return if (uppertri) { document.write(\"Unilaterally Connected\"); return 0; } // Check lowertraingle elements let lowertri = true; // Traverse the path matrix for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // If lowertraingle elements // are 0 then break cause // 1's are expected if (i < j && graph[i][j] == 0) { lowertri = false; break; } } // Break out of the loop if false if (!lowertri) { break; } } // If true then print unilaterally // connected and return if (lowertri) { document.write(\"Unilaterally Connected\"); return 0; } // If elements are in random order // unsynchronized then print weakly // connected and return else { document.write(\"Weakly Connected\"); } return 0;} // Driver Code // Number of nodes let n = 3; // Given Path Matrix let graph = [[ 0, 1, 1 ], [ 0, 0, 1 ], [ 0, 0, 0 ]]; // Function call checkConnected(graph, n); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 41809,
"s": 38905,
"text": null
},
{
"code": null,
"e": 41832,
"s": 41809,
"text": "Unilaterally Connected"
},
{
"code": null,
"e": 41879,
"s": 41834,
"text": "Time Complexity: O(N2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 41891,
"s": 41879,
"text": "29AjayKumar"
},
{
"code": null,
"e": 41904,
"s": 41891,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 41914,
"s": 41904,
"text": "rutvik_56"
},
{
"code": null,
"e": 41936,
"s": 41914,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 41949,
"s": 41936,
"text": "ankita_saini"
},
{
"code": null,
"e": 41960,
"s": 41949,
"text": "Algorithms"
},
{
"code": null,
"e": 41967,
"s": 41960,
"text": "Arrays"
},
{
"code": null,
"e": 41973,
"s": 41967,
"text": "Graph"
},
{
"code": null,
"e": 41986,
"s": 41973,
"text": "Mathematical"
},
{
"code": null,
"e": 41993,
"s": 41986,
"text": "Matrix"
},
{
"code": null,
"e": 42000,
"s": 41993,
"text": "Arrays"
},
{
"code": null,
"e": 42013,
"s": 42000,
"text": "Mathematical"
},
{
"code": null,
"e": 42020,
"s": 42013,
"text": "Matrix"
},
{
"code": null,
"e": 42026,
"s": 42020,
"text": "Graph"
},
{
"code": null,
"e": 42037,
"s": 42026,
"text": "Algorithms"
},
{
"code": null,
"e": 42135,
"s": 42037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42144,
"s": 42135,
"text": "Comments"
},
{
"code": null,
"e": 42157,
"s": 42144,
"text": "Old Comments"
},
{
"code": null,
"e": 42206,
"s": 42157,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 42231,
"s": 42206,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 42258,
"s": 42231,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 42286,
"s": 42258,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 42342,
"s": 42286,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 42357,
"s": 42342,
"text": "Arrays in Java"
},
{
"code": null,
"e": 42373,
"s": 42357,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 42400,
"s": 42373,
"text": "Program for array rotation"
},
{
"code": null,
"e": 42448,
"s": 42400,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Java lang Integer.toHexString() Method with Examples - GeeksforGeeks
|
05 Dec, 2018
The Java.lang.Integer.toHexString() is a built-in function in Java which returns a string representation of the integer argument as an unsigned integer in base 16. The function accepts a single parameter as an argument in Integer data-type.
Syntax :
public static String toHexString(int num)
Parameter : The function accepts a single mandatory parameter
num - This parameter specifies the number which is to be converted
to a Hexadecimal string. The data-type is int.
Return Value : The function returns a string representation of the int argument as an unsigned integer in base 16.
Examples:
Input : 11
Output : b
Input : 12
Output : c
Program 1: The program below demonstrates the working of function.
// Java program to demonstrate working// of java.lang.Integer.toHexString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { int l = 234; // returns the string representation of the unsigned int value // represented by the argument in binary (base 2) System.out.println("Hex string is " + Integer.toHexString(l)); l = 11; System.out.println("Hex string is " + Integer.toHexString(l)); }}
Output:
Hex string is ea
Hex string is b
Program 2: The program below demonstrates the working function when a negative number is passed.
// Java program to demonstrate// of java.lang.Integer.toHexString() method// negative number import java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when negative number is passed System.out.println("Hex is " + Integer.toHexString(-10)); }}
Output:
Hex is fffffff6
Errors and Exception: Whenever a decimal number or a string is passed as an argument, it returns an error message which says “incompatible types”.
Program 3: The program below demonstrates the working function when a string number is passed.
// Java program to demonstrate// of java.lang.Integer.toHexString() method// string number import java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when negative number is passed System.out.println("Hex is " + Integer.toHexString("12")); }}
Output:
prog.java:13: error: incompatible types: String cannot be converted to int
System.out.println("Hex is " + Integer.toHexString("12"));
Program 4: The program below demonstrates the working function when a decimal is passed.
// Java program to demonstrate// of java.lang.Integer.toHexString() method// decimal import java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when decimal number is passed System.out.println("Hex is " + Integer.toHexString(12.34)); }}
Output:
prog.java:13: error: incompatible types: possible lossy conversion from double to int
System.out.println("Hex is " + Integer.toHexString(12.34));
Java-Functions
Java-Integer
Java-lang package
java-math
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
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Multithreading in Java
LinkedList in Java
Collections in Java
Overriding in Java
|
[
{
"code": null,
"e": 24397,
"s": 24369,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 24638,
"s": 24397,
"text": "The Java.lang.Integer.toHexString() is a built-in function in Java which returns a string representation of the integer argument as an unsigned integer in base 16. The function accepts a single parameter as an argument in Integer data-type."
},
{
"code": null,
"e": 24647,
"s": 24638,
"text": "Syntax :"
},
{
"code": null,
"e": 24867,
"s": 24647,
"text": "public static String toHexString(int num)\n\nParameter : The function accepts a single mandatory parameter\nnum - This parameter specifies the number which is to be converted\nto a Hexadecimal string. The data-type is int. "
},
{
"code": null,
"e": 24982,
"s": 24867,
"text": "Return Value : The function returns a string representation of the int argument as an unsigned integer in base 16."
},
{
"code": null,
"e": 24992,
"s": 24982,
"text": "Examples:"
},
{
"code": null,
"e": 25038,
"s": 24992,
"text": "Input : 11\nOutput : b\n\nInput : 12\nOutput : c\n"
},
{
"code": null,
"e": 25105,
"s": 25038,
"text": "Program 1: The program below demonstrates the working of function."
},
{
"code": "// Java program to demonstrate working// of java.lang.Integer.toHexString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { int l = 234; // returns the string representation of the unsigned int value // represented by the argument in binary (base 2) System.out.println(\"Hex string is \" + Integer.toHexString(l)); l = 11; System.out.println(\"Hex string is \" + Integer.toHexString(l)); }}",
"e": 25605,
"s": 25105,
"text": null
},
{
"code": null,
"e": 25613,
"s": 25605,
"text": "Output:"
},
{
"code": null,
"e": 25647,
"s": 25613,
"text": "Hex string is ea\nHex string is b\n"
},
{
"code": null,
"e": 25744,
"s": 25647,
"text": "Program 2: The program below demonstrates the working function when a negative number is passed."
},
{
"code": "// Java program to demonstrate// of java.lang.Integer.toHexString() method// negative number import java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when negative number is passed System.out.println(\"Hex is \" + Integer.toHexString(-10)); }}",
"e": 26054,
"s": 25744,
"text": null
},
{
"code": null,
"e": 26062,
"s": 26054,
"text": "Output:"
},
{
"code": null,
"e": 26079,
"s": 26062,
"text": "Hex is fffffff6\n"
},
{
"code": null,
"e": 26226,
"s": 26079,
"text": "Errors and Exception: Whenever a decimal number or a string is passed as an argument, it returns an error message which says “incompatible types”."
},
{
"code": null,
"e": 26321,
"s": 26226,
"text": "Program 3: The program below demonstrates the working function when a string number is passed."
},
{
"code": "// Java program to demonstrate// of java.lang.Integer.toHexString() method// string number import java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when negative number is passed System.out.println(\"Hex is \" + Integer.toHexString(\"12\")); }}",
"e": 26630,
"s": 26321,
"text": null
},
{
"code": null,
"e": 26638,
"s": 26630,
"text": "Output:"
},
{
"code": null,
"e": 26777,
"s": 26638,
"text": "prog.java:13: error: incompatible types: String cannot be converted to int\n System.out.println(\"Hex is \" + Integer.toHexString(\"12\")); "
},
{
"code": null,
"e": 26866,
"s": 26777,
"text": "Program 4: The program below demonstrates the working function when a decimal is passed."
},
{
"code": "// Java program to demonstrate// of java.lang.Integer.toHexString() method// decimal import java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when decimal number is passed System.out.println(\"Hex is \" + Integer.toHexString(12.34)); }}",
"e": 27169,
"s": 26866,
"text": null
},
{
"code": null,
"e": 27177,
"s": 27169,
"text": "Output:"
},
{
"code": null,
"e": 27328,
"s": 27177,
"text": "prog.java:13: error: incompatible types: possible lossy conversion from double to int\n System.out.println(\"Hex is \" + Integer.toHexString(12.34)); "
},
{
"code": null,
"e": 27343,
"s": 27328,
"text": "Java-Functions"
},
{
"code": null,
"e": 27356,
"s": 27343,
"text": "Java-Integer"
},
{
"code": null,
"e": 27374,
"s": 27356,
"text": "Java-lang package"
},
{
"code": null,
"e": 27384,
"s": 27374,
"text": "java-math"
},
{
"code": null,
"e": 27389,
"s": 27384,
"text": "Java"
},
{
"code": null,
"e": 27394,
"s": 27389,
"text": "Java"
},
{
"code": null,
"e": 27492,
"s": 27394,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27501,
"s": 27492,
"text": "Comments"
},
{
"code": null,
"e": 27514,
"s": 27501,
"text": "Old Comments"
},
{
"code": null,
"e": 27546,
"s": 27514,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27565,
"s": 27546,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27583,
"s": 27565,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27615,
"s": 27583,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27639,
"s": 27615,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 27659,
"s": 27639,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27682,
"s": 27659,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 27701,
"s": 27682,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 27721,
"s": 27701,
"text": "Collections in Java"
}
] |
Build a Motion Heatmap Video Using OpenCV With Python | by Rob | Towards Data Science
|
1
2
3
4
5
6
7
8
9
10
Powered by Play.ht
Create audio with Play.ht
Create Audio Narrations with Play.ht
OpenCV, or (Open source computer vision) is a library developed by Intel in 1999 mainly aimed at computer vision, and real-time video operations, it is written in C++ but it is supported in different languages, among them Python.
This program is based on a technique known as gaussian background subtraction. This technique is widely used for detecting moving objects with a steady camera.
Background subtraction creates a mask representing the background of a frame (the static part of an image) and for each frame, it subtracts the previous one.
Let’s have a gentle overview of the main two steps on how this algorithm works:
Background Initialization: In this first step, a model of the background is calculated by freezing the first frame.
Update: In this second step the next frame is being subtracted from the previous, hence, if a change (a movement) happened between the two frames, the difference of the frames will reflect the change which can be market by applying a filter.
The following is an example of the background mask applied to a short video recorded from a city camera:
For the whole project repository please check here.
The code starts by reading the input video file and by initialising some variables needed:
capture = cv2.VideoCapture('input.mp4')background_subtractor = cv2.bgsegm.createBackgroundSubtractorMOG()length = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
Then, the for loop iterating over frames begins:
for i in range(0, length): ret, frame = capture.read() # If first frame if first_iteration_indicator == 1: first_frame = copy.deepcopy(frame) height, width = frame.shape[:2] accum_image = np.zeros((height, width), np.uint8)
The first if block checks whether the frame is the first frame of the video, this is done in order to initialize our background for the background subtraction, then the accum_image array is being initialised with a size corresponding to the size of the frame.
filter = background_subtractor.apply(frame) # remove the backgroundthreshold = 2maxValue = 2ret, th1 = cv2.threshold(filter, threshold, maxValue, cv2.THRESH_BINARY)accum_image = cv2.add(accum_image, th1)color_image_video = cv2.applyColorMap(accum_image, cv2.COLORMAP_HOT)
To remove small amounts of movements, such as the wind, a small bird flying, or some noyse a threshold is applied to the mask together with maxValue .
The result of the mask is then added to the accum_image array , this operation is performed for each frame. The result consists of the accum_image array to store every movement that happened in the video.
Furthermore, at the very end, hence, when the previously described operations have been done for each frame, a colourmap is applied to the mask and the mask merged with the current frame.
To go further, it is possible to make a video showing the heatmap fading in frame by frame. To achieve this, each frame is being exported and again, using cv2 , the video is generated by merging together all the frames:
video = cv2.VideoWriter('output.avi', fourcc, 30.0, (width, height))for image in images: video.write(cv2.imread(os.path.join(image_folder, image)))cv2.destroyAllWindows()
The final result:
This story is inspired by Intel’s GitHub repository which proposed this use of OpenCV back in 2018.
|
[
{
"code": null,
"e": 174,
"s": 172,
"text": "1"
},
{
"code": null,
"e": 176,
"s": 174,
"text": "2"
},
{
"code": null,
"e": 178,
"s": 176,
"text": "3"
},
{
"code": null,
"e": 180,
"s": 178,
"text": "4"
},
{
"code": null,
"e": 182,
"s": 180,
"text": "5"
},
{
"code": null,
"e": 184,
"s": 182,
"text": "6"
},
{
"code": null,
"e": 186,
"s": 184,
"text": "7"
},
{
"code": null,
"e": 188,
"s": 186,
"text": "8"
},
{
"code": null,
"e": 190,
"s": 188,
"text": "9"
},
{
"code": null,
"e": 193,
"s": 190,
"text": "10"
},
{
"code": null,
"e": 212,
"s": 193,
"text": "Powered by Play.ht"
},
{
"code": null,
"e": 238,
"s": 212,
"text": "Create audio with Play.ht"
},
{
"code": null,
"e": 275,
"s": 238,
"text": "Create Audio Narrations with Play.ht"
},
{
"code": null,
"e": 505,
"s": 275,
"text": "OpenCV, or (Open source computer vision) is a library developed by Intel in 1999 mainly aimed at computer vision, and real-time video operations, it is written in C++ but it is supported in different languages, among them Python."
},
{
"code": null,
"e": 665,
"s": 505,
"text": "This program is based on a technique known as gaussian background subtraction. This technique is widely used for detecting moving objects with a steady camera."
},
{
"code": null,
"e": 823,
"s": 665,
"text": "Background subtraction creates a mask representing the background of a frame (the static part of an image) and for each frame, it subtracts the previous one."
},
{
"code": null,
"e": 903,
"s": 823,
"text": "Let’s have a gentle overview of the main two steps on how this algorithm works:"
},
{
"code": null,
"e": 1019,
"s": 903,
"text": "Background Initialization: In this first step, a model of the background is calculated by freezing the first frame."
},
{
"code": null,
"e": 1261,
"s": 1019,
"text": "Update: In this second step the next frame is being subtracted from the previous, hence, if a change (a movement) happened between the two frames, the difference of the frames will reflect the change which can be market by applying a filter."
},
{
"code": null,
"e": 1366,
"s": 1261,
"text": "The following is an example of the background mask applied to a short video recorded from a city camera:"
},
{
"code": null,
"e": 1418,
"s": 1366,
"text": "For the whole project repository please check here."
},
{
"code": null,
"e": 1509,
"s": 1418,
"text": "The code starts by reading the input video file and by initialising some variables needed:"
},
{
"code": null,
"e": 1666,
"s": 1509,
"text": "capture = cv2.VideoCapture('input.mp4')background_subtractor = cv2.bgsegm.createBackgroundSubtractorMOG()length = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))"
},
{
"code": null,
"e": 1715,
"s": 1666,
"text": "Then, the for loop iterating over frames begins:"
},
{
"code": null,
"e": 1969,
"s": 1715,
"text": "for i in range(0, length): ret, frame = capture.read() # If first frame if first_iteration_indicator == 1: first_frame = copy.deepcopy(frame) height, width = frame.shape[:2] accum_image = np.zeros((height, width), np.uint8)"
},
{
"code": null,
"e": 2229,
"s": 1969,
"text": "The first if block checks whether the frame is the first frame of the video, this is done in order to initialize our background for the background subtraction, then the accum_image array is being initialised with a size corresponding to the size of the frame."
},
{
"code": null,
"e": 2502,
"s": 2229,
"text": "filter = background_subtractor.apply(frame) # remove the backgroundthreshold = 2maxValue = 2ret, th1 = cv2.threshold(filter, threshold, maxValue, cv2.THRESH_BINARY)accum_image = cv2.add(accum_image, th1)color_image_video = cv2.applyColorMap(accum_image, cv2.COLORMAP_HOT)"
},
{
"code": null,
"e": 2653,
"s": 2502,
"text": "To remove small amounts of movements, such as the wind, a small bird flying, or some noyse a threshold is applied to the mask together with maxValue ."
},
{
"code": null,
"e": 2858,
"s": 2653,
"text": "The result of the mask is then added to the accum_image array , this operation is performed for each frame. The result consists of the accum_image array to store every movement that happened in the video."
},
{
"code": null,
"e": 3046,
"s": 2858,
"text": "Furthermore, at the very end, hence, when the previously described operations have been done for each frame, a colourmap is applied to the mask and the mask merged with the current frame."
},
{
"code": null,
"e": 3266,
"s": 3046,
"text": "To go further, it is possible to make a video showing the heatmap fading in frame by frame. To achieve this, each frame is being exported and again, using cv2 , the video is generated by merging together all the frames:"
},
{
"code": null,
"e": 3440,
"s": 3266,
"text": "video = cv2.VideoWriter('output.avi', fourcc, 30.0, (width, height))for image in images: video.write(cv2.imread(os.path.join(image_folder, image)))cv2.destroyAllWindows()"
},
{
"code": null,
"e": 3458,
"s": 3440,
"text": "The final result:"
}
] |
How to read a text file with C++?
|
This is a C++ program to read a text file.
tpoint.txt is having initial content as
“Tutorials point.”
Tutorials point.
Begin
Create an object newfile against the class fstream.
Call open() method to open a file “tpoint.txt” to perform write operation using object newfile.
If file is open then
Input a string “Tutorials point" in the tpoint.txt file.
Close the file object newfile using close() method.
Call open() method to open a file “tpoint.txt” to perform read operation using object newfile.
If file is open then
Declare a string “tp”.
Read all data of file object newfile using getline() method and put it into the string tp.
Print the data of string tp.
Close the file object newfile using close() method.
End.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream newfile;
newfile.open("tpoint.txt",ios::out); // open a file to perform write operation using file object
if(newfile.is_open()) //checking whether the file is open {
newfile<<"Tutorials point \n"; //inserting text
newfile.close(); //close the file object
}
newfile.open("tpoint.txt",ios::in); //open a file to perform read operation using file object
if (newfile.is_open()){ //checking whether the file is open
string tp;
while(getline(newfile, tp)){ //read data from file object and put it into string.
cout << tp << "\n"; //print the data of the string
}
newfile.close(); //close the file object.
}
}
Tutorials point
|
[
{
"code": null,
"e": 1105,
"s": 1062,
"text": "This is a C++ program to read a text file."
},
{
"code": null,
"e": 1164,
"s": 1105,
"text": "tpoint.txt is having initial content as\n“Tutorials point.”"
},
{
"code": null,
"e": 1181,
"s": 1164,
"text": "Tutorials point."
},
{
"code": null,
"e": 1829,
"s": 1181,
"text": "Begin\n Create an object newfile against the class fstream.\n Call open() method to open a file “tpoint.txt” to perform write operation using object newfile.\n If file is open then\n Input a string “Tutorials point\" in the tpoint.txt file.\n Close the file object newfile using close() method.\n Call open() method to open a file “tpoint.txt” to perform read operation using object newfile.\n If file is open then\n Declare a string “tp”.\n Read all data of file object newfile using getline() method and put it into the string tp.\n Print the data of string tp.\n Close the file object newfile using close() method.\nEnd."
},
{
"code": null,
"e": 2597,
"s": 1829,
"text": "#include <iostream>\n#include <fstream>\n#include <string>\nusing namespace std;\nint main(){\n fstream newfile;\n newfile.open(\"tpoint.txt\",ios::out); // open a file to perform write operation using file object\n if(newfile.is_open()) //checking whether the file is open {\n newfile<<\"Tutorials point \\n\"; //inserting text\n newfile.close(); //close the file object\n }\n newfile.open(\"tpoint.txt\",ios::in); //open a file to perform read operation using file object\n if (newfile.is_open()){ //checking whether the file is open\n string tp;\n while(getline(newfile, tp)){ //read data from file object and put it into string.\n cout << tp << \"\\n\"; //print the data of the string\n }\n newfile.close(); //close the file object.\n }\n}"
},
{
"code": null,
"e": 2613,
"s": 2597,
"text": "Tutorials point"
}
] |
Intellij Idea - Code Refactoring
|
In this chapter, we will learn about Code Refactoring and how it works in IntelliJ. Code refactoring is restructuring of code without changing its functionality and usability. Code refactoring can be done to improve code readability, performance or to remove unused/duplicate functionality. IntelliJ provides great support for code refactoring. This chapter discusses various code refactoring actions.
Rename actions can be used to rename methods, its parameters, class attributes, local variables and so on. Let us create the following class in IntelliJ.
public class Employee {
private String name;
private String address;
private int age;
public Employee() {
this("Jarvis", "Palo Alto", 35);
}
public Employee(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
public static void main(String args[]) {
Employee e = new Employee();
System.out.println(e);
}
}
Now, let us rename Employee class to Person. This action will do modifications in constructors and the main() method −
Select Employee word
Select Employee word
Go to Refactor → Rename and rename it with Person.
Go to Refactor → Rename and rename it with Person.
This is one of the powerful refactoring actions. IntelliJ identifies code duplicates and
replaces it with appropriate code. Let us introduce code duplication and refactor it. Type
the following code in the Editor −
public class Employee {
private String name;
private String address;
private int age;
public Employee() {
this("Jarvis", "Palo Alto", 35);
}
public Employee(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public void setData(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public void showEmployeeDetail() {
System.out.println("Name = " + name + ", Address = " + address + ", Age = " + age);
}
public static void main(String args[]) {
Employee e = new Employee();
e.showEmployeeDetail();
}
}
In this example, Employee(String name, String address, int age) constructor and public void setData(String name, String address, int age) method are exactly identical. After refactoring, the Employee(String name, String address, int age) constructor gets modified as follows −
public Employee(String name, String address, int age) {
setData(name, address, age);
}
To replace the duplicates −
Go to Refactor → Find and Replace Code Duplicates.
Go to Refactor → Find and Replace Code Duplicates.
Select refactor scope and follow on-screen steps to complete action.
Select refactor scope and follow on-screen steps to complete action.
In this section, we will understand how to copy one class to another. Let us copy Employee
class to Person class. We can copy it to the existing module or a new one. IntelliJ will do
the required changes depending on it. Follow these steps to perform copy refactoring −
Go to Refactor → Copy, it will open the dialog box.
Go to Refactor → Copy, it will open the dialog box.
Enter new name and destination package.
Enter new name and destination package.
Click on the OK button and it will do the needful.
Click on the OK button and it will do the needful.
Move refactoring is similar to copy but instead of making another copy it moves the code to a different package or make it as inner class of another class.
Follow these steps to perform move refactoring −
Go to, Refactor → Move.
Go to, Refactor → Move.
A new window will appear.
A new window will appear.
Select one of the options according to your choice and click on Refactor.
Select one of the options according to your choice and click on Refactor.
The Safe Delete action will delete object only when it is not referenced anywhere in the
project. The target for this option can be class, interface, method, field or parameter.
Let us see this in action. Type the following code in Editor −
public class HelloWorld {
static void sayHello() {
System.out.println("Hello, World !!!");
}
public static void main(String[] args) {
sayHello();
}
}
Follow these steps to perform the safe delete action −
Select the sayHello() method.
Select the sayHello() method.
Right-click on it and select the Refactor → Safe Delete option.
Right-click on it and select the Refactor → Safe Delete option.
As the sayHello() method is being used it will show an error as in the following
screenshot −
As the sayHello() method is being used it will show an error as in the following
screenshot −
The action modifies method signature. It can change the method name, its parameters,
types, return values and so on. Let us take a method from the above example and change
its signature.
Follow these steps to perform the Change Signature action −
Select method.
Select method.
Right-click on it and select the Refactor → Change signature action
Right-click on it and select the Refactor → Change signature action
A new window will appear wherein you can perform the above actions.
A new window will appear wherein you can perform the above actions.
At the bottom of the window, it shows the preview of new signature.
At the bottom of the window, it shows the preview of new signature.
The Type Migration changes the type of the symbol. This symbol can be a method parameter or class attribute. Let us consider the following method before performing the required action −
static void sayHello(String name) {
System.out.println(name);
}
Follow these steps to perform type migration −
Select the “String” data type.
Select the “String” data type.
Right-click on it and select Refactor → Type migration.
Right-click on it and select Refactor → Type migration.
Enter the required data type in the given text box.
Enter the required data type in the given text box.
Choose scope and click on the Refactor button.
Choose scope and click on the Refactor button.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2491,
"s": 2089,
"text": "In this chapter, we will learn about Code Refactoring and how it works in IntelliJ. Code refactoring is restructuring of code without changing its functionality and usability. Code refactoring can be done to improve code readability, performance or to remove unused/duplicate functionality. IntelliJ provides great support for code refactoring. This chapter discusses various code refactoring actions."
},
{
"code": null,
"e": 2645,
"s": 2491,
"text": "Rename actions can be used to rename methods, its parameters, class attributes, local variables and so on. Let us create the following class in IntelliJ."
},
{
"code": null,
"e": 3611,
"s": 2645,
"text": "public class Employee {\n private String name;\n private String address;\n private int age;\n public Employee() {\n this(\"Jarvis\", \"Palo Alto\", 35);\n }\n public Employee(String name, String address, int age) {\n this.name = name;\n this.address = address;\n this.age = age;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n \n @Override\n public String toString() {\n return \"Employee{\" +\n \"name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n \", age=\" + age +\n '}';\n }\n public static void main(String args[]) {\n Employee e = new Employee();\n System.out.println(e);\n }\n}"
},
{
"code": null,
"e": 3730,
"s": 3611,
"text": "Now, let us rename Employee class to Person. This action will do modifications in constructors and the main() method −"
},
{
"code": null,
"e": 3751,
"s": 3730,
"text": "Select Employee word"
},
{
"code": null,
"e": 3772,
"s": 3751,
"text": "Select Employee word"
},
{
"code": null,
"e": 3823,
"s": 3772,
"text": "Go to Refactor → Rename and rename it with Person."
},
{
"code": null,
"e": 3874,
"s": 3823,
"text": "Go to Refactor → Rename and rename it with Person."
},
{
"code": null,
"e": 4089,
"s": 3874,
"text": "This is one of the powerful refactoring actions. IntelliJ identifies code duplicates and\nreplaces it with appropriate code. Let us introduce code duplication and refactor it. Type\nthe following code in the Editor −"
},
{
"code": null,
"e": 4786,
"s": 4089,
"text": "public class Employee {\n private String name;\n private String address;\n private int age;\n public Employee() {\n this(\"Jarvis\", \"Palo Alto\", 35);\n }\n public Employee(String name, String address, int age) {\n this.name = name;\n this.address = address;\n this.age = age;\n }\n public void setData(String name, String address, int age) {\n this.name = name;\n this.address = address;\n this.age = age;\n }\n public void showEmployeeDetail() {\n System.out.println(\"Name = \" + name + \", Address = \" + address + \", Age = \" + age);\n }\n public static void main(String args[]) {\n Employee e = new Employee();\n e.showEmployeeDetail();\n }\n} "
},
{
"code": null,
"e": 5063,
"s": 4786,
"text": "In this example, Employee(String name, String address, int age) constructor and public void setData(String name, String address, int age) method are exactly identical. After refactoring, the Employee(String name, String address, int age) constructor gets modified as follows −"
},
{
"code": null,
"e": 5153,
"s": 5063,
"text": "public Employee(String name, String address, int age) {\n setData(name, address, age);\n}"
},
{
"code": null,
"e": 5181,
"s": 5153,
"text": "To replace the duplicates −"
},
{
"code": null,
"e": 5232,
"s": 5181,
"text": "Go to Refactor → Find and Replace Code Duplicates."
},
{
"code": null,
"e": 5283,
"s": 5232,
"text": "Go to Refactor → Find and Replace Code Duplicates."
},
{
"code": null,
"e": 5352,
"s": 5283,
"text": "Select refactor scope and follow on-screen steps to complete action."
},
{
"code": null,
"e": 5421,
"s": 5352,
"text": "Select refactor scope and follow on-screen steps to complete action."
},
{
"code": null,
"e": 5691,
"s": 5421,
"text": "In this section, we will understand how to copy one class to another. Let us copy Employee\nclass to Person class. We can copy it to the existing module or a new one. IntelliJ will do\nthe required changes depending on it. Follow these steps to perform copy refactoring −"
},
{
"code": null,
"e": 5743,
"s": 5691,
"text": "Go to Refactor → Copy, it will open the dialog box."
},
{
"code": null,
"e": 5795,
"s": 5743,
"text": "Go to Refactor → Copy, it will open the dialog box."
},
{
"code": null,
"e": 5835,
"s": 5795,
"text": "Enter new name and destination package."
},
{
"code": null,
"e": 5875,
"s": 5835,
"text": "Enter new name and destination package."
},
{
"code": null,
"e": 5926,
"s": 5875,
"text": "Click on the OK button and it will do the needful."
},
{
"code": null,
"e": 5977,
"s": 5926,
"text": "Click on the OK button and it will do the needful."
},
{
"code": null,
"e": 6133,
"s": 5977,
"text": "Move refactoring is similar to copy but instead of making another copy it moves the code to a different package or make it as inner class of another class."
},
{
"code": null,
"e": 6182,
"s": 6133,
"text": "Follow these steps to perform move refactoring −"
},
{
"code": null,
"e": 6206,
"s": 6182,
"text": "Go to, Refactor → Move."
},
{
"code": null,
"e": 6230,
"s": 6206,
"text": "Go to, Refactor → Move."
},
{
"code": null,
"e": 6256,
"s": 6230,
"text": "A new window will appear."
},
{
"code": null,
"e": 6282,
"s": 6256,
"text": "A new window will appear."
},
{
"code": null,
"e": 6356,
"s": 6282,
"text": "Select one of the options according to your choice and click on Refactor."
},
{
"code": null,
"e": 6430,
"s": 6356,
"text": "Select one of the options according to your choice and click on Refactor."
},
{
"code": null,
"e": 6608,
"s": 6430,
"text": "The Safe Delete action will delete object only when it is not referenced anywhere in the\nproject. The target for this option can be class, interface, method, field or parameter."
},
{
"code": null,
"e": 6671,
"s": 6608,
"text": "Let us see this in action. Type the following code in Editor −"
},
{
"code": null,
"e": 6845,
"s": 6671,
"text": "public class HelloWorld {\n static void sayHello() {\n System.out.println(\"Hello, World !!!\");\n }\n public static void main(String[] args) {\n sayHello();\n }\n}"
},
{
"code": null,
"e": 6900,
"s": 6845,
"text": "Follow these steps to perform the safe delete action −"
},
{
"code": null,
"e": 6930,
"s": 6900,
"text": "Select the sayHello() method."
},
{
"code": null,
"e": 6960,
"s": 6930,
"text": "Select the sayHello() method."
},
{
"code": null,
"e": 7024,
"s": 6960,
"text": "Right-click on it and select the Refactor → Safe Delete option."
},
{
"code": null,
"e": 7088,
"s": 7024,
"text": "Right-click on it and select the Refactor → Safe Delete option."
},
{
"code": null,
"e": 7182,
"s": 7088,
"text": "As the sayHello() method is being used it will show an error as in the following\nscreenshot −"
},
{
"code": null,
"e": 7276,
"s": 7182,
"text": "As the sayHello() method is being used it will show an error as in the following\nscreenshot −"
},
{
"code": null,
"e": 7463,
"s": 7276,
"text": "The action modifies method signature. It can change the method name, its parameters,\ntypes, return values and so on. Let us take a method from the above example and change\nits signature."
},
{
"code": null,
"e": 7523,
"s": 7463,
"text": "Follow these steps to perform the Change Signature action −"
},
{
"code": null,
"e": 7538,
"s": 7523,
"text": "Select method."
},
{
"code": null,
"e": 7553,
"s": 7538,
"text": "Select method."
},
{
"code": null,
"e": 7621,
"s": 7553,
"text": "Right-click on it and select the Refactor → Change signature action"
},
{
"code": null,
"e": 7689,
"s": 7621,
"text": "Right-click on it and select the Refactor → Change signature action"
},
{
"code": null,
"e": 7757,
"s": 7689,
"text": "A new window will appear wherein you can perform the above actions."
},
{
"code": null,
"e": 7825,
"s": 7757,
"text": "A new window will appear wherein you can perform the above actions."
},
{
"code": null,
"e": 7893,
"s": 7825,
"text": "At the bottom of the window, it shows the preview of new signature."
},
{
"code": null,
"e": 7961,
"s": 7893,
"text": "At the bottom of the window, it shows the preview of new signature."
},
{
"code": null,
"e": 8147,
"s": 7961,
"text": "The Type Migration changes the type of the symbol. This symbol can be a method parameter or class attribute. Let us consider the following method before performing the required action −"
},
{
"code": null,
"e": 8214,
"s": 8147,
"text": "static void sayHello(String name) {\n System.out.println(name);\n}"
},
{
"code": null,
"e": 8261,
"s": 8214,
"text": "Follow these steps to perform type migration −"
},
{
"code": null,
"e": 8292,
"s": 8261,
"text": "Select the “String” data type."
},
{
"code": null,
"e": 8323,
"s": 8292,
"text": "Select the “String” data type."
},
{
"code": null,
"e": 8379,
"s": 8323,
"text": "Right-click on it and select Refactor → Type migration."
},
{
"code": null,
"e": 8435,
"s": 8379,
"text": "Right-click on it and select Refactor → Type migration."
},
{
"code": null,
"e": 8487,
"s": 8435,
"text": "Enter the required data type in the given text box."
},
{
"code": null,
"e": 8539,
"s": 8487,
"text": "Enter the required data type in the given text box."
},
{
"code": null,
"e": 8586,
"s": 8539,
"text": "Choose scope and click on the Refactor button."
},
{
"code": null,
"e": 8633,
"s": 8586,
"text": "Choose scope and click on the Refactor button."
},
{
"code": null,
"e": 8640,
"s": 8633,
"text": " Print"
},
{
"code": null,
"e": 8651,
"s": 8640,
"text": " Add Notes"
}
] |
CSS font-variant-ligatures Property - GeeksforGeeks
|
18 Sep, 2020
The CSS font-variant-ligatures property is used for controlling ligatures on a text’s font. A ligature is a special character that combines two or more characters into one. Ligatures are commonly used to give certain style or look to the text.
Syntax:
font-variant-ligatures: Keyword_values
Or
font-variant-ligatures: Global_values
Property values: This property accepts property values mentioned above and described below.
Keyword_values: This property value refers to the values defined by “normal”, “none”, “common-ligatures”, “no-common-ligatures”, “discretionary-ligatures”, “no-discretionary-ligatures”, “historical-ligatures”, “no-historical-ligatures”, “contextual”, “no-contextual”.
Global_values: This property value refers to the values defined by “inherit”, “initial”, “unset”.
Example 1: Below is the example that illustrates the use of font-variant-ligatures property using common-ligatures and no-common-ligatures.
HTML
<!DOCTYPE html><html lang="en"> <head> <style> div { font-size: 5vw; } .off { font-variant-ligatures: no-common-ligatures; color: rgb(83, 241, 21); } .on { font-variant-ligatures: common-ligatures; color: rgb(96, 153, 4); } </style></head> <body> <h1 style="color: green;">GeeksforGeeks</h1> <div> <span class="off">wifi</span> <span class="on">wifi</span> </div></body> </html>
Output:
Supported Browsers:
Chrome
Firefox
Safari
Opera
Edge
Internet Explorer (Not Supported).
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24600,
"s": 24572,
"text": "\n18 Sep, 2020"
},
{
"code": null,
"e": 24844,
"s": 24600,
"text": "The CSS font-variant-ligatures property is used for controlling ligatures on a text’s font. A ligature is a special character that combines two or more characters into one. Ligatures are commonly used to give certain style or look to the text."
},
{
"code": null,
"e": 24852,
"s": 24844,
"text": "Syntax:"
},
{
"code": null,
"e": 24891,
"s": 24852,
"text": "font-variant-ligatures: Keyword_values"
},
{
"code": null,
"e": 24894,
"s": 24891,
"text": "Or"
},
{
"code": null,
"e": 24934,
"s": 24894,
"text": " font-variant-ligatures: Global_values "
},
{
"code": null,
"e": 25026,
"s": 24934,
"text": "Property values: This property accepts property values mentioned above and described below."
},
{
"code": null,
"e": 25294,
"s": 25026,
"text": "Keyword_values: This property value refers to the values defined by “normal”, “none”, “common-ligatures”, “no-common-ligatures”, “discretionary-ligatures”, “no-discretionary-ligatures”, “historical-ligatures”, “no-historical-ligatures”, “contextual”, “no-contextual”."
},
{
"code": null,
"e": 25392,
"s": 25294,
"text": "Global_values: This property value refers to the values defined by “inherit”, “initial”, “unset”."
},
{
"code": null,
"e": 25532,
"s": 25392,
"text": "Example 1: Below is the example that illustrates the use of font-variant-ligatures property using common-ligatures and no-common-ligatures."
},
{
"code": null,
"e": 25537,
"s": 25532,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> div { font-size: 5vw; } .off { font-variant-ligatures: no-common-ligatures; color: rgb(83, 241, 21); } .on { font-variant-ligatures: common-ligatures; color: rgb(96, 153, 4); } </style></head> <body> <h1 style=\"color: green;\">GeeksforGeeks</h1> <div> <span class=\"off\">wifi</span> <span class=\"on\">wifi</span> </div></body> </html>",
"e": 26049,
"s": 25537,
"text": null
},
{
"code": null,
"e": 26057,
"s": 26049,
"text": "Output:"
},
{
"code": null,
"e": 26077,
"s": 26057,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 26084,
"s": 26077,
"text": "Chrome"
},
{
"code": null,
"e": 26092,
"s": 26084,
"text": "Firefox"
},
{
"code": null,
"e": 26099,
"s": 26092,
"text": "Safari"
},
{
"code": null,
"e": 26105,
"s": 26099,
"text": "Opera"
},
{
"code": null,
"e": 26110,
"s": 26105,
"text": "Edge"
},
{
"code": null,
"e": 26145,
"s": 26110,
"text": "Internet Explorer (Not Supported)."
},
{
"code": null,
"e": 26160,
"s": 26145,
"text": "CSS-Properties"
},
{
"code": null,
"e": 26164,
"s": 26160,
"text": "CSS"
},
{
"code": null,
"e": 26181,
"s": 26164,
"text": "Web Technologies"
},
{
"code": null,
"e": 26279,
"s": 26181,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26288,
"s": 26279,
"text": "Comments"
},
{
"code": null,
"e": 26301,
"s": 26288,
"text": "Old Comments"
},
{
"code": null,
"e": 26359,
"s": 26301,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26396,
"s": 26359,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26460,
"s": 26396,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 26501,
"s": 26460,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 26538,
"s": 26501,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26580,
"s": 26538,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26623,
"s": 26580,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26668,
"s": 26623,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26737,
"s": 26668,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
GraphQL - Mutation
|
In this chapter, we will learn mutation queries in GraphQL.
Mutation queries modify data in the data store and returns a value. It can be used to insert, update, or delete data. Mutations are defined as a part of the schema.
The syntax of a mutation query is given below −
mutation{
someEditOperation(dataField:"valueOfField"):returnType
}
Let us understand how to add new student record into the datastore using a mutation query.
Create a project folder by the name mutation-app. Change your directory to mutation-app from the terminal. Follow steps 3 to 5 explained in the Environment Setup chapter.
Add schema.graphql file in the project folder mutation-app and add the following code −
type Query {
greeting:String
}
type Mutation {
createStudent(collegeId:ID,firstName:String,lastName:String):String
}
Note that the function createStudent returns a String type. This is a unique identifier (ID) which is generated after creating a student.
Create a file resolvers.js in the project folder and add the following code −
const db = require('./db')
const Mutation = {
createStudent:(root,args,context,info) => {
return db.students.create({collegeId:args.collegeId,
firstName:args.firstName,
lastName:args.lastName})
}
}
const Query = {
greeting:() => "hello"
}
module.exports = {Query,Mutation}
The mutation function points to students collection in the datastore. To add a new student, invoke the create method in students collection. The args object will contain the parameters which are passed in the query. The create method of students collection will return the id of a newly created student object.
Create a server.js file. Refer to step 8 in the Environment Setup Chapter. Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application.
Next step is to open browser and type the URL http://localhost:9000/graphiql. Type the following query in the editor −
//college Id should be matched with data from colleges.json for easy retrieval
mutation {
createStudent(collegeId:"col-2",firstName:"Tim",lastName:"George")
}
The above query will create a student object in student.json file. The query will return a unique identifier. The response of the query is as shown below −
{
"data": {
"createStudent": "SkQtxYBUm"
}
}
To verify if the student object is created, we can use the studentById query. You can also open the students.json file from data folder to verify the id.
To use studentById query, edit the schema.graphql as given below −
type Query {
studentById(id:ID!):Student
}
type Student {
id:ID!
firstName:String
lastName:String
collegeId:String
}
Edit the resolver.js file as given below −
const db = require('./db')
const Query = {
studentById:(root,args,context,info) => {
return db.students.get(args.id);
}
}
const Mutation = {
createStudent:(root,args,context,info) => {
return db.students.create({collegeId:args.collegeId,
firstName:args.firstName,
lastName:args.lastName})
}
}
module.exports = {Query,Mutation}
Given below is the query to get student by unique id returned from the mutation query −
{
studentById(id:"SkQtxYBUm") {
id
firstName
lastName
}
}
The response from the server is as follows −
{
"data": {
"studentById": {
"id": "SkQtxYBUm",
"firstName": "Tim",
"lastName":"George"
}
}
}
It is best practice to return an object in mutation. For example, the client application wants to fetch student and college details. In this case, rather than making two different requests, we can create a query that returns an object containing students and their college details.
Add a new method named addStudent which returns object in mutation type of schema.graphql.
Let us learn how to access the college details through student details. Add college type in the schema file.
type Mutation {
addStudent_returns_object(collegeId:ID,firstName:String,lastName:String):Student
createStudent(collegeId:ID,firstName:String,lastName:String):String
}
type College {
id:ID!
name:String
location:String
rating:Float
}
type Student {
id:ID!
firstName:String
lastName:String
college:College
}
Update a file resolvers.js in the project folder and add the following code −
const Mutation = {
createStudent:(root,args,context,info) => {
return db.students.create({
collegeId:args.collegeId,
firstName:args.firstName,
lastName:args.lastName
})
},
// new resolver function
addStudent_returns_object:(root,args,context,info) => {
const id = db.students.create({
collegeId:args.collegeId,
firstName:args.firstName,
lastName:args.lastName
})
return db.students.get(id)
}
}
//for each single student object returned,resolver is invoked
const Student = {
college:(root) => {
return db.colleges.get(root.collegeId);
}
}
module.exports = {Query,Student,Mutation}
Next, we shall start the server and request query in GraphiQL with the following code −
mutation {
addStudent_returns_object(collegeId:"col-101",firstName:"Susan",lastName:"George") {
id
firstName
college{
id
name
}
}
}
The above query adds a new student and retrieves the student object along with college object. This saves round trips to the server.
The response is as given below −
{
"data": {
"addStudent_returns_object": {
"id": "rklUl08IX",
"firstName": "Susan",
"college": {
"id": "col-101",
"name": "AMU"
}
}
}
}
43 Lectures
3 hours
Nilay Mehta
53 Lectures
3 hours
Asfend Yar
17 Lectures
2 hours
Mohd Raqif Warsi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2011,
"s": 1951,
"text": "In this chapter, we will learn mutation queries in GraphQL."
},
{
"code": null,
"e": 2176,
"s": 2011,
"text": "Mutation queries modify data in the data store and returns a value. It can be used to insert, update, or delete data. Mutations are defined as a part of the schema."
},
{
"code": null,
"e": 2224,
"s": 2176,
"text": "The syntax of a mutation query is given below −"
},
{
"code": null,
"e": 2295,
"s": 2224,
"text": "mutation{\n someEditOperation(dataField:\"valueOfField\"):returnType\n}\n"
},
{
"code": null,
"e": 2386,
"s": 2295,
"text": "Let us understand how to add new student record into the datastore using a mutation query."
},
{
"code": null,
"e": 2557,
"s": 2386,
"text": "Create a project folder by the name mutation-app. Change your directory to mutation-app from the terminal. Follow steps 3 to 5 explained in the Environment Setup chapter."
},
{
"code": null,
"e": 2645,
"s": 2557,
"text": "Add schema.graphql file in the project folder mutation-app and add the following code −"
},
{
"code": null,
"e": 2769,
"s": 2645,
"text": "type Query {\n greeting:String\n}\n\ntype Mutation {\n createStudent(collegeId:ID,firstName:String,lastName:String):String\n}"
},
{
"code": null,
"e": 2907,
"s": 2769,
"text": "Note that the function createStudent returns a String type. This is a unique identifier (ID) which is generated after creating a student."
},
{
"code": null,
"e": 2985,
"s": 2907,
"text": "Create a file resolvers.js in the project folder and add the following code −"
},
{
"code": null,
"e": 3286,
"s": 2985,
"text": "const db = require('./db')\nconst Mutation = {\n createStudent:(root,args,context,info) => {\n return db.students.create({collegeId:args.collegeId,\n firstName:args.firstName,\n lastName:args.lastName})\n }\n}\nconst Query = {\n greeting:() => \"hello\"\n}\n\nmodule.exports = {Query,Mutation}"
},
{
"code": null,
"e": 3597,
"s": 3286,
"text": "The mutation function points to students collection in the datastore. To add a new student, invoke the create method in students collection. The args object will contain the parameters which are passed in the query. The create method of students collection will return the id of a newly created student object."
},
{
"code": null,
"e": 3826,
"s": 3597,
"text": "Create a server.js file. Refer to step 8 in the Environment Setup Chapter. Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application."
},
{
"code": null,
"e": 3945,
"s": 3826,
"text": "Next step is to open browser and type the URL http://localhost:9000/graphiql. Type the following query in the editor −"
},
{
"code": null,
"e": 4108,
"s": 3945,
"text": "//college Id should be matched with data from colleges.json for easy retrieval\n\nmutation {\n createStudent(collegeId:\"col-2\",firstName:\"Tim\",lastName:\"George\")\n}"
},
{
"code": null,
"e": 4264,
"s": 4108,
"text": "The above query will create a student object in student.json file. The query will return a unique identifier. The response of the query is as shown below −"
},
{
"code": null,
"e": 4321,
"s": 4264,
"text": "{\n \"data\": {\n \"createStudent\": \"SkQtxYBUm\"\n }\n}"
},
{
"code": null,
"e": 4475,
"s": 4321,
"text": "To verify if the student object is created, we can use the studentById query. You can also open the students.json file from data folder to verify the id."
},
{
"code": null,
"e": 4542,
"s": 4475,
"text": "To use studentById query, edit the schema.graphql as given below −"
},
{
"code": null,
"e": 4675,
"s": 4542,
"text": "type Query {\n studentById(id:ID!):Student\n}\n\ntype Student {\n id:ID!\n firstName:String\n lastName:String\n collegeId:String\n}"
},
{
"code": null,
"e": 4718,
"s": 4675,
"text": "Edit the resolver.js file as given below −"
},
{
"code": null,
"e": 5083,
"s": 4718,
"text": "const db = require('./db')\nconst Query = {\n studentById:(root,args,context,info) => {\n return db.students.get(args.id);\n }\n}\n\nconst Mutation = {\n createStudent:(root,args,context,info) => {\n return db.students.create({collegeId:args.collegeId,\n firstName:args.firstName,\n lastName:args.lastName})\n }\n}\n\nmodule.exports = {Query,Mutation}"
},
{
"code": null,
"e": 5171,
"s": 5083,
"text": "Given below is the query to get student by unique id returned from the mutation query −"
},
{
"code": null,
"e": 5247,
"s": 5171,
"text": "{\n studentById(id:\"SkQtxYBUm\") {\n id\n firstName\n lastName\n }\n}"
},
{
"code": null,
"e": 5292,
"s": 5247,
"text": "The response from the server is as follows −"
},
{
"code": null,
"e": 5431,
"s": 5292,
"text": "{\n \"data\": {\n \"studentById\": {\n \"id\": \"SkQtxYBUm\",\n \"firstName\": \"Tim\",\n \"lastName\":\"George\"\n }\n }\n}"
},
{
"code": null,
"e": 5713,
"s": 5431,
"text": "It is best practice to return an object in mutation. For example, the client application wants to fetch student and college details. In this case, rather than making two different requests, we can create a query that returns an object containing students and their college details."
},
{
"code": null,
"e": 5804,
"s": 5713,
"text": "Add a new method named addStudent which returns object in mutation type of schema.graphql."
},
{
"code": null,
"e": 5913,
"s": 5804,
"text": "Let us learn how to access the college details through student details. Add college type in the schema file."
},
{
"code": null,
"e": 6251,
"s": 5913,
"text": "type Mutation {\n addStudent_returns_object(collegeId:ID,firstName:String,lastName:String):Student\n\n createStudent(collegeId:ID,firstName:String,lastName:String):String\n}\n\ntype College {\n id:ID!\n name:String\n location:String\n rating:Float\n}\n\ntype Student {\n id:ID!\n firstName:String\n lastName:String\n college:College\n}"
},
{
"code": null,
"e": 6329,
"s": 6251,
"text": "Update a file resolvers.js in the project folder and add the following code −"
},
{
"code": null,
"e": 7028,
"s": 6329,
"text": "const Mutation = {\n createStudent:(root,args,context,info) => {\n\n return db.students.create({\n collegeId:args.collegeId,\n firstName:args.firstName,\n lastName:args.lastName\n })\n },\n \n // new resolver function\n addStudent_returns_object:(root,args,context,info) => {\n const id = db.students.create({\n collegeId:args.collegeId,\n firstName:args.firstName,\n lastName:args.lastName\n })\n\n return db.students.get(id)\n }\n}\n\n//for each single student object returned,resolver is invoked\nconst Student = {\n college:(root) => {\n return db.colleges.get(root.collegeId);\n }\n}\n\nmodule.exports = {Query,Student,Mutation}"
},
{
"code": null,
"e": 7116,
"s": 7028,
"text": "Next, we shall start the server and request query in GraphiQL with the following code −"
},
{
"code": null,
"e": 7296,
"s": 7116,
"text": "mutation {\n addStudent_returns_object(collegeId:\"col-101\",firstName:\"Susan\",lastName:\"George\") {\n id\n firstName\n college{\n id\n name\n }\n }\n}"
},
{
"code": null,
"e": 7429,
"s": 7296,
"text": "The above query adds a new student and retrieves the student object along with college object. This saves round trips to the server."
},
{
"code": null,
"e": 7462,
"s": 7429,
"text": "The response is as given below −"
},
{
"code": null,
"e": 7676,
"s": 7462,
"text": "{\n \"data\": {\n \"addStudent_returns_object\": {\n \"id\": \"rklUl08IX\",\n \"firstName\": \"Susan\",\n \"college\": {\n \"id\": \"col-101\",\n \"name\": \"AMU\"\n }\n }\n }\n}"
},
{
"code": null,
"e": 7709,
"s": 7676,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7722,
"s": 7709,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 7755,
"s": 7722,
"text": "\n 53 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7767,
"s": 7755,
"text": " Asfend Yar"
},
{
"code": null,
"e": 7800,
"s": 7767,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7818,
"s": 7800,
"text": " Mohd Raqif Warsi"
},
{
"code": null,
"e": 7825,
"s": 7818,
"text": " Print"
},
{
"code": null,
"e": 7836,
"s": 7825,
"text": " Add Notes"
}
] |
How to Update Multiple Records Using One Query in SQL Server? - GeeksforGeeks
|
19 Nov, 2021
In SQL, sometimes we need to update multiple records in a single query. We will use the UPDATE keyword to achieve this. For this, we use 2 kinds of examples i.e. the first based on only one condition and the second based on multiple conditions. For this article, we will be using the Microsoft SQL Server as our database and Select keyword.
Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks.
Query:
CREATE DATABASE GeeksForGeeks
Output:
Step 2: Use the GeeksForGeeks database. For this use the below command.
Query:
USE GeeksForGeeks
Output:
Step 3: Create a table of BANDS inside the database GeeksForGeeks. This table has 3 columns namely BAND_NAME, PERFORMING_COST, and NUMBER_OF_MEMBERS containing the names, charges for performing, and the number of members of a band.
Query:
CREATE TABLE BANDS(
BAND_NAME VARCHAR(20),
PERFORMING_COST INT,
NUMBER_OF_MEMBERS INT);
Output:
Step 4: Describe the structure of the table BANDS.
Query:
EXEC SP_COLUMNS BANDS;
Output:
Step 5: Insert 5 rows into the BANDS table.
Query:
INSERT INTO BANDS VALUES('INDIAN OCEAN',10000,5);
INSERT INTO BANDS VALUES('BTS',20000,6);
INSERT INTO BANDS VALUES('METALLICA',30000,10);
INSERT INTO BANDS VALUES('BEATLES',40000,4);
INSERT INTO BANDS VALUES('EAGLES',50000,4);
Output:
Step 6: Display all the rows of the BANDS table.
Query:
SELECT * FROM BANDS;
Output:
Step 7: Update all records of the table BANDS satisfying only a single condition. The condition here is that the value of the column NUMBER_OF_MEMBERS should be less than 5. If the condition is satisfied then the value of the column PERFORMING_COST doubles itself. Use the keyword UPDATE and WHERE to achieve this.
Syntax:
UPDATE TABLE_NAME SET COLUMN_NAME
= VALUE WHERE CONDITION;
Query:
UPDATE BANDS SET PERFORMING_COST =
2*PERFORMING_COST WHERE NUMBER_OF_MEMBERS<=5;
Output:
Step 8: Display all the rows of the updated FIRM table.
Query:
SELECT * FROM BANDS;
Note: The PERFORMING_COST has been doubled for the bands having NUMBER_OF_MEMBERS<=5.
Output:
Step 9: Update all records of the table BANDS satisfying two(multiple) conditions. The condition here is if the BAND_NAME is ‘METALLICA’, then its PERFORMING_COST is set to 90000 and if the BAND_NAME is ‘BTS’, then its PERFORMING_COST is set to 200000. Use the keyword UPDATE and WHEN to achieve this. This query behaves like an if-else if-else block.
Syntax:
UPDATE TABLE_NAME
SET COLUMN_VALUE
= CASE COLUMN_NAME
WHEN 'COLUMN_NAME1' THEN COLUMN_VALUE1
WHEN 'COLUMN_NAME2' THEN COLUMN_VALUE2
ELSE COLUMN_VALUE
END
WHERE BAND_NAME IN('COLUMN_NAME1', 'COLUMN_NAME2');
Query:
UPDATE BANDS
SET PERFORMING_COST
= CASE BAND_NAME
WHEN 'METALLICA' THEN 90000
WHEN 'BTS' THEN 200000
ELSE PERFORMING_COST
END
WHERE BAND_NAME IN('METALLICA', 'BTS');
Output:
Step 10: Display all the rows of the updated FIRM table.
Query:
SELECT * FROM BANDS;
Note: The PERFORMING_COST for METALLICA and BTS have been updated to 90000 and 200000 respectively.
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Interview Questions
Difference between DDL and DML in DBMS
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL - ORDER BY
SQL using Python
MySQL | Regular expressions (Regexp)
|
[
{
"code": null,
"e": 23970,
"s": 23942,
"text": "\n19 Nov, 2021"
},
{
"code": null,
"e": 24311,
"s": 23970,
"text": "In SQL, sometimes we need to update multiple records in a single query. We will use the UPDATE keyword to achieve this. For this, we use 2 kinds of examples i.e. the first based on only one condition and the second based on multiple conditions. For this article, we will be using the Microsoft SQL Server as our database and Select keyword."
},
{
"code": null,
"e": 24411,
"s": 24311,
"text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks."
},
{
"code": null,
"e": 24418,
"s": 24411,
"text": "Query:"
},
{
"code": null,
"e": 24448,
"s": 24418,
"text": "CREATE DATABASE GeeksForGeeks"
},
{
"code": null,
"e": 24456,
"s": 24448,
"text": "Output:"
},
{
"code": null,
"e": 24528,
"s": 24456,
"text": "Step 2: Use the GeeksForGeeks database. For this use the below command."
},
{
"code": null,
"e": 24535,
"s": 24528,
"text": "Query:"
},
{
"code": null,
"e": 24553,
"s": 24535,
"text": "USE GeeksForGeeks"
},
{
"code": null,
"e": 24561,
"s": 24553,
"text": "Output:"
},
{
"code": null,
"e": 24793,
"s": 24561,
"text": "Step 3: Create a table of BANDS inside the database GeeksForGeeks. This table has 3 columns namely BAND_NAME, PERFORMING_COST, and NUMBER_OF_MEMBERS containing the names, charges for performing, and the number of members of a band."
},
{
"code": null,
"e": 24800,
"s": 24793,
"text": "Query:"
},
{
"code": null,
"e": 24888,
"s": 24800,
"text": "CREATE TABLE BANDS(\nBAND_NAME VARCHAR(20),\nPERFORMING_COST INT,\nNUMBER_OF_MEMBERS INT);"
},
{
"code": null,
"e": 24896,
"s": 24888,
"text": "Output:"
},
{
"code": null,
"e": 24947,
"s": 24896,
"text": "Step 4: Describe the structure of the table BANDS."
},
{
"code": null,
"e": 24954,
"s": 24947,
"text": "Query:"
},
{
"code": null,
"e": 24977,
"s": 24954,
"text": "EXEC SP_COLUMNS BANDS;"
},
{
"code": null,
"e": 24985,
"s": 24977,
"text": "Output:"
},
{
"code": null,
"e": 25029,
"s": 24985,
"text": "Step 5: Insert 5 rows into the BANDS table."
},
{
"code": null,
"e": 25036,
"s": 25029,
"text": "Query:"
},
{
"code": null,
"e": 25264,
"s": 25036,
"text": "INSERT INTO BANDS VALUES('INDIAN OCEAN',10000,5);\nINSERT INTO BANDS VALUES('BTS',20000,6);\nINSERT INTO BANDS VALUES('METALLICA',30000,10);\nINSERT INTO BANDS VALUES('BEATLES',40000,4);\nINSERT INTO BANDS VALUES('EAGLES',50000,4);"
},
{
"code": null,
"e": 25272,
"s": 25264,
"text": "Output:"
},
{
"code": null,
"e": 25321,
"s": 25272,
"text": "Step 6: Display all the rows of the BANDS table."
},
{
"code": null,
"e": 25328,
"s": 25321,
"text": "Query:"
},
{
"code": null,
"e": 25349,
"s": 25328,
"text": "SELECT * FROM BANDS;"
},
{
"code": null,
"e": 25357,
"s": 25349,
"text": "Output:"
},
{
"code": null,
"e": 25672,
"s": 25357,
"text": "Step 7: Update all records of the table BANDS satisfying only a single condition. The condition here is that the value of the column NUMBER_OF_MEMBERS should be less than 5. If the condition is satisfied then the value of the column PERFORMING_COST doubles itself. Use the keyword UPDATE and WHERE to achieve this."
},
{
"code": null,
"e": 25680,
"s": 25672,
"text": "Syntax:"
},
{
"code": null,
"e": 25739,
"s": 25680,
"text": "UPDATE TABLE_NAME SET COLUMN_NAME\n= VALUE WHERE CONDITION;"
},
{
"code": null,
"e": 25746,
"s": 25739,
"text": "Query:"
},
{
"code": null,
"e": 25828,
"s": 25746,
"text": "UPDATE BANDS SET PERFORMING_COST = \n2*PERFORMING_COST WHERE NUMBER_OF_MEMBERS<=5;"
},
{
"code": null,
"e": 25836,
"s": 25828,
"text": "Output:"
},
{
"code": null,
"e": 25892,
"s": 25836,
"text": "Step 8: Display all the rows of the updated FIRM table."
},
{
"code": null,
"e": 25899,
"s": 25892,
"text": "Query:"
},
{
"code": null,
"e": 25920,
"s": 25899,
"text": "SELECT * FROM BANDS;"
},
{
"code": null,
"e": 26006,
"s": 25920,
"text": "Note: The PERFORMING_COST has been doubled for the bands having NUMBER_OF_MEMBERS<=5."
},
{
"code": null,
"e": 26014,
"s": 26006,
"text": "Output:"
},
{
"code": null,
"e": 26366,
"s": 26014,
"text": "Step 9: Update all records of the table BANDS satisfying two(multiple) conditions. The condition here is if the BAND_NAME is ‘METALLICA’, then its PERFORMING_COST is set to 90000 and if the BAND_NAME is ‘BTS’, then its PERFORMING_COST is set to 200000. Use the keyword UPDATE and WHEN to achieve this. This query behaves like an if-else if-else block."
},
{
"code": null,
"e": 26374,
"s": 26366,
"text": "Syntax:"
},
{
"code": null,
"e": 26581,
"s": 26374,
"text": "UPDATE TABLE_NAME\nSET COLUMN_VALUE \n= CASE COLUMN_NAME\nWHEN 'COLUMN_NAME1' THEN COLUMN_VALUE1\nWHEN 'COLUMN_NAME2' THEN COLUMN_VALUE2\nELSE COLUMN_VALUE\nEND\nWHERE BAND_NAME IN('COLUMN_NAME1', 'COLUMN_NAME2');"
},
{
"code": null,
"e": 26588,
"s": 26581,
"text": "Query:"
},
{
"code": null,
"e": 26755,
"s": 26588,
"text": "UPDATE BANDS\nSET PERFORMING_COST \n= CASE BAND_NAME\nWHEN 'METALLICA' THEN 90000\nWHEN 'BTS' THEN 200000\nELSE PERFORMING_COST\nEND\nWHERE BAND_NAME IN('METALLICA', 'BTS');"
},
{
"code": null,
"e": 26763,
"s": 26755,
"text": "Output:"
},
{
"code": null,
"e": 26820,
"s": 26763,
"text": "Step 10: Display all the rows of the updated FIRM table."
},
{
"code": null,
"e": 26827,
"s": 26820,
"text": "Query:"
},
{
"code": null,
"e": 26848,
"s": 26827,
"text": "SELECT * FROM BANDS;"
},
{
"code": null,
"e": 26948,
"s": 26848,
"text": "Note: The PERFORMING_COST for METALLICA and BTS have been updated to 90000 and 200000 respectively."
},
{
"code": null,
"e": 26956,
"s": 26948,
"text": "Output:"
},
{
"code": null,
"e": 26963,
"s": 26956,
"text": "Picked"
},
{
"code": null,
"e": 26974,
"s": 26963,
"text": "SQL-Server"
},
{
"code": null,
"e": 26978,
"s": 26974,
"text": "SQL"
},
{
"code": null,
"e": 26982,
"s": 26978,
"text": "SQL"
},
{
"code": null,
"e": 27080,
"s": 26982,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27091,
"s": 27080,
"text": "CTE in SQL"
},
{
"code": null,
"e": 27115,
"s": 27091,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 27154,
"s": 27115,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 27199,
"s": 27154,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 27231,
"s": 27199,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 27263,
"s": 27231,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27341,
"s": 27263,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27356,
"s": 27341,
"text": "SQL - ORDER BY"
},
{
"code": null,
"e": 27373,
"s": 27356,
"text": "SQL using Python"
}
] |
Print all the peaks and troughs in an Array of Integers - GeeksforGeeks
|
12 May, 2021
Given an array of integers arr[], the task is to print a list of all the peaks and another list of all the troughs present in the array. A peak is an element in the array which is greater than its neighbouring elements. Similarly, a trough is an element that is smaller than its neighbouring elements.
Examples:
Input: arr[] = {5, 10, 5, 7, 4, 3, 5} Output: Peaks : 10 7 5 Troughs : 5 5 3Input: arr[] = {1, 2, 3, 4, 5} Output: Peaks : 5 Troughs : 1
Approach: For every element of the array, check whether the current element is a peak (the element has to be greater than its neighbouring elements) or a trough (the element has to be smaller than its neighbouring elements). Note that the first and the last element of the array will have a single neighbour.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function that returns true if num is// greater than both arr[i] and arr[j]static bool isPeak(int arr[], int n, int num, int i, int j){ // If num is smaller than the element // on the left (if exists) if (i >= 0 && arr[i] > num) return false; // If num is smaller than the element // on the right (if exists) if (j < n && arr[j] > num) return false; return true;} // Function that returns true if num is// smaller than both arr[i] and arr[j]static bool isTrough(int arr[], int n, int num, int i, int j){ // If num is greater than the element // on the left (if exists) if (i >= 0 && arr[i] < num) return false; // If num is greater than the element // on the right (if exists) if (j < n && arr[j] < num) return false; return true;} void printPeaksTroughs(int arr[], int n){ cout << "Peaks : "; // For every element for (int i = 0; i < n; i++) { // If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)) cout << arr[i] << " "; } cout << endl; cout << "Troughs : "; // For every element for (int i = 0; i < n; i++) { // If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)) cout << arr[i] << " "; }} // Driver codeint main(){ int arr[] = { 5, 10, 5, 7, 4, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); printPeaksTroughs(arr, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if num is // greater than both arr[i] and arr[j] static boolean isPeak(int arr[], int n, int num, int i, int j) { // If num is smaller than the element // on the left (if exists) if (i >= 0 && arr[i] > num) { return false; } // If num is smaller than the element // on the right (if exists) if (j < n && arr[j] > num) { return false; } return true; } // Function that returns true if num is // smaller than both arr[i] and arr[j] static boolean isTrough(int arr[], int n, int num, int i, int j) { // If num is greater than the element // on the left (if exists) if (i >= 0 && arr[i] < num) { return false; } // If num is greater than the element // on the right (if exists) if (j < n && arr[j] < num) { return false; } return true; } static void printPeaksTroughs(int arr[], int n) { System.out.print("Peaks : "); // For every element for (int i = 0; i < n; i++) { // If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)) { System.out.print(arr[i] + " "); } } System.out.println(""); System.out.print("Troughs : "); // For every element for (int i = 0; i < n; i++) { // If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)) { System.out.print(arr[i] + " "); } } } // Driver code public static void main(String[] args) { int arr[] = {5, 10, 5, 7, 4, 3, 5}; int n = arr.length; printPeaksTroughs(arr, n); }} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function that returns true if num is# greater than both arr[i] and arr[j]def isPeak(arr, n, num, i, j): # If num is smaller than the element # on the left (if exists) if (i >= 0 and arr[i] > num): return False # If num is smaller than the element # on the right (if exists) if (j < n and arr[j] > num): return False return True # Function that returns true if num is# smaller than both arr[i] and arr[j]def isTrough(arr, n, num, i, j): # If num is greater than the element # on the left (if exists) if (i >= 0 and arr[i] < num): return False # If num is greater than the element # on the right (if exists) if (j < n and arr[j] < num): return False return True def printPeaksTroughs(arr, n): print("Peaks : ", end = "") # For every element for i in range(n): # If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)): print(arr[i], end = " ") print() print("Troughs : ", end = "") # For every element for i in range(n): # If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)): print(arr[i], end = " ") # Driver codearr = [5, 10, 5, 7, 4, 3, 5]n = len(arr) printPeaksTroughs(arr, n) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ // Function that returns true if num is // greater than both arr[i] and arr[j] static Boolean isPeak(int []arr, int n, int num, int i, int j) { // If num is smaller than the element // on the left (if exists) if (i >= 0 && arr[i] > num) { return false; } // If num is smaller than the element // on the right (if exists) if (j < n && arr[j] > num) { return false; } return true; } // Function that returns true if num is // smaller than both arr[i] and arr[j] static Boolean isTrough(int []arr, int n, int num, int i, int j) { // If num is greater than the element // on the left (if exists) if (i >= 0 && arr[i] < num) { return false; } // If num is greater than the element // on the right (if exists) if (j < n && arr[j] < num) { return false; } return true; } static void printPeaksTroughs(int []arr, int n) { Console.Write("Peaks : "); // For every element for (int i = 0; i < n; i++) { // If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)) { Console.Write(arr[i] + " "); } } Console.WriteLine(""); Console.Write("Troughs : "); // For every element for (int i = 0; i < n; i++) { // If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)) { Console.Write(arr[i] + " "); } } } // Driver code public static void Main(String[] args) { int []arr = {5, 10, 5, 7, 4, 3, 5}; int n = arr.Length; printPeaksTroughs(arr, n); }} // This code is contributed by Princi Singh
<script> // Function that returns true if num is// greater than both arr[i] and arr[j]function isPeak(arr, n, num, i, j){ // If num is smaller than the element // on the left (if exists) if (i >= 0 && arr[i] > num) return false; // If num is smaller than the element // on the right (if exists) if (j < n && arr[j] > num) return false; return true;} // Function that returns true if num is// smaller than both arr[i] and arr[j]function isTrough( arr, n, num, i, j){ // If num is greater than the element // on the left (if exists) if (i >= 0 && arr[i] < num) return false; // If num is greater than the element // on the right (if exists) if (j < n && arr[j] < num) return false; return true;} function printPeaksTroughs( arr, n){ document.write( "Peaks : "); // For every element for (var i = 0; i < n; i++) { // If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)) document.write( arr[i] + " "); } document.write( "<br>"); document.write( "Troughs : "); // For every element for (var i = 0; i < n; i++) { // If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)) document.write( arr[i] + " "); }}var arr=[ 5, 10, 5, 7, 4, 3, 5 ]; printPeaksTroughs(arr, 7); </script>
Peaks : 10 7 5
Troughs : 5 5 3
mohit kumar 29
Rajput-Ji
princi singh
akshitsaxenaa09
Traversal
Arrays
Python
Arrays
Traversal
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
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
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": 25156,
"s": 25128,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 25458,
"s": 25156,
"text": "Given an array of integers arr[], the task is to print a list of all the peaks and another list of all the troughs present in the array. A peak is an element in the array which is greater than its neighbouring elements. Similarly, a trough is an element that is smaller than its neighbouring elements."
},
{
"code": null,
"e": 25470,
"s": 25458,
"text": "Examples: "
},
{
"code": null,
"e": 25609,
"s": 25470,
"text": "Input: arr[] = {5, 10, 5, 7, 4, 3, 5} Output: Peaks : 10 7 5 Troughs : 5 5 3Input: arr[] = {1, 2, 3, 4, 5} Output: Peaks : 5 Troughs : 1 "
},
{
"code": null,
"e": 25918,
"s": 25609,
"text": "Approach: For every element of the array, check whether the current element is a peak (the element has to be greater than its neighbouring elements) or a trough (the element has to be smaller than its neighbouring elements). Note that the first and the last element of the array will have a single neighbour."
},
{
"code": null,
"e": 25970,
"s": 25918,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25974,
"s": 25970,
"text": "C++"
},
{
"code": null,
"e": 25979,
"s": 25974,
"text": "Java"
},
{
"code": null,
"e": 25987,
"s": 25979,
"text": "Python3"
},
{
"code": null,
"e": 25990,
"s": 25987,
"text": "C#"
},
{
"code": null,
"e": 26001,
"s": 25990,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function that returns true if num is// greater than both arr[i] and arr[j]static bool isPeak(int arr[], int n, int num, int i, int j){ // If num is smaller than the element // on the left (if exists) if (i >= 0 && arr[i] > num) return false; // If num is smaller than the element // on the right (if exists) if (j < n && arr[j] > num) return false; return true;} // Function that returns true if num is// smaller than both arr[i] and arr[j]static bool isTrough(int arr[], int n, int num, int i, int j){ // If num is greater than the element // on the left (if exists) if (i >= 0 && arr[i] < num) return false; // If num is greater than the element // on the right (if exists) if (j < n && arr[j] < num) return false; return true;} void printPeaksTroughs(int arr[], int n){ cout << \"Peaks : \"; // For every element for (int i = 0; i < n; i++) { // If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)) cout << arr[i] << \" \"; } cout << endl; cout << \"Troughs : \"; // For every element for (int i = 0; i < n; i++) { // If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)) cout << arr[i] << \" \"; }} // Driver codeint main(){ int arr[] = { 5, 10, 5, 7, 4, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); printPeaksTroughs(arr, n); return 0;}",
"e": 27571,
"s": 26001,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true if num is // greater than both arr[i] and arr[j] static boolean isPeak(int arr[], int n, int num, int i, int j) { // If num is smaller than the element // on the left (if exists) if (i >= 0 && arr[i] > num) { return false; } // If num is smaller than the element // on the right (if exists) if (j < n && arr[j] > num) { return false; } return true; } // Function that returns true if num is // smaller than both arr[i] and arr[j] static boolean isTrough(int arr[], int n, int num, int i, int j) { // If num is greater than the element // on the left (if exists) if (i >= 0 && arr[i] < num) { return false; } // If num is greater than the element // on the right (if exists) if (j < n && arr[j] < num) { return false; } return true; } static void printPeaksTroughs(int arr[], int n) { System.out.print(\"Peaks : \"); // For every element for (int i = 0; i < n; i++) { // If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)) { System.out.print(arr[i] + \" \"); } } System.out.println(\"\"); System.out.print(\"Troughs : \"); // For every element for (int i = 0; i < n; i++) { // If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)) { System.out.print(arr[i] + \" \"); } } } // Driver code public static void main(String[] args) { int arr[] = {5, 10, 5, 7, 4, 3, 5}; int n = arr.length; printPeaksTroughs(arr, n); }} // This code is contributed by Rajput-Ji",
"e": 29616,
"s": 27571,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function that returns true if num is# greater than both arr[i] and arr[j]def isPeak(arr, n, num, i, j): # If num is smaller than the element # on the left (if exists) if (i >= 0 and arr[i] > num): return False # If num is smaller than the element # on the right (if exists) if (j < n and arr[j] > num): return False return True # Function that returns true if num is# smaller than both arr[i] and arr[j]def isTrough(arr, n, num, i, j): # If num is greater than the element # on the left (if exists) if (i >= 0 and arr[i] < num): return False # If num is greater than the element # on the right (if exists) if (j < n and arr[j] < num): return False return True def printPeaksTroughs(arr, n): print(\"Peaks : \", end = \"\") # For every element for i in range(n): # If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)): print(arr[i], end = \" \") print() print(\"Troughs : \", end = \"\") # For every element for i in range(n): # If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)): print(arr[i], end = \" \") # Driver codearr = [5, 10, 5, 7, 4, 3, 5]n = len(arr) printPeaksTroughs(arr, n) # This code is contributed by Mohit Kumar",
"e": 30977,
"s": 29616,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if num is // greater than both arr[i] and arr[j] static Boolean isPeak(int []arr, int n, int num, int i, int j) { // If num is smaller than the element // on the left (if exists) if (i >= 0 && arr[i] > num) { return false; } // If num is smaller than the element // on the right (if exists) if (j < n && arr[j] > num) { return false; } return true; } // Function that returns true if num is // smaller than both arr[i] and arr[j] static Boolean isTrough(int []arr, int n, int num, int i, int j) { // If num is greater than the element // on the left (if exists) if (i >= 0 && arr[i] < num) { return false; } // If num is greater than the element // on the right (if exists) if (j < n && arr[j] < num) { return false; } return true; } static void printPeaksTroughs(int []arr, int n) { Console.Write(\"Peaks : \"); // For every element for (int i = 0; i < n; i++) { // If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)) { Console.Write(arr[i] + \" \"); } } Console.WriteLine(\"\"); Console.Write(\"Troughs : \"); // For every element for (int i = 0; i < n; i++) { // If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)) { Console.Write(arr[i] + \" \"); } } } // Driver code public static void Main(String[] args) { int []arr = {5, 10, 5, 7, 4, 3, 5}; int n = arr.Length; printPeaksTroughs(arr, n); }} // This code is contributed by Princi Singh",
"e": 33008,
"s": 30977,
"text": null
},
{
"code": "<script> // Function that returns true if num is// greater than both arr[i] and arr[j]function isPeak(arr, n, num, i, j){ // If num is smaller than the element // on the left (if exists) if (i >= 0 && arr[i] > num) return false; // If num is smaller than the element // on the right (if exists) if (j < n && arr[j] > num) return false; return true;} // Function that returns true if num is// smaller than both arr[i] and arr[j]function isTrough( arr, n, num, i, j){ // If num is greater than the element // on the left (if exists) if (i >= 0 && arr[i] < num) return false; // If num is greater than the element // on the right (if exists) if (j < n && arr[j] < num) return false; return true;} function printPeaksTroughs( arr, n){ document.write( \"Peaks : \"); // For every element for (var i = 0; i < n; i++) { // If the current element is a peak if (isPeak(arr, n, arr[i], i - 1, i + 1)) document.write( arr[i] + \" \"); } document.write( \"<br>\"); document.write( \"Troughs : \"); // For every element for (var i = 0; i < n; i++) { // If the current element is a trough if (isTrough(arr, n, arr[i], i - 1, i + 1)) document.write( arr[i] + \" \"); }}var arr=[ 5, 10, 5, 7, 4, 3, 5 ]; printPeaksTroughs(arr, 7); </script>",
"e": 34392,
"s": 33008,
"text": null
},
{
"code": null,
"e": 34424,
"s": 34392,
"text": "Peaks : 10 7 5 \nTroughs : 5 5 3"
},
{
"code": null,
"e": 34441,
"s": 34426,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34451,
"s": 34441,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34464,
"s": 34451,
"text": "princi singh"
},
{
"code": null,
"e": 34480,
"s": 34464,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 34490,
"s": 34480,
"text": "Traversal"
},
{
"code": null,
"e": 34497,
"s": 34490,
"text": "Arrays"
},
{
"code": null,
"e": 34504,
"s": 34497,
"text": "Python"
},
{
"code": null,
"e": 34511,
"s": 34504,
"text": "Arrays"
},
{
"code": null,
"e": 34521,
"s": 34511,
"text": "Traversal"
},
{
"code": null,
"e": 34619,
"s": 34521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34687,
"s": 34619,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34735,
"s": 34687,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34779,
"s": 34735,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34811,
"s": 34779,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34834,
"s": 34811,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34862,
"s": 34834,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 34912,
"s": 34862,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 34934,
"s": 34912,
"text": "Python map() function"
}
] |
D3.js voronoi() Function - GeeksforGeeks
|
01 Oct, 2020
The d3.voronoi() function in D3.js is used to create a new Voronoi diagram layout with the default x and y accessors and a null extent. The Voronoi diagram is drawn using a set of data points that can be specified later.
Syntax:
d3.voronoi()
Parameters: This function does not accept any parameters.
The example below demonstrates the d3.voronoi() function:
Example:
HTML
<!DOCTYPE html><html><head> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-voronoi.v1.min.js"> </script></head><body> <h1 style="color:green"> GeeksforGeeks </h1> <script> // Import the CSV data for // specifying the Voronoi d3.csv("data.csv", function (error, data) { var svg = d3.select("body") .append("svg") .attr("height", 400) .attr("width", 400) .append("g") .attr("transform", "translate(" + 20 + "," + -20 + ")"); var y = d3.scaleLinear() .domain([2, 20]) .range([400, 0]); var x = d3.scaleLinear() .domain([2, 15]) .range([0, 400]); svg.append("g") .call(d3.axisLeft(y)); svg.append("g") .attr("transform", "translate(0," + 400 + ")") .call(d3.axisBottom(x)); // Using the d3.voronoi() function // to create a Voronoi diagram var voronoi = d3.voronoi() .x(function (d) { return x(d.x); }) .y(function (d) { return y(d.y); }) .extent([[0, 0], [400, 400]]); // Adding data to represent the Voronoi // and displaying it svg.append("g").selectAll("path") .data(voronoi(data).polygons()) .enter() .append("path") .attr("d", (d) => { return d ? ("M" + d.join("L") + "Z") : null; }) .attr("fill", "green") .attr("stroke", "black"); }); </script></body></html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25521,
"s": 25300,
"text": "The d3.voronoi() function in D3.js is used to create a new Voronoi diagram layout with the default x and y accessors and a null extent. The Voronoi diagram is drawn using a set of data points that can be specified later."
},
{
"code": null,
"e": 25529,
"s": 25521,
"text": "Syntax:"
},
{
"code": null,
"e": 25543,
"s": 25529,
"text": "d3.voronoi()\n"
},
{
"code": null,
"e": 25601,
"s": 25543,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 25659,
"s": 25601,
"text": "The example below demonstrates the d3.voronoi() function:"
},
{
"code": null,
"e": 25668,
"s": 25659,
"text": "Example:"
},
{
"code": null,
"e": 25673,
"s": 25668,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-voronoi.v1.min.js\"> </script></head><body> <h1 style=\"color:green\"> GeeksforGeeks </h1> <script> // Import the CSV data for // specifying the Voronoi d3.csv(\"data.csv\", function (error, data) { var svg = d3.select(\"body\") .append(\"svg\") .attr(\"height\", 400) .attr(\"width\", 400) .append(\"g\") .attr(\"transform\", \"translate(\" + 20 + \",\" + -20 + \")\"); var y = d3.scaleLinear() .domain([2, 20]) .range([400, 0]); var x = d3.scaleLinear() .domain([2, 15]) .range([0, 400]); svg.append(\"g\") .call(d3.axisLeft(y)); svg.append(\"g\") .attr(\"transform\", \"translate(0,\" + 400 + \")\") .call(d3.axisBottom(x)); // Using the d3.voronoi() function // to create a Voronoi diagram var voronoi = d3.voronoi() .x(function (d) { return x(d.x); }) .y(function (d) { return y(d.y); }) .extent([[0, 0], [400, 400]]); // Adding data to represent the Voronoi // and displaying it svg.append(\"g\").selectAll(\"path\") .data(voronoi(data).polygons()) .enter() .append(\"path\") .attr(\"d\", (d) => { return d ? (\"M\" + d.join(\"L\") + \"Z\") : null; }) .attr(\"fill\", \"green\") .attr(\"stroke\", \"black\"); }); </script></body></html>",
"e": 27214,
"s": 25673,
"text": null
},
{
"code": null,
"e": 27222,
"s": 27214,
"text": "Output:"
},
{
"code": null,
"e": 27228,
"s": 27222,
"text": "D3.js"
},
{
"code": null,
"e": 27239,
"s": 27228,
"text": "JavaScript"
},
{
"code": null,
"e": 27256,
"s": 27239,
"text": "Web Technologies"
},
{
"code": null,
"e": 27354,
"s": 27256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27415,
"s": 27354,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27455,
"s": 27415,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27496,
"s": 27455,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27550,
"s": 27496,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27598,
"s": 27550,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27640,
"s": 27598,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27673,
"s": 27640,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27735,
"s": 27673,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27778,
"s": 27735,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Data types that supports std::numeric_limits() in C++ - GeeksforGeeks
|
21 Aug, 2021
The numeric_limits class template provides an easy and standardized way to query various properties of arithmetic types. For example, the maximum value a type T can store is std::numeric_limits<T>::max().
Example:
std::numeric_limits<int>::max() gives the maximum possible value we can store in type int.
std::numeric_limits<unsigned int>::max()) gives the maximum possible value we can store in type unsigned int.
The numeric_limits have many member functions, member constants, and helper classes and some of them are type-specific. For example std::numeric_limits<T>::lowest() for floating data types only. The most common queries for data types are:
std::numeric_limits<T>::is_integer: It is true if T is numerical type and false for floating-point types.
std::numeric_limits<T>::is_signed: It is true for all signed arithmetic types T and false for the unsigned types.
std::numeric_limits<T>::digits: It is the number of digits in base-radix. For example- -1 for bool, 7 for char, 31 for int, etc.
std::numeric_limits<T>::digits10: It is the number of base-10 digits that can be represented by the type T without any change.
std::numeric_limits<T>::max_digits10: It is the number of base-10 digits that are necessary to uniquely represent all distinct values of the type T.
Also, queries for a min, max, lowest, size in bytes, and bits.
The floating points have epsilon-related queries. Except for these, numeric_limits some more functions. For Example: has_infinity, traps, round_error, etc.
Below is the program to show the most common numeric_limits functions for all data types:
C++
// C++ program to demonstrate the use// possible numerical data types// that supports std::numeric_limits #include <cstdint>#include <functional>#include <iomanip>#include <iostream>#include <limits>#include <string> struct RowPrinter { // Left alignment int m_left; // Right alignment int m_right; RowPrinter(int left, int right) : m_left(left), m_right(right) { // Print bool as 'true' or 'false' // instead of 0 or 1. std::cout << std::boolalpha; } template <class A> auto printRow(const std::string& label, const A& value) const -> void { std::cout << std::setw(m_left) << label << std::setw(m_right) << value << "\n"; }}; #define SHOW_INTEGER_LIMITS(numtype) \ showNumericLimits<numtype>(#numtype)#define SHOW_FLOAT_LIMITS(numtype) \ showFloatPointLimits<numtype>(#numtype) // Function to show the numeric// limitstemplate <class T>void showNumericLimits(const std::string& name){ RowPrinter rp{ 30, 25 }; std::cout << "Numeric limits for type: " << name << "\n"; std::cout << std::string(60, '-') << "\n"; rp.printRow("Type:", name); rp.printRow("Is integer:", std::numeric_limits<T>::is_integer); rp.printRow("Is signed:", std::numeric_limits<T>::is_signed); rp.printRow("Number of digits:", std::numeric_limits<T>::digits); rp.printRow("Number of digits 10:", std::numeric_limits<T>::digits10); rp.printRow("Max Number of digits 10:", std::numeric_limits<T>::max_digits10); // RTTI - Run-Time Type Information if (typeid(T) == typeid(uint8_t) || typeid(T) == typeid(int8_t) || typeid(T) == typeid(bool) || typeid(T) == typeid(char) || typeid(T) == typeid(unsigned char)) { // Min Abs - smallest positive value // for float point numbers rp.printRow("Min:", static_cast<int>( std::numeric_limits<T>::min())); // Smallest value (can be negative) rp.printRow("Lowest:", static_cast<int>( std::numeric_limits<T>::lowest())); // Largest value rp.printRow("Max:", static_cast<int>( std::numeric_limits<T>::max())); } else { rp.printRow("Min:", std::numeric_limits<T>::min()); rp.printRow("Lowest:", std::numeric_limits<T>::lowest()); rp.printRow("Max:", std::numeric_limits<T>::max()); } rp.printRow("Size in bytes:", sizeof(T)); rp.printRow("Size in bits:", 8 * sizeof(T)); std::cout << "\n";} // Function to show float points// limitstemplate <class T>void showFloatPointLimits(const std::string& name){ RowPrinter rp{ 30, 25 }; showNumericLimits<T>(name); rp.printRow("Epsilon:", std::numeric_limits<T>::epsilon()); rp.printRow("Min exponent:", std::numeric_limits<T>::min_exponent10); rp.printRow("Max exponent:", std::numeric_limits<T>::max_exponent10);} // Driver Codeint main(){ // Boolean type SHOW_INTEGER_LIMITS(bool); // Character types SHOW_INTEGER_LIMITS(char); SHOW_INTEGER_LIMITS(unsigned char); SHOW_INTEGER_LIMITS(wchar_t); // Standard integers in <cstdint> SHOW_INTEGER_LIMITS(int8_t); SHOW_INTEGER_LIMITS(uint8_t); SHOW_INTEGER_LIMITS(int16_t); SHOW_INTEGER_LIMITS(uint16_t); SHOW_INTEGER_LIMITS(int32_t); SHOW_INTEGER_LIMITS(uint32_t); SHOW_INTEGER_LIMITS(int64_t); SHOW_INTEGER_LIMITS(uint64_t); // Integer types SHOW_INTEGER_LIMITS(short); SHOW_INTEGER_LIMITS(unsigned short); SHOW_INTEGER_LIMITS(int); SHOW_INTEGER_LIMITS(unsigned int); SHOW_INTEGER_LIMITS(long); SHOW_INTEGER_LIMITS(unsigned long); SHOW_INTEGER_LIMITS(long long); SHOW_INTEGER_LIMITS(unsigned long long); // Floating types SHOW_FLOAT_LIMITS(float); SHOW_FLOAT_LIMITS(double); SHOW_FLOAT_LIMITS(long double); return 0;}
Numeric limits for type: bool
------------------------------------------------------------
Type: bool
Is integer: true
Is signed: false
Number of digits: 1
Number of digits 10: 0
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 1
Size in bytes: 1
Size in bits: 8
Numeric limits for type: char
------------------------------------------------------------
Type: char
Is integer: true
Is signed: true
Number of digits: 7
Number of digits 10: 2
Max Number of digits 10: 0
Min: -128
Lowest: -128
Max: 127
Size in bytes: 1
Size in bits: 8
Numeric limits for type: unsigned char
------------------------------------------------------------
Type: unsigned char
Is integer: true
Is signed: false
Number of digits: 8
Number of digits 10: 2
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 255
Size in bytes: 1
Size in bits: 8
Numeric limits for type: wchar_t
------------------------------------------------------------
Type: wchar_t
Is integer: true
Is signed: true
Number of digits: 31
Number of digits 10: 9
Max Number of digits 10: 0
Min: -2147483648
Lowest: -2147483648
Max: 2147483647
Size in bytes: 4
Size in bits: 32
Numeric limits for type: int8_t
------------------------------------------------------------
Type: int8_t
Is integer: true
Is signed: true
Number of digits: 7
Number of digits 10: 2
Max Number of digits 10: 0
Min: -128
Lowest: -128
Max: 127
Size in bytes: 1
Size in bits: 8
Numeric limits for type: uint8_t
------------------------------------------------------------
Type: uint8_t
Is integer: true
Is signed: false
Number of digits: 8
Number of digits 10: 2
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 255
Size in bytes: 1
Size in bits: 8
Numeric limits for type: int16_t
------------------------------------------------------------
Type: int16_t
Is integer: true
Is signed: true
Number of digits: 15
Number of digits 10: 4
Max Number of digits 10: 0
Min: -32768
Lowest: -32768
Max: 32767
Size in bytes: 2
Size in bits: 16
Numeric limits for type: uint16_t
------------------------------------------------------------
Type: uint16_t
Is integer: true
Is signed: false
Number of digits: 16
Number of digits 10: 4
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 65535
Size in bytes: 2
Size in bits: 16
Numeric limits for type: int32_t
------------------------------------------------------------
Type: int32_t
Is integer: true
Is signed: true
Number of digits: 31
Number of digits 10: 9
Max Number of digits 10: 0
Min: -2147483648
Lowest: -2147483648
Max: 2147483647
Size in bytes: 4
Size in bits: 32
Numeric limits for type: uint32_t
------------------------------------------------------------
Type: uint32_t
Is integer: true
Is signed: false
Number of digits: 32
Number of digits 10: 9
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 4294967295
Size in bytes: 4
Size in bits: 32
Numeric limits for type: int64_t
------------------------------------------------------------
Type: int64_t
Is integer: true
Is signed: true
Number of digits: 63
Number of digits 10: 18
Max Number of digits 10: 0
Min: -9223372036854775808
Lowest: -9223372036854775808
Max: 9223372036854775807
Size in bytes: 8
Size in bits: 64
Numeric limits for type: uint64_t
------------------------------------------------------------
Type: uint64_t
Is integer: true
Is signed: false
Number of digits: 64
Number of digits 10: 19
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 18446744073709551615
Size in bytes: 8
Size in bits: 64
Numeric limits for type: short
------------------------------------------------------------
Type: short
Is integer: true
Is signed: true
Number of digits: 15
Number of digits 10: 4
Max Number of digits 10: 0
Min: -32768
Lowest: -32768
Max: 32767
Size in bytes: 2
Size in bits: 16
Numeric limits for type: unsigned short
------------------------------------------------------------
Type: unsigned short
Is integer: true
Is signed: false
Number of digits: 16
Number of digits 10: 4
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 65535
Size in bytes: 2
Size in bits: 16
Numeric limits for type: int
------------------------------------------------------------
Type: int
Is integer: true
Is signed: true
Number of digits: 31
Number of digits 10: 9
Max Number of digits 10: 0
Min: -2147483648
Lowest: -2147483648
Max: 2147483647
Size in bytes: 4
Size in bits: 32
Numeric limits for type: unsigned int
------------------------------------------------------------
Type: unsigned int
Is integer: true
Is signed: false
Number of digits: 32
Number of digits 10: 9
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 4294967295
Size in bytes: 4
Size in bits: 32
Numeric limits for type: long
------------------------------------------------------------
Type: long
Is integer: true
Is signed: true
Number of digits: 63
Number of digits 10: 18
Max Number of digits 10: 0
Min: -9223372036854775808
Lowest: -9223372036854775808
Max: 9223372036854775807
Size in bytes: 8
Size in bits: 64
Numeric limits for type: unsigned long
------------------------------------------------------------
Type: unsigned long
Is integer: true
Is signed: false
Number of digits: 64
Number of digits 10: 19
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 18446744073709551615
Size in bytes: 8
Size in bits: 64
Numeric limits for type: long long
------------------------------------------------------------
Type: long long
Is integer: true
Is signed: true
Number of digits: 63
Number of digits 10: 18
Max Number of digits 10: 0
Min: -9223372036854775808
Lowest: -9223372036854775808
Max: 9223372036854775807
Size in bytes: 8
Size in bits: 64
Numeric limits for type: unsigned long long
------------------------------------------------------------
Type: unsigned long long
Is integer: true
Is signed: false
Number of digits: 64
Number of digits 10: 19
Max Number of digits 10: 0
Min: 0
Lowest: 0
Max: 18446744073709551615
Size in bytes: 8
Size in bits: 64
Numeric limits for type: float
------------------------------------------------------------
Type: float
Is integer: false
Is signed: true
Number of digits: 24
Number of digits 10: 6
Max Number of digits 10: 9
Min: 1.17549e-38
Lowest: -3.40282e+38
Max: 3.40282e+38
Size in bytes: 4
Size in bits: 32
Epsilon: 1.19209e-07
Min exponent: -37
Max exponent: 38
Numeric limits for type: double
------------------------------------------------------------
Type: double
Is integer: false
Is signed: true
Number of digits: 53
Number of digits 10: 15
Max Number of digits 10: 17
Min: 2.22507e-308
Lowest: -1.79769e+308
Max: 1.79769e+308
Size in bytes: 8
Size in bits: 64
Epsilon: 2.22045e-16
Min exponent: -307
Max exponent: 308
Numeric limits for type: long double
------------------------------------------------------------
Type: long double
Is integer: false
Is signed: true
Number of digits: 64
Number of digits 10: 18
Max Number of digits 10: 21
Min: 3.3621e-4932
Lowest: -1.18973e+4932
Max: 1.18973e+4932
Size in bytes: 16
Size in bits: 128
Epsilon: 1.0842e-19
Min exponent: -4931
Max exponent: 4932
sumitgumber28
cpp-numerics-library
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Program to print ASCII Value of a character
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 24124,
"s": 24096,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 24329,
"s": 24124,
"text": "The numeric_limits class template provides an easy and standardized way to query various properties of arithmetic types. For example, the maximum value a type T can store is std::numeric_limits<T>::max()."
},
{
"code": null,
"e": 24338,
"s": 24329,
"text": "Example:"
},
{
"code": null,
"e": 24429,
"s": 24338,
"text": "std::numeric_limits<int>::max() gives the maximum possible value we can store in type int."
},
{
"code": null,
"e": 24539,
"s": 24429,
"text": "std::numeric_limits<unsigned int>::max()) gives the maximum possible value we can store in type unsigned int."
},
{
"code": null,
"e": 24778,
"s": 24539,
"text": "The numeric_limits have many member functions, member constants, and helper classes and some of them are type-specific. For example std::numeric_limits<T>::lowest() for floating data types only. The most common queries for data types are:"
},
{
"code": null,
"e": 24884,
"s": 24778,
"text": "std::numeric_limits<T>::is_integer: It is true if T is numerical type and false for floating-point types."
},
{
"code": null,
"e": 24998,
"s": 24884,
"text": "std::numeric_limits<T>::is_signed: It is true for all signed arithmetic types T and false for the unsigned types."
},
{
"code": null,
"e": 25127,
"s": 24998,
"text": "std::numeric_limits<T>::digits: It is the number of digits in base-radix. For example- -1 for bool, 7 for char, 31 for int, etc."
},
{
"code": null,
"e": 25254,
"s": 25127,
"text": "std::numeric_limits<T>::digits10: It is the number of base-10 digits that can be represented by the type T without any change."
},
{
"code": null,
"e": 25403,
"s": 25254,
"text": "std::numeric_limits<T>::max_digits10: It is the number of base-10 digits that are necessary to uniquely represent all distinct values of the type T."
},
{
"code": null,
"e": 25466,
"s": 25403,
"text": "Also, queries for a min, max, lowest, size in bytes, and bits."
},
{
"code": null,
"e": 25622,
"s": 25466,
"text": "The floating points have epsilon-related queries. Except for these, numeric_limits some more functions. For Example: has_infinity, traps, round_error, etc."
},
{
"code": null,
"e": 25712,
"s": 25622,
"text": "Below is the program to show the most common numeric_limits functions for all data types:"
},
{
"code": null,
"e": 25716,
"s": 25712,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the use// possible numerical data types// that supports std::numeric_limits #include <cstdint>#include <functional>#include <iomanip>#include <iostream>#include <limits>#include <string> struct RowPrinter { // Left alignment int m_left; // Right alignment int m_right; RowPrinter(int left, int right) : m_left(left), m_right(right) { // Print bool as 'true' or 'false' // instead of 0 or 1. std::cout << std::boolalpha; } template <class A> auto printRow(const std::string& label, const A& value) const -> void { std::cout << std::setw(m_left) << label << std::setw(m_right) << value << \"\\n\"; }}; #define SHOW_INTEGER_LIMITS(numtype) \\ showNumericLimits<numtype>(#numtype)#define SHOW_FLOAT_LIMITS(numtype) \\ showFloatPointLimits<numtype>(#numtype) // Function to show the numeric// limitstemplate <class T>void showNumericLimits(const std::string& name){ RowPrinter rp{ 30, 25 }; std::cout << \"Numeric limits for type: \" << name << \"\\n\"; std::cout << std::string(60, '-') << \"\\n\"; rp.printRow(\"Type:\", name); rp.printRow(\"Is integer:\", std::numeric_limits<T>::is_integer); rp.printRow(\"Is signed:\", std::numeric_limits<T>::is_signed); rp.printRow(\"Number of digits:\", std::numeric_limits<T>::digits); rp.printRow(\"Number of digits 10:\", std::numeric_limits<T>::digits10); rp.printRow(\"Max Number of digits 10:\", std::numeric_limits<T>::max_digits10); // RTTI - Run-Time Type Information if (typeid(T) == typeid(uint8_t) || typeid(T) == typeid(int8_t) || typeid(T) == typeid(bool) || typeid(T) == typeid(char) || typeid(T) == typeid(unsigned char)) { // Min Abs - smallest positive value // for float point numbers rp.printRow(\"Min:\", static_cast<int>( std::numeric_limits<T>::min())); // Smallest value (can be negative) rp.printRow(\"Lowest:\", static_cast<int>( std::numeric_limits<T>::lowest())); // Largest value rp.printRow(\"Max:\", static_cast<int>( std::numeric_limits<T>::max())); } else { rp.printRow(\"Min:\", std::numeric_limits<T>::min()); rp.printRow(\"Lowest:\", std::numeric_limits<T>::lowest()); rp.printRow(\"Max:\", std::numeric_limits<T>::max()); } rp.printRow(\"Size in bytes:\", sizeof(T)); rp.printRow(\"Size in bits:\", 8 * sizeof(T)); std::cout << \"\\n\";} // Function to show float points// limitstemplate <class T>void showFloatPointLimits(const std::string& name){ RowPrinter rp{ 30, 25 }; showNumericLimits<T>(name); rp.printRow(\"Epsilon:\", std::numeric_limits<T>::epsilon()); rp.printRow(\"Min exponent:\", std::numeric_limits<T>::min_exponent10); rp.printRow(\"Max exponent:\", std::numeric_limits<T>::max_exponent10);} // Driver Codeint main(){ // Boolean type SHOW_INTEGER_LIMITS(bool); // Character types SHOW_INTEGER_LIMITS(char); SHOW_INTEGER_LIMITS(unsigned char); SHOW_INTEGER_LIMITS(wchar_t); // Standard integers in <cstdint> SHOW_INTEGER_LIMITS(int8_t); SHOW_INTEGER_LIMITS(uint8_t); SHOW_INTEGER_LIMITS(int16_t); SHOW_INTEGER_LIMITS(uint16_t); SHOW_INTEGER_LIMITS(int32_t); SHOW_INTEGER_LIMITS(uint32_t); SHOW_INTEGER_LIMITS(int64_t); SHOW_INTEGER_LIMITS(uint64_t); // Integer types SHOW_INTEGER_LIMITS(short); SHOW_INTEGER_LIMITS(unsigned short); SHOW_INTEGER_LIMITS(int); SHOW_INTEGER_LIMITS(unsigned int); SHOW_INTEGER_LIMITS(long); SHOW_INTEGER_LIMITS(unsigned long); SHOW_INTEGER_LIMITS(long long); SHOW_INTEGER_LIMITS(unsigned long long); // Floating types SHOW_FLOAT_LIMITS(float); SHOW_FLOAT_LIMITS(double); SHOW_FLOAT_LIMITS(long double); return 0;}",
"e": 29783,
"s": 25716,
"text": null
},
{
"code": null,
"e": 46665,
"s": 29783,
"text": "Numeric limits for type: bool\n------------------------------------------------------------\n Type: bool\n Is integer: true\n Is signed: false\n Number of digits: 1\n Number of digits 10: 0\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 1\n Size in bytes: 1\n Size in bits: 8\n\nNumeric limits for type: char\n------------------------------------------------------------\n Type: char\n Is integer: true\n Is signed: true\n Number of digits: 7\n Number of digits 10: 2\n Max Number of digits 10: 0\n Min: -128\n Lowest: -128\n Max: 127\n Size in bytes: 1\n Size in bits: 8\n\nNumeric limits for type: unsigned char\n------------------------------------------------------------\n Type: unsigned char\n Is integer: true\n Is signed: false\n Number of digits: 8\n Number of digits 10: 2\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 255\n Size in bytes: 1\n Size in bits: 8\n\nNumeric limits for type: wchar_t\n------------------------------------------------------------\n Type: wchar_t\n Is integer: true\n Is signed: true\n Number of digits: 31\n Number of digits 10: 9\n Max Number of digits 10: 0\n Min: -2147483648\n Lowest: -2147483648\n Max: 2147483647\n Size in bytes: 4\n Size in bits: 32\n\nNumeric limits for type: int8_t\n------------------------------------------------------------\n Type: int8_t\n Is integer: true\n Is signed: true\n Number of digits: 7\n Number of digits 10: 2\n Max Number of digits 10: 0\n Min: -128\n Lowest: -128\n Max: 127\n Size in bytes: 1\n Size in bits: 8\n\nNumeric limits for type: uint8_t\n------------------------------------------------------------\n Type: uint8_t\n Is integer: true\n Is signed: false\n Number of digits: 8\n Number of digits 10: 2\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 255\n Size in bytes: 1\n Size in bits: 8\n\nNumeric limits for type: int16_t\n------------------------------------------------------------\n Type: int16_t\n Is integer: true\n Is signed: true\n Number of digits: 15\n Number of digits 10: 4\n Max Number of digits 10: 0\n Min: -32768\n Lowest: -32768\n Max: 32767\n Size in bytes: 2\n Size in bits: 16\n\nNumeric limits for type: uint16_t\n------------------------------------------------------------\n Type: uint16_t\n Is integer: true\n Is signed: false\n Number of digits: 16\n Number of digits 10: 4\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 65535\n Size in bytes: 2\n Size in bits: 16\n\nNumeric limits for type: int32_t\n------------------------------------------------------------\n Type: int32_t\n Is integer: true\n Is signed: true\n Number of digits: 31\n Number of digits 10: 9\n Max Number of digits 10: 0\n Min: -2147483648\n Lowest: -2147483648\n Max: 2147483647\n Size in bytes: 4\n Size in bits: 32\n\nNumeric limits for type: uint32_t\n------------------------------------------------------------\n Type: uint32_t\n Is integer: true\n Is signed: false\n Number of digits: 32\n Number of digits 10: 9\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 4294967295\n Size in bytes: 4\n Size in bits: 32\n\nNumeric limits for type: int64_t\n------------------------------------------------------------\n Type: int64_t\n Is integer: true\n Is signed: true\n Number of digits: 63\n Number of digits 10: 18\n Max Number of digits 10: 0\n Min: -9223372036854775808\n Lowest: -9223372036854775808\n Max: 9223372036854775807\n Size in bytes: 8\n Size in bits: 64\n\nNumeric limits for type: uint64_t\n------------------------------------------------------------\n Type: uint64_t\n Is integer: true\n Is signed: false\n Number of digits: 64\n Number of digits 10: 19\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 18446744073709551615\n Size in bytes: 8\n Size in bits: 64\n\nNumeric limits for type: short\n------------------------------------------------------------\n Type: short\n Is integer: true\n Is signed: true\n Number of digits: 15\n Number of digits 10: 4\n Max Number of digits 10: 0\n Min: -32768\n Lowest: -32768\n Max: 32767\n Size in bytes: 2\n Size in bits: 16\n\nNumeric limits for type: unsigned short\n------------------------------------------------------------\n Type: unsigned short\n Is integer: true\n Is signed: false\n Number of digits: 16\n Number of digits 10: 4\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 65535\n Size in bytes: 2\n Size in bits: 16\n\nNumeric limits for type: int\n------------------------------------------------------------\n Type: int\n Is integer: true\n Is signed: true\n Number of digits: 31\n Number of digits 10: 9\n Max Number of digits 10: 0\n Min: -2147483648\n Lowest: -2147483648\n Max: 2147483647\n Size in bytes: 4\n Size in bits: 32\n\nNumeric limits for type: unsigned int\n------------------------------------------------------------\n Type: unsigned int\n Is integer: true\n Is signed: false\n Number of digits: 32\n Number of digits 10: 9\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 4294967295\n Size in bytes: 4\n Size in bits: 32\n\nNumeric limits for type: long\n------------------------------------------------------------\n Type: long\n Is integer: true\n Is signed: true\n Number of digits: 63\n Number of digits 10: 18\n Max Number of digits 10: 0\n Min: -9223372036854775808\n Lowest: -9223372036854775808\n Max: 9223372036854775807\n Size in bytes: 8\n Size in bits: 64\n\nNumeric limits for type: unsigned long\n------------------------------------------------------------\n Type: unsigned long\n Is integer: true\n Is signed: false\n Number of digits: 64\n Number of digits 10: 19\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 18446744073709551615\n Size in bytes: 8\n Size in bits: 64\n\nNumeric limits for type: long long\n------------------------------------------------------------\n Type: long long\n Is integer: true\n Is signed: true\n Number of digits: 63\n Number of digits 10: 18\n Max Number of digits 10: 0\n Min: -9223372036854775808\n Lowest: -9223372036854775808\n Max: 9223372036854775807\n Size in bytes: 8\n Size in bits: 64\n\nNumeric limits for type: unsigned long long\n------------------------------------------------------------\n Type: unsigned long long\n Is integer: true\n Is signed: false\n Number of digits: 64\n Number of digits 10: 19\n Max Number of digits 10: 0\n Min: 0\n Lowest: 0\n Max: 18446744073709551615\n Size in bytes: 8\n Size in bits: 64\n\nNumeric limits for type: float\n------------------------------------------------------------\n Type: float\n Is integer: false\n Is signed: true\n Number of digits: 24\n Number of digits 10: 6\n Max Number of digits 10: 9\n Min: 1.17549e-38\n Lowest: -3.40282e+38\n Max: 3.40282e+38\n Size in bytes: 4\n Size in bits: 32\n\n Epsilon: 1.19209e-07\n Min exponent: -37\n Max exponent: 38\nNumeric limits for type: double\n------------------------------------------------------------\n Type: double\n Is integer: false\n Is signed: true\n Number of digits: 53\n Number of digits 10: 15\n Max Number of digits 10: 17\n Min: 2.22507e-308\n Lowest: -1.79769e+308\n Max: 1.79769e+308\n Size in bytes: 8\n Size in bits: 64\n\n Epsilon: 2.22045e-16\n Min exponent: -307\n Max exponent: 308\nNumeric limits for type: long double\n------------------------------------------------------------\n Type: long double\n Is integer: false\n Is signed: true\n Number of digits: 64\n Number of digits 10: 18\n Max Number of digits 10: 21\n Min: 3.3621e-4932\n Lowest: -1.18973e+4932\n Max: 1.18973e+4932\n Size in bytes: 16\n Size in bits: 128\n\n Epsilon: 1.0842e-19\n Min exponent: -4931\n Max exponent: 4932"
},
{
"code": null,
"e": 46683,
"s": 46669,
"text": "sumitgumber28"
},
{
"code": null,
"e": 46704,
"s": 46683,
"text": "cpp-numerics-library"
},
{
"code": null,
"e": 46708,
"s": 46704,
"text": "C++"
},
{
"code": null,
"e": 46721,
"s": 46708,
"text": "C++ Programs"
},
{
"code": null,
"e": 46725,
"s": 46721,
"text": "CPP"
},
{
"code": null,
"e": 46823,
"s": 46725,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46851,
"s": 46823,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 46871,
"s": 46851,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 46895,
"s": 46871,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 46928,
"s": 46895,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 46972,
"s": 46928,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 47007,
"s": 46972,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 47066,
"s": 47007,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 47092,
"s": 47066,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 47136,
"s": 47092,
"text": "Program to print ASCII Value of a character"
}
] |
ByteBuffer arrayOffset() method in Java with Examples - GeeksforGeeks
|
20 Sep, 2018
The arrayOffset() method of java.nio.ByteBuffer class is used to return the offset within the given buffer’s backing array of the first element of the buffer.
If this buffer is backed by an array then buffer position p corresponds to array index p + arrayOffset().
Invoke the hasArray method before invoking this method in order to ensure that this buffer has an accessible backing array.
Syntax :
public final int arrayOffset()
Return Value: This method returns the offset within this buffer’s array of the first element of the buffer
Exception:: This method throws the ReadOnlyBufferException, If this buffer is backed by an array but is read-only.
Below are the examples to illustrate the arrayOffset() method:
Example 1:
// Java program to demonstrate// arrayOffset() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); bb.rewind(); // print the ByteBuffer System.out.println("ByteBuffer: " + Arrays.toString(bb.array())); // print the arrayOffset System.out.println("arrayOffset: " + bb.arrayOffset()); } catch (IllegalArgumentException e) { System.out.println("IllegalArgumentException catched"); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws" + e); } }}
ByteBuffer: [20, 30, 40, 50]
arrayOffset: 0
Example 2:
// Java program to demonstrate// arrayOffset() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 3; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.rewind(); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); // print the ByteBuffer System.out.print("Read only buffer : "); while (bb1.hasRemaining()) System.out.print(bb1.get() + ", "); // next line System.out.println(""); // print the arrayOffset System.out.println("\nTry to print the array offset" + " of read only buffer"); System.out.println("arrayOffset: " + bb1.arrayOffset()); } catch (IllegalArgumentException e) { System.out.println("Exception throws: " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws: " + e); } }}
Read only buffer : 20, 30, 40,
Try to print the array offset of read only buffer
Exception throws: java.nio.ReadOnlyBufferException
Java-ByteBuffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n20 Sep, 2018"
},
{
"code": null,
"e": 24107,
"s": 23948,
"text": "The arrayOffset() method of java.nio.ByteBuffer class is used to return the offset within the given buffer’s backing array of the first element of the buffer."
},
{
"code": null,
"e": 24213,
"s": 24107,
"text": "If this buffer is backed by an array then buffer position p corresponds to array index p + arrayOffset()."
},
{
"code": null,
"e": 24337,
"s": 24213,
"text": "Invoke the hasArray method before invoking this method in order to ensure that this buffer has an accessible backing array."
},
{
"code": null,
"e": 24346,
"s": 24337,
"text": "Syntax :"
},
{
"code": null,
"e": 24377,
"s": 24346,
"text": "public final int arrayOffset()"
},
{
"code": null,
"e": 24484,
"s": 24377,
"text": "Return Value: This method returns the offset within this buffer’s array of the first element of the buffer"
},
{
"code": null,
"e": 24599,
"s": 24484,
"text": "Exception:: This method throws the ReadOnlyBufferException, If this buffer is backed by an array but is read-only."
},
{
"code": null,
"e": 24662,
"s": 24599,
"text": "Below are the examples to illustrate the arrayOffset() method:"
},
{
"code": null,
"e": 24673,
"s": 24662,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// arrayOffset() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); bb.rewind(); // print the ByteBuffer System.out.println(\"ByteBuffer: \" + Arrays.toString(bb.array())); // print the arrayOffset System.out.println(\"arrayOffset: \" + bb.arrayOffset()); } catch (IllegalArgumentException e) { System.out.println(\"IllegalArgumentException catched\"); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws\" + e); } }}",
"e": 25841,
"s": 24673,
"text": null
},
{
"code": null,
"e": 25886,
"s": 25841,
"text": "ByteBuffer: [20, 30, 40, 50]\narrayOffset: 0\n"
},
{
"code": null,
"e": 25897,
"s": 25886,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// arrayOffset() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 3; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.rewind(); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); // print the ByteBuffer System.out.print(\"Read only buffer : \"); while (bb1.hasRemaining()) System.out.print(bb1.get() + \", \"); // next line System.out.println(\"\"); // print the arrayOffset System.out.println(\"\\nTry to print the array offset\" + \" of read only buffer\"); System.out.println(\"arrayOffset: \" + bb1.arrayOffset()); } catch (IllegalArgumentException e) { System.out.println(\"Exception throws: \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws: \" + e); } }}",
"e": 27353,
"s": 25897,
"text": null
},
{
"code": null,
"e": 27488,
"s": 27353,
"text": "Read only buffer : 20, 30, 40, \n\nTry to print the array offset of read only buffer\nException throws: java.nio.ReadOnlyBufferException\n"
},
{
"code": null,
"e": 27504,
"s": 27488,
"text": "Java-ByteBuffer"
},
{
"code": null,
"e": 27519,
"s": 27504,
"text": "Java-Functions"
},
{
"code": null,
"e": 27536,
"s": 27519,
"text": "Java-NIO package"
},
{
"code": null,
"e": 27541,
"s": 27536,
"text": "Java"
},
{
"code": null,
"e": 27546,
"s": 27541,
"text": "Java"
},
{
"code": null,
"e": 27644,
"s": 27546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27659,
"s": 27644,
"text": "Stream In Java"
},
{
"code": null,
"e": 27680,
"s": 27659,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27726,
"s": 27680,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27745,
"s": 27726,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27775,
"s": 27745,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27792,
"s": 27775,
"text": "Generics in Java"
},
{
"code": null,
"e": 27835,
"s": 27792,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27856,
"s": 27835,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27885,
"s": 27856,
"text": "HashMap get() Method in Java"
}
] |
Insurance Risk Pricing — Tweedie Approach | by Ajay Tiwari | Towards Data Science
|
Insurance is a unique industry, probably one of the few where a company doesn’t know the actual cost of the product sold, they deal with the risks of unforeseeable events. Therefore, this industry has been relying on mathematics to understand the risk behavior of its customers and prospects for the last few centuries to estimate expected loss costs. Of course, methods have been evolving from Pascal’s triangle, application of probability, minimum bias procedures to generalized linear models and now machine learning.
We have discussed the count models (used in claim frequency) and the gamma model (used in claim severity) in previous articles in detail. The pure premium, also known as ‘loss cost’ is just the product of both the model estimates.
Claim Frequency = Claim Count / Exposure
Claim Severity = Claim Cost / Claim Count
Loss Cost = Claim Frequency x Claim Severity
In the current article, we are going to discuss a very important and interesting distribution called Tweedie, this distribution is interesting because it delivers many other distributions from Gaussian to inverse Gaussian by just changing a single parameter.
This distribution will help us in modeling pure premium directly without any need for two different models.
Tweedie distribution is a special case of exponential dispersion models and is often used as a distribution for generalized linear models. It can have a cluster of data items at zero and this particular property makes it useful for modeling claims in the insurance industry. This model can also be applied in other use cases across industries where you find a mixture of zeros and non-negative continuous data points.
If you see a histogram as below with a spike at zero, it’s a possible candidate to be fitted to a Tweedie model.
A mean, E(Y)= μ
A variance, Var(Y)= φμp
Let’s understand with this expression “Y ~ Twp(μ,φ)”, where Y denote the response variable, Twp(μ,φ) denotes a Tweedie random variable with mean μ and variance φμp and φ>0 and p ∈ (-∞,0 ] ∪[1,∞).
The p in the variance function is an additional shape parameter for the distribution.
An important point to be noted, this distribution is not defined for values of p between 0 and 1.
If 1< p <2, the distribution are continuous for Y>0, with a positive mass at Y=0
If p > 2, the distributions are continuous for Y > 0
Let’s look at Some of the commonly used members of the Tweedie family of distributions with their index parameter (p), variance function (V (μ)) and dispersion (ф)
One distribution enables fitting many other distributions. Setting p = 0 gives a normal distribution, p = 1 is Poisson, p = 2 gives a gamma distribution and p = 3 yields an inverse Gaussian.
We know Tweedie as a compound Poisson-Gamma distribution where a count N~Poisson(λ) and continuous number Z ~ Gamma(α,θ), in such case parameters can be easily translated into Tweedie parameters as given below:
Variance can also be translated — Var[Y] = φμp =λ⋅θ2 ⋅α (α+1)
Similarly, Tweedie parameters can also be converted into Poisson and Gamma parameters as follows:
Now, we got some understanding of this interesting distribution and its relation with its close family members like Poisson and Gamma.
Recall our insurance dataset which we used in previous articles. We are hoping Tweedie distribution is the ideal candidate for this dataset, let’s explore this data to confirm our assumption.
This dataset (dataCar)can be downloaded from an R package called “insuranceData”.
library(insuranceData)data(dataCar)
This dataset is based on one-year vehicle insurance policies taken out in 2004 or 2005. There are 67,856 policies, of which 4624 (6.8% notified claims) filed claims.
Only 7% of observation has positive values for the response variable, the rest of the values are zero. Let’s look at the distribution of claim count and cost independently.
As we have seen above
Loss Cost = Claim Frequency x Claim Severity
Let’s re-write in terms of original variables
Loss Cost = Claim Cost / Exposure
Response Variable — We are going to use ‘Claim Cost’ as a response variable keeping ‘exposure’ as an offset which is a suggested approach for modeling rates and averages.
Let’s have a look at the distribution of this variable.
We can see this data can not be fitted to the normal distribution, Poisson can also be discarded because this is not a count data. Another option we can think of Gamma, but this distribution does not take zero values. So, finally, we are left with Tweedie distribution which might be the best fit for this data.
Now, look at the independent variables. For detailed exploratory analysis and transformation of these variables, you can refer to the source code shared along with this article.
Independent Variables — We are going to use Vehicle body, vehicle age, driver’s age category, gender, area, and vehicle value as predictor variables. Claim occurrence indicator and the number of claims cannot be used as they are related to the dependent variable and can be known only after the event take place.
Derived Variable and Transformation — Vehicle body type by low frequencies can be grouped, also created an alternate categorical variable for vehicle value which can be tested for significance.
Based on this exploratory analysis, we can confirm Tweedie distribution is an ideal candidate for fitting the model, but we are yet to find an optimum value for “p” which we know varies between 1 to 2.
Approach 1 — Manual selection of the variance power.
Test a sequence of “p” between 1 to 2 by running iterative models.
The Log-likelihood shows an inverse “U” shape.
Select the “p” that corresponds to the “maximum” log-likelihood value.
Fit the final model using that “p” value.
Approach 2 — Automated selection of variance power using statistical packages
Statistical packages (macros) are available in various software such as R, SAS, Python, and Emblem (Industry-specific software) to calculate maximum likelihood estimate for a series of “p” value. These are a kind of improvement to approach 1 with many other added features such as visualization. We can see the sample output below in the form of a graph generated from R using the “Tweedie” package.
#Maximum likelihood estimation of the Tweedie index parameter pest_p <-tweedie.profile(claimcst0 ~ veh_value+veh_body+veh_age+ gender+area+agecat,data=training,link.power = 0,do.smooth = TRUE, do.plot = TRUE)#Notelink.power - Index of power link function, link.power=0 produces a log-linkdo.smooth - logical flag. If TRUE (the default), a spline is fitted to the data to smooth the profile likelihood plot. If FALSE, no smoothing is used (and the function is quicker)do.plot - logical flag. If TRUE, a plot of the profile likelihood is produce. If FALSE (the default), no plot is produced
This graph shows that optimum “p” values lie somewhere between 1.5 and 1.6. We can use the suggested value for fitting the Tweedie model.
In Python, statsmodels has a function called estimate_tweedie_power for obtaining an optimum value.
We are using R and Python for fitting the Generalized Linear Models. R is quite mature in statistical models, python is also catching up with its statsmodels package. I feel a lack of proper examples and documentation for statsmodels is the only disadvantage.
In machine learning models, the Tweedie loss function is available in many algorithms such as GBM, LightGBM, XGBOOST, etc. Here, I will walk you through XGBOOST implementation.
Implementation in R
library(tweedie)library(statmod)#Modeltweedie_model <- glm(claimcst0 ~ veh_value+veh_body+veh_age+gender+ area+agecat,data=training, family = tweedie(var.power=1.6, link. power=0),offset=log(exposure))#Notevar.power -index of power variance function, for Tweedie it ranges between 1 to 2, here we are using 1.6.link.power -index of power link function, link.power=0 produces a log-link
Implementation in Python, Statsmodels
import pandas as pdimport numpy as npfrom patsy import dmatricesimport statsmodels.api as sm# Training and test splitmask = np.random.rand(len(df3)) < 0.8df_train = df3[mask]df_test = df3[~mask]print('Training data set length='+str(len(df_train)))print('Testing data set length='+str(len(df_test)))# Model expressionexpr = """claimcst0 ~ veh_value_cat+veh_age+gender+area+agecat"""# Converting data into dmatricesy_train, X_train = dmatrices(expr,df_train,return_type='dataframe')y_test, X_test = dmatrices(expr, df_test, return_type='dataframe')# Training modeltweedie_model = sm.GLM(y_train, X_train,exposure=df_train.exposure, family=sm.families.Tweedie(link=None,var_power= 1.6,eql=True))tweedie_result = tweedie_model.fit()#Notelink - The default link for the Tweedie family is the log link. Available links are log and Powervar_power - The variance power. The default is 1eql - If True, the Extended Quasi-Likelihood is used, else the likelihood is used (however the latter is not implemented). If eql is True, var_power must be between 1 and 2.
Model validation and goodness of fit in GLMs
We can analyze the results like any other regression, by looking at the results summary.
If the p-value is less than or equal to the significance level, you can conclude that the variable is significant
Other metrics such as AIC, Deviance, and Loglikelihood are useful for comparing related models. Lower the AIC and Deviance, better the model, whereas a higher value of the likelihood is better.
import xgboost as xgbfrom sklearn.metrics import mean_squared_errorfrom sklearn.model_selection import train_test_split#Segregating response and predictor variables in different data frameX, y = data.iloc[:,:-1],data.iloc[:,-1]X_train, X_test, y_train, y_test = train_test_split (X,y,test_size =.2, random_state=123)#Creating DMatrix as required for this algorithmdtrain = xgb.DMatrix(data=X_train.iloc[:,1:28],label=y_train)dtest = xgb.DMatrix(data=X_test.iloc[:,1:28],label=y_test)#Applying offsetdtrain.set_base_margin(np.log(X_train['exposure']))dtest.set_base_margin(np.log(X_test['exposure']))#Setting Parametersparams = {"objective":"reg:tweedie",'colsample_bytree': 1.0, 'learning_rate': 0.01,'gamma':1.5,'max_depth': 2, 'subsample':0.6, 'reg_alpha': 0,'reg_lambda':1,'min_child_weight':5, 'n_estimators':2000,'tweedie_variance_power':1.6}xg_reg = xgb.train(params=params, dtrain=dtrain, num_boost_round=1000)#Notereg:tweedie - Tweedie regression with log-linktweedie_variance_power - default=1.5, range: (1,2)
Model validation in XGBOOST
Evaluation metrics like root mean squared error (rmse), mean absolute error (mae) and k-fold cross-validation techniques are some of the methods of validating and comparing the models.
preds = xg_reg.predict(dtest)rmse = np.sqrt(mean_squared_error(y_test, preds))print("RMSE: %f" % (rmse))
Please feel free to access complete code on my gist path.
We have discussed Tweedie distribution, one of the most commonly used distributions in the Insurance industry and its relation with other distributions of exponential dispersion models such as Poisson and Gamma. We also learned to estimate the Tweedie variance power which is the most important parameter required to fit an accurate model.
Though we discussed Tweedie implementation examples in some of the popular open-source packages, there are few more software that has this implementation which can be explored such as H2O, SAS, and Emblem.
Thanks for reading, hope you found the article informative. Please feel free to reach me for any queries or suggestions.
[1]Tweedie, M. C. K., “An Index which Distinguishes between Some Important Exponential Families,” in Statistics: Applications and New Directions, Proceedings of the Indian Statistical Golden Jubilee International Conference, J. K. Ghosh and J. Roy (Eds.), Indian Statistical Institute, 1984, 579–604
|
[
{
"code": null,
"e": 568,
"s": 47,
"text": "Insurance is a unique industry, probably one of the few where a company doesn’t know the actual cost of the product sold, they deal with the risks of unforeseeable events. Therefore, this industry has been relying on mathematics to understand the risk behavior of its customers and prospects for the last few centuries to estimate expected loss costs. Of course, methods have been evolving from Pascal’s triangle, application of probability, minimum bias procedures to generalized linear models and now machine learning."
},
{
"code": null,
"e": 799,
"s": 568,
"text": "We have discussed the count models (used in claim frequency) and the gamma model (used in claim severity) in previous articles in detail. The pure premium, also known as ‘loss cost’ is just the product of both the model estimates."
},
{
"code": null,
"e": 840,
"s": 799,
"text": "Claim Frequency = Claim Count / Exposure"
},
{
"code": null,
"e": 882,
"s": 840,
"text": "Claim Severity = Claim Cost / Claim Count"
},
{
"code": null,
"e": 927,
"s": 882,
"text": "Loss Cost = Claim Frequency x Claim Severity"
},
{
"code": null,
"e": 1186,
"s": 927,
"text": "In the current article, we are going to discuss a very important and interesting distribution called Tweedie, this distribution is interesting because it delivers many other distributions from Gaussian to inverse Gaussian by just changing a single parameter."
},
{
"code": null,
"e": 1294,
"s": 1186,
"text": "This distribution will help us in modeling pure premium directly without any need for two different models."
},
{
"code": null,
"e": 1712,
"s": 1294,
"text": "Tweedie distribution is a special case of exponential dispersion models and is often used as a distribution for generalized linear models. It can have a cluster of data items at zero and this particular property makes it useful for modeling claims in the insurance industry. This model can also be applied in other use cases across industries where you find a mixture of zeros and non-negative continuous data points."
},
{
"code": null,
"e": 1825,
"s": 1712,
"text": "If you see a histogram as below with a spike at zero, it’s a possible candidate to be fitted to a Tweedie model."
},
{
"code": null,
"e": 1841,
"s": 1825,
"text": "A mean, E(Y)= μ"
},
{
"code": null,
"e": 1865,
"s": 1841,
"text": "A variance, Var(Y)= φμp"
},
{
"code": null,
"e": 2061,
"s": 1865,
"text": "Let’s understand with this expression “Y ~ Twp(μ,φ)”, where Y denote the response variable, Twp(μ,φ) denotes a Tweedie random variable with mean μ and variance φμp and φ>0 and p ∈ (-∞,0 ] ∪[1,∞)."
},
{
"code": null,
"e": 2147,
"s": 2061,
"text": "The p in the variance function is an additional shape parameter for the distribution."
},
{
"code": null,
"e": 2245,
"s": 2147,
"text": "An important point to be noted, this distribution is not defined for values of p between 0 and 1."
},
{
"code": null,
"e": 2326,
"s": 2245,
"text": "If 1< p <2, the distribution are continuous for Y>0, with a positive mass at Y=0"
},
{
"code": null,
"e": 2379,
"s": 2326,
"text": "If p > 2, the distributions are continuous for Y > 0"
},
{
"code": null,
"e": 2543,
"s": 2379,
"text": "Let’s look at Some of the commonly used members of the Tweedie family of distributions with their index parameter (p), variance function (V (μ)) and dispersion (ф)"
},
{
"code": null,
"e": 2734,
"s": 2543,
"text": "One distribution enables fitting many other distributions. Setting p = 0 gives a normal distribution, p = 1 is Poisson, p = 2 gives a gamma distribution and p = 3 yields an inverse Gaussian."
},
{
"code": null,
"e": 2945,
"s": 2734,
"text": "We know Tweedie as a compound Poisson-Gamma distribution where a count N~Poisson(λ) and continuous number Z ~ Gamma(α,θ), in such case parameters can be easily translated into Tweedie parameters as given below:"
},
{
"code": null,
"e": 3007,
"s": 2945,
"text": "Variance can also be translated — Var[Y] = φμp =λ⋅θ2 ⋅α (α+1)"
},
{
"code": null,
"e": 3105,
"s": 3007,
"text": "Similarly, Tweedie parameters can also be converted into Poisson and Gamma parameters as follows:"
},
{
"code": null,
"e": 3240,
"s": 3105,
"text": "Now, we got some understanding of this interesting distribution and its relation with its close family members like Poisson and Gamma."
},
{
"code": null,
"e": 3432,
"s": 3240,
"text": "Recall our insurance dataset which we used in previous articles. We are hoping Tweedie distribution is the ideal candidate for this dataset, let’s explore this data to confirm our assumption."
},
{
"code": null,
"e": 3514,
"s": 3432,
"text": "This dataset (dataCar)can be downloaded from an R package called “insuranceData”."
},
{
"code": null,
"e": 3550,
"s": 3514,
"text": "library(insuranceData)data(dataCar)"
},
{
"code": null,
"e": 3716,
"s": 3550,
"text": "This dataset is based on one-year vehicle insurance policies taken out in 2004 or 2005. There are 67,856 policies, of which 4624 (6.8% notified claims) filed claims."
},
{
"code": null,
"e": 3889,
"s": 3716,
"text": "Only 7% of observation has positive values for the response variable, the rest of the values are zero. Let’s look at the distribution of claim count and cost independently."
},
{
"code": null,
"e": 3911,
"s": 3889,
"text": "As we have seen above"
},
{
"code": null,
"e": 3956,
"s": 3911,
"text": "Loss Cost = Claim Frequency x Claim Severity"
},
{
"code": null,
"e": 4002,
"s": 3956,
"text": "Let’s re-write in terms of original variables"
},
{
"code": null,
"e": 4036,
"s": 4002,
"text": "Loss Cost = Claim Cost / Exposure"
},
{
"code": null,
"e": 4207,
"s": 4036,
"text": "Response Variable — We are going to use ‘Claim Cost’ as a response variable keeping ‘exposure’ as an offset which is a suggested approach for modeling rates and averages."
},
{
"code": null,
"e": 4263,
"s": 4207,
"text": "Let’s have a look at the distribution of this variable."
},
{
"code": null,
"e": 4575,
"s": 4263,
"text": "We can see this data can not be fitted to the normal distribution, Poisson can also be discarded because this is not a count data. Another option we can think of Gamma, but this distribution does not take zero values. So, finally, we are left with Tweedie distribution which might be the best fit for this data."
},
{
"code": null,
"e": 4753,
"s": 4575,
"text": "Now, look at the independent variables. For detailed exploratory analysis and transformation of these variables, you can refer to the source code shared along with this article."
},
{
"code": null,
"e": 5066,
"s": 4753,
"text": "Independent Variables — We are going to use Vehicle body, vehicle age, driver’s age category, gender, area, and vehicle value as predictor variables. Claim occurrence indicator and the number of claims cannot be used as they are related to the dependent variable and can be known only after the event take place."
},
{
"code": null,
"e": 5260,
"s": 5066,
"text": "Derived Variable and Transformation — Vehicle body type by low frequencies can be grouped, also created an alternate categorical variable for vehicle value which can be tested for significance."
},
{
"code": null,
"e": 5462,
"s": 5260,
"text": "Based on this exploratory analysis, we can confirm Tweedie distribution is an ideal candidate for fitting the model, but we are yet to find an optimum value for “p” which we know varies between 1 to 2."
},
{
"code": null,
"e": 5515,
"s": 5462,
"text": "Approach 1 — Manual selection of the variance power."
},
{
"code": null,
"e": 5582,
"s": 5515,
"text": "Test a sequence of “p” between 1 to 2 by running iterative models."
},
{
"code": null,
"e": 5629,
"s": 5582,
"text": "The Log-likelihood shows an inverse “U” shape."
},
{
"code": null,
"e": 5700,
"s": 5629,
"text": "Select the “p” that corresponds to the “maximum” log-likelihood value."
},
{
"code": null,
"e": 5742,
"s": 5700,
"text": "Fit the final model using that “p” value."
},
{
"code": null,
"e": 5820,
"s": 5742,
"text": "Approach 2 — Automated selection of variance power using statistical packages"
},
{
"code": null,
"e": 6220,
"s": 5820,
"text": "Statistical packages (macros) are available in various software such as R, SAS, Python, and Emblem (Industry-specific software) to calculate maximum likelihood estimate for a series of “p” value. These are a kind of improvement to approach 1 with many other added features such as visualization. We can see the sample output below in the form of a graph generated from R using the “Tweedie” package."
},
{
"code": null,
"e": 6809,
"s": 6220,
"text": "#Maximum likelihood estimation of the Tweedie index parameter pest_p <-tweedie.profile(claimcst0 ~ veh_value+veh_body+veh_age+ gender+area+agecat,data=training,link.power = 0,do.smooth = TRUE, do.plot = TRUE)#Notelink.power - Index of power link function, link.power=0 produces a log-linkdo.smooth - logical flag. If TRUE (the default), a spline is fitted to the data to smooth the profile likelihood plot. If FALSE, no smoothing is used (and the function is quicker)do.plot - logical flag. If TRUE, a plot of the profile likelihood is produce. If FALSE (the default), no plot is produced"
},
{
"code": null,
"e": 6947,
"s": 6809,
"text": "This graph shows that optimum “p” values lie somewhere between 1.5 and 1.6. We can use the suggested value for fitting the Tweedie model."
},
{
"code": null,
"e": 7047,
"s": 6947,
"text": "In Python, statsmodels has a function called estimate_tweedie_power for obtaining an optimum value."
},
{
"code": null,
"e": 7307,
"s": 7047,
"text": "We are using R and Python for fitting the Generalized Linear Models. R is quite mature in statistical models, python is also catching up with its statsmodels package. I feel a lack of proper examples and documentation for statsmodels is the only disadvantage."
},
{
"code": null,
"e": 7484,
"s": 7307,
"text": "In machine learning models, the Tweedie loss function is available in many algorithms such as GBM, LightGBM, XGBOOST, etc. Here, I will walk you through XGBOOST implementation."
},
{
"code": null,
"e": 7504,
"s": 7484,
"text": "Implementation in R"
},
{
"code": null,
"e": 7890,
"s": 7504,
"text": "library(tweedie)library(statmod)#Modeltweedie_model <- glm(claimcst0 ~ veh_value+veh_body+veh_age+gender+ area+agecat,data=training, family = tweedie(var.power=1.6, link. power=0),offset=log(exposure))#Notevar.power -index of power variance function, for Tweedie it ranges between 1 to 2, here we are using 1.6.link.power -index of power link function, link.power=0 produces a log-link"
},
{
"code": null,
"e": 7928,
"s": 7890,
"text": "Implementation in Python, Statsmodels"
},
{
"code": null,
"e": 8980,
"s": 7928,
"text": "import pandas as pdimport numpy as npfrom patsy import dmatricesimport statsmodels.api as sm# Training and test splitmask = np.random.rand(len(df3)) < 0.8df_train = df3[mask]df_test = df3[~mask]print('Training data set length='+str(len(df_train)))print('Testing data set length='+str(len(df_test)))# Model expressionexpr = \"\"\"claimcst0 ~ veh_value_cat+veh_age+gender+area+agecat\"\"\"# Converting data into dmatricesy_train, X_train = dmatrices(expr,df_train,return_type='dataframe')y_test, X_test = dmatrices(expr, df_test, return_type='dataframe')# Training modeltweedie_model = sm.GLM(y_train, X_train,exposure=df_train.exposure, family=sm.families.Tweedie(link=None,var_power= 1.6,eql=True))tweedie_result = tweedie_model.fit()#Notelink - The default link for the Tweedie family is the log link. Available links are log and Powervar_power - The variance power. The default is 1eql - If True, the Extended Quasi-Likelihood is used, else the likelihood is used (however the latter is not implemented). If eql is True, var_power must be between 1 and 2."
},
{
"code": null,
"e": 9025,
"s": 8980,
"text": "Model validation and goodness of fit in GLMs"
},
{
"code": null,
"e": 9114,
"s": 9025,
"text": "We can analyze the results like any other regression, by looking at the results summary."
},
{
"code": null,
"e": 9228,
"s": 9114,
"text": "If the p-value is less than or equal to the significance level, you can conclude that the variable is significant"
},
{
"code": null,
"e": 9422,
"s": 9228,
"text": "Other metrics such as AIC, Deviance, and Loglikelihood are useful for comparing related models. Lower the AIC and Deviance, better the model, whereas a higher value of the likelihood is better."
},
{
"code": null,
"e": 10441,
"s": 9422,
"text": "import xgboost as xgbfrom sklearn.metrics import mean_squared_errorfrom sklearn.model_selection import train_test_split#Segregating response and predictor variables in different data frameX, y = data.iloc[:,:-1],data.iloc[:,-1]X_train, X_test, y_train, y_test = train_test_split (X,y,test_size =.2, random_state=123)#Creating DMatrix as required for this algorithmdtrain = xgb.DMatrix(data=X_train.iloc[:,1:28],label=y_train)dtest = xgb.DMatrix(data=X_test.iloc[:,1:28],label=y_test)#Applying offsetdtrain.set_base_margin(np.log(X_train['exposure']))dtest.set_base_margin(np.log(X_test['exposure']))#Setting Parametersparams = {\"objective\":\"reg:tweedie\",'colsample_bytree': 1.0, 'learning_rate': 0.01,'gamma':1.5,'max_depth': 2, 'subsample':0.6, 'reg_alpha': 0,'reg_lambda':1,'min_child_weight':5, 'n_estimators':2000,'tweedie_variance_power':1.6}xg_reg = xgb.train(params=params, dtrain=dtrain, num_boost_round=1000)#Notereg:tweedie - Tweedie regression with log-linktweedie_variance_power - default=1.5, range: (1,2)"
},
{
"code": null,
"e": 10469,
"s": 10441,
"text": "Model validation in XGBOOST"
},
{
"code": null,
"e": 10654,
"s": 10469,
"text": "Evaluation metrics like root mean squared error (rmse), mean absolute error (mae) and k-fold cross-validation techniques are some of the methods of validating and comparing the models."
},
{
"code": null,
"e": 10759,
"s": 10654,
"text": "preds = xg_reg.predict(dtest)rmse = np.sqrt(mean_squared_error(y_test, preds))print(\"RMSE: %f\" % (rmse))"
},
{
"code": null,
"e": 10817,
"s": 10759,
"text": "Please feel free to access complete code on my gist path."
},
{
"code": null,
"e": 11157,
"s": 10817,
"text": "We have discussed Tweedie distribution, one of the most commonly used distributions in the Insurance industry and its relation with other distributions of exponential dispersion models such as Poisson and Gamma. We also learned to estimate the Tweedie variance power which is the most important parameter required to fit an accurate model."
},
{
"code": null,
"e": 11363,
"s": 11157,
"text": "Though we discussed Tweedie implementation examples in some of the popular open-source packages, there are few more software that has this implementation which can be explored such as H2O, SAS, and Emblem."
},
{
"code": null,
"e": 11484,
"s": 11363,
"text": "Thanks for reading, hope you found the article informative. Please feel free to reach me for any queries or suggestions."
}
] |
Keyword Extraction with BERT | Towards Data Science
|
When we want to understand key information from specific documents, we typically turn towards keyword extraction. Keyword extraction is the automated process of extracting the words and phrases that are most relevant to an input text.
With methods such as Rake and YAKE! we already have easy-to-use packages that can be used to extract keywords and keyphrases. However, these models typically work based on the statistical properties of a text and not so much on semantic similarity.
In comes BERT. BERT is a bi-directional transformer model that allows us to transform phrases and documents to vectors that capture their meaning.
What if we were to use BERT instead of statistical models?
Although there are many great papers and solutions out there that use BERT-embeddings (e.g., 1, 2, 3, ), I could not find a simple and easy-to-use BERT-based solution. Instead, I decide to create KeyBERT a minimal and easy-to-use keyword extraction technique that leverages BERT embeddings.
Now, the main topic of this article will not be the use of KeyBERT but a tutorial on how to use BERT to create your own keyword extraction model.
For this tutorial, we are going to be using a document about supervised machine learning:
doc = """ Supervised learning is the machine learning task of learning a function that maps an input to an output based on example input-output pairs.[1] It infers a function from labeled training data consisting of a set of training examples.[2] In supervised learning, each example is a pair consisting of an input object (typically a vector) and a desired output value (also called the supervisory signal). A supervised learning algorithm analyzes the training data and produces an inferred function, which can be used for mapping new examples. An optimal scenario will allow for the algorithm to correctly determine the class labels for unseen instances. This requires the learning algorithm to generalize from the training data to unseen situations in a 'reasonable' way (see inductive bias). """
I believe that using a document about a topic that the readers know quite a bit about helps you understand if the resulting keyphrases are of quality.
We start by creating a list of candidate keywords or keyphrases from a document. Although many focus on noun phrases, we are going to keep it simple by using Scikit-Learns CountVectorizer. This allows us to specify the length of the keywords and make them into keyphrases. It also is a nice method for quickly removing stop words.
We can use n_gram_range to change the size of the resulting candidates. For example, if we would set it to (3, 3) then the resulting candidates would phrases that include 3 keywords.
Then, the variable candidates is simply a list of strings that includes our candidate keywords/keyphrases.
NOTE: You can play around with n_gram_range to create different lengths of keyphrases. Then, you might not want to remove stop_words as they can tie longer keyphrases together.
Next, we convert both the document as well as the candidate keywords/keyphrases to numerical data. We use BERT for this purpose as it has shown great results for both similarity- and paraphrasing tasks.
There are many methods for generating the BERT embeddings, such as Flair, Hugginface Transformers, and now even spaCy with their 3.0 release! However, I prefer to use the sentence-transformers package as it allows me to quickly create high-quality embeddings that work quite well for sentence- and document-level embeddings.
We install the package with pip install sentence-transformers. If you run into issues installing this package, then it might be helpful to install Pytorch first.
Now, we are going to run the following code to transform our document and candidates into vectors:
We are Distilbert as it has shown great performance in similarity tasks, which is what we are aiming for with keyword/keyphrase extraction!
Since transformer models have a token limit, you might run into some errors when inputting large documents. In that case, you could consider splitting up your document into paragraphs and mean pooling (taking the average of) the resulting vectors.
NOTE: There are many pre-trained BERT-based models that you can use for keyword extraction. However, I would advise you to use either distilbert — base-nli-stsb-mean-tokens or xlm-r-distilroberta-base-paraphase-v1 as they have shown great performance in semantic similarity and paraphrase identification respectively.
In the final step, we want to find the candidates that are most similar to the document. We assume that the most similar candidates to the document are good keywords/keyphrases for representing the document.
To calculate the similarity between candidates and the document, we will be using the cosine similarity between vectors as it performs quite well in high-dimensionality:
And...that is it! We take the top 5 most similar candidates to the input document as the resulting keywords:
The results look great! These terms definitely look like they describe a document about supervised machine learning.
Now, let us take a look at what happens if we change the n_gram_range to (3,3):
It seems that we get keyphrases instead of keywords now! These keyphrases, by themselves, seem to nicely represent the document. However, I am not happy that all keyphrases are so similar to each other.
To solve this issue, let us take a look at the diversification of our results.
There is a reason why similar results are returned... they best represent the document! If we were to diversify the keywords/keyphrases then they are less likely to represent the document well as a collective.
Thus, the diversification of our results requires a delicate balance between the accuracy of keywords/keyphrases and the diversity between them.
There are two algorithms that we will be using to diversify our results:
Max Sum Similarity
Maximal Marginal Relevance
The maximum sum distance between pairs of data is defined as the pairs of data for which the distance between them is maximized. In our case, we want to maximize the candidate similarity to the document whilst minimizing the similarity between candidates.
To do this, we select the top 20 keywords/keyphrases, and from those 20, select the 5 that are the least similar to each other:
If we set a low nr_candidates, then our results seem to be very similar to our original cosine similarity method:
However, a relatively high nr_candidates will create more diverse keyphrases:
As mentioned before, there is a tradeoff between accuracy and diversity that you must keep in mind. If you increase the nr_candidates, then there is a good chance you get very diverse keywords but that are not very good representations of the document.
I would advise you to keep nr_candidates less than 20% of the total number of unique words in your document.
The final method for diversifying our results is Maximal Marginal Relevance (MMR). MMR tries to minimize redundancy and maximize the diversity of results in text summarization tasks. Fortunately, a keyword extraction algorithm called EmbedRank has implemented a version of MMR that allows us to use it for diversifying our keywords/keyphrases.
We start by selecting the keyword/keyphrase that is the most similar to the document. Then, we iteratively select new candidates that are both similar to the document and not similar to the already selected keywords/keyphrases:
If we set a relatively low diversity, then our results seem to be very similar to our original cosine similarity method:
However, a relatively high diversity score will create very diverse keyphrases:
If you are, like me, passionate about AI, Data Science, or Psychology, please feel free to add me on LinkedIn or follow me on Twitter.
All examples and code in this article can be found here:
|
[
{
"code": null,
"e": 407,
"s": 172,
"text": "When we want to understand key information from specific documents, we typically turn towards keyword extraction. Keyword extraction is the automated process of extracting the words and phrases that are most relevant to an input text."
},
{
"code": null,
"e": 656,
"s": 407,
"text": "With methods such as Rake and YAKE! we already have easy-to-use packages that can be used to extract keywords and keyphrases. However, these models typically work based on the statistical properties of a text and not so much on semantic similarity."
},
{
"code": null,
"e": 803,
"s": 656,
"text": "In comes BERT. BERT is a bi-directional transformer model that allows us to transform phrases and documents to vectors that capture their meaning."
},
{
"code": null,
"e": 862,
"s": 803,
"text": "What if we were to use BERT instead of statistical models?"
},
{
"code": null,
"e": 1153,
"s": 862,
"text": "Although there are many great papers and solutions out there that use BERT-embeddings (e.g., 1, 2, 3, ), I could not find a simple and easy-to-use BERT-based solution. Instead, I decide to create KeyBERT a minimal and easy-to-use keyword extraction technique that leverages BERT embeddings."
},
{
"code": null,
"e": 1299,
"s": 1153,
"text": "Now, the main topic of this article will not be the use of KeyBERT but a tutorial on how to use BERT to create your own keyword extraction model."
},
{
"code": null,
"e": 1389,
"s": 1299,
"text": "For this tutorial, we are going to be using a document about supervised machine learning:"
},
{
"code": null,
"e": 2331,
"s": 1389,
"text": "doc = \"\"\" Supervised learning is the machine learning task of learning a function that maps an input to an output based on example input-output pairs.[1] It infers a function from labeled training data consisting of a set of training examples.[2] In supervised learning, each example is a pair consisting of an input object (typically a vector) and a desired output value (also called the supervisory signal). A supervised learning algorithm analyzes the training data and produces an inferred function, which can be used for mapping new examples. An optimal scenario will allow for the algorithm to correctly determine the class labels for unseen instances. This requires the learning algorithm to generalize from the training data to unseen situations in a 'reasonable' way (see inductive bias). \"\"\""
},
{
"code": null,
"e": 2482,
"s": 2331,
"text": "I believe that using a document about a topic that the readers know quite a bit about helps you understand if the resulting keyphrases are of quality."
},
{
"code": null,
"e": 2813,
"s": 2482,
"text": "We start by creating a list of candidate keywords or keyphrases from a document. Although many focus on noun phrases, we are going to keep it simple by using Scikit-Learns CountVectorizer. This allows us to specify the length of the keywords and make them into keyphrases. It also is a nice method for quickly removing stop words."
},
{
"code": null,
"e": 2996,
"s": 2813,
"text": "We can use n_gram_range to change the size of the resulting candidates. For example, if we would set it to (3, 3) then the resulting candidates would phrases that include 3 keywords."
},
{
"code": null,
"e": 3103,
"s": 2996,
"text": "Then, the variable candidates is simply a list of strings that includes our candidate keywords/keyphrases."
},
{
"code": null,
"e": 3280,
"s": 3103,
"text": "NOTE: You can play around with n_gram_range to create different lengths of keyphrases. Then, you might not want to remove stop_words as they can tie longer keyphrases together."
},
{
"code": null,
"e": 3483,
"s": 3280,
"text": "Next, we convert both the document as well as the candidate keywords/keyphrases to numerical data. We use BERT for this purpose as it has shown great results for both similarity- and paraphrasing tasks."
},
{
"code": null,
"e": 3808,
"s": 3483,
"text": "There are many methods for generating the BERT embeddings, such as Flair, Hugginface Transformers, and now even spaCy with their 3.0 release! However, I prefer to use the sentence-transformers package as it allows me to quickly create high-quality embeddings that work quite well for sentence- and document-level embeddings."
},
{
"code": null,
"e": 3970,
"s": 3808,
"text": "We install the package with pip install sentence-transformers. If you run into issues installing this package, then it might be helpful to install Pytorch first."
},
{
"code": null,
"e": 4069,
"s": 3970,
"text": "Now, we are going to run the following code to transform our document and candidates into vectors:"
},
{
"code": null,
"e": 4209,
"s": 4069,
"text": "We are Distilbert as it has shown great performance in similarity tasks, which is what we are aiming for with keyword/keyphrase extraction!"
},
{
"code": null,
"e": 4457,
"s": 4209,
"text": "Since transformer models have a token limit, you might run into some errors when inputting large documents. In that case, you could consider splitting up your document into paragraphs and mean pooling (taking the average of) the resulting vectors."
},
{
"code": null,
"e": 4775,
"s": 4457,
"text": "NOTE: There are many pre-trained BERT-based models that you can use for keyword extraction. However, I would advise you to use either distilbert — base-nli-stsb-mean-tokens or xlm-r-distilroberta-base-paraphase-v1 as they have shown great performance in semantic similarity and paraphrase identification respectively."
},
{
"code": null,
"e": 4983,
"s": 4775,
"text": "In the final step, we want to find the candidates that are most similar to the document. We assume that the most similar candidates to the document are good keywords/keyphrases for representing the document."
},
{
"code": null,
"e": 5153,
"s": 4983,
"text": "To calculate the similarity between candidates and the document, we will be using the cosine similarity between vectors as it performs quite well in high-dimensionality:"
},
{
"code": null,
"e": 5262,
"s": 5153,
"text": "And...that is it! We take the top 5 most similar candidates to the input document as the resulting keywords:"
},
{
"code": null,
"e": 5379,
"s": 5262,
"text": "The results look great! These terms definitely look like they describe a document about supervised machine learning."
},
{
"code": null,
"e": 5459,
"s": 5379,
"text": "Now, let us take a look at what happens if we change the n_gram_range to (3,3):"
},
{
"code": null,
"e": 5662,
"s": 5459,
"text": "It seems that we get keyphrases instead of keywords now! These keyphrases, by themselves, seem to nicely represent the document. However, I am not happy that all keyphrases are so similar to each other."
},
{
"code": null,
"e": 5741,
"s": 5662,
"text": "To solve this issue, let us take a look at the diversification of our results."
},
{
"code": null,
"e": 5951,
"s": 5741,
"text": "There is a reason why similar results are returned... they best represent the document! If we were to diversify the keywords/keyphrases then they are less likely to represent the document well as a collective."
},
{
"code": null,
"e": 6096,
"s": 5951,
"text": "Thus, the diversification of our results requires a delicate balance between the accuracy of keywords/keyphrases and the diversity between them."
},
{
"code": null,
"e": 6169,
"s": 6096,
"text": "There are two algorithms that we will be using to diversify our results:"
},
{
"code": null,
"e": 6188,
"s": 6169,
"text": "Max Sum Similarity"
},
{
"code": null,
"e": 6215,
"s": 6188,
"text": "Maximal Marginal Relevance"
},
{
"code": null,
"e": 6471,
"s": 6215,
"text": "The maximum sum distance between pairs of data is defined as the pairs of data for which the distance between them is maximized. In our case, we want to maximize the candidate similarity to the document whilst minimizing the similarity between candidates."
},
{
"code": null,
"e": 6599,
"s": 6471,
"text": "To do this, we select the top 20 keywords/keyphrases, and from those 20, select the 5 that are the least similar to each other:"
},
{
"code": null,
"e": 6713,
"s": 6599,
"text": "If we set a low nr_candidates, then our results seem to be very similar to our original cosine similarity method:"
},
{
"code": null,
"e": 6791,
"s": 6713,
"text": "However, a relatively high nr_candidates will create more diverse keyphrases:"
},
{
"code": null,
"e": 7044,
"s": 6791,
"text": "As mentioned before, there is a tradeoff between accuracy and diversity that you must keep in mind. If you increase the nr_candidates, then there is a good chance you get very diverse keywords but that are not very good representations of the document."
},
{
"code": null,
"e": 7153,
"s": 7044,
"text": "I would advise you to keep nr_candidates less than 20% of the total number of unique words in your document."
},
{
"code": null,
"e": 7497,
"s": 7153,
"text": "The final method for diversifying our results is Maximal Marginal Relevance (MMR). MMR tries to minimize redundancy and maximize the diversity of results in text summarization tasks. Fortunately, a keyword extraction algorithm called EmbedRank has implemented a version of MMR that allows us to use it for diversifying our keywords/keyphrases."
},
{
"code": null,
"e": 7725,
"s": 7497,
"text": "We start by selecting the keyword/keyphrase that is the most similar to the document. Then, we iteratively select new candidates that are both similar to the document and not similar to the already selected keywords/keyphrases:"
},
{
"code": null,
"e": 7846,
"s": 7725,
"text": "If we set a relatively low diversity, then our results seem to be very similar to our original cosine similarity method:"
},
{
"code": null,
"e": 7926,
"s": 7846,
"text": "However, a relatively high diversity score will create very diverse keyphrases:"
},
{
"code": null,
"e": 8061,
"s": 7926,
"text": "If you are, like me, passionate about AI, Data Science, or Psychology, please feel free to add me on LinkedIn or follow me on Twitter."
}
] |
What is Dynamic Polymorphism in C#?
|
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
Dynamic polymorphism is implemented by abstract classes and virtual functions. The following is an example showing an example of dynamic polymorphism −
Live Demo
using System;
namespace PolymorphismApplication {
class Shape {
protected int width, height;
public Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
public virtual int area() {
Console.WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape {
public Rectangle( int a = 0, int b = 0): base(a, b) {}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape {
public Triangle(int a = 0, int b = 0): base(a, b) {}
public override int area() {
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller {
public void CallArea(Shape sh) {
int a;
a = sh.area();
Console.WriteLine("Area: {0}", a);
}
}
class Tester {
static void Main(string[] args) {
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}
}
Rectangle class area :
Area: 70
Triangle class area :
Area: 25
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time."
},
{
"code": null,
"e": 1391,
"s": 1239,
"text": "Dynamic polymorphism is implemented by abstract classes and virtual functions. The following is an example showing an example of dynamic polymorphism −"
},
{
"code": null,
"e": 1402,
"s": 1391,
"text": " Live Demo"
},
{
"code": null,
"e": 2599,
"s": 1402,
"text": "using System;\n\nnamespace PolymorphismApplication {\n class Shape {\n protected int width, height;\n\n public Shape( int a = 0, int b = 0) {\n width = a;\n height = b;\n }\n\n public virtual int area() {\n Console.WriteLine(\"Parent class area :\");\n return 0;\n }\n }\n\n class Rectangle: Shape {\n public Rectangle( int a = 0, int b = 0): base(a, b) {}\n\n public override int area () {\n Console.WriteLine(\"Rectangle class area :\");\n return (width * height);\n }\n }\n\n class Triangle: Shape {\n public Triangle(int a = 0, int b = 0): base(a, b) {}\n public override int area() {\n Console.WriteLine(\"Triangle class area :\");\n return (width * height / 2);\n }\n }\n\n class Caller {\n public void CallArea(Shape sh) {\n int a;\n a = sh.area();\n Console.WriteLine(\"Area: {0}\", a);\n }\n }\n\n class Tester {\n static void Main(string[] args) {\n Caller c = new Caller();\n Rectangle r = new Rectangle(10, 7);\n Triangle t = new Triangle(10, 5);\n\n c.CallArea(r);\n c.CallArea(t);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2662,
"s": 2599,
"text": "Rectangle class area :\nArea: 70\nTriangle class area :\nArea: 25"
}
] |
Excel Ranges
|
Range is an important part of Excel because it allows you to work with selections of cells.
There are four different operations for selection;
Selecting a cell
Selecting multiple cells
Selecting a column
Selecting a row
Before having a look at the different operations for selection, we will introduce the Name Box.
The Name Box shows you the reference of which cell or range you have selected. It can also be used to select cells or ranges by typing their values.
You will learn more about the Name Box later in this chapter.
Cells are selected by clicking them with the left mouse button or by navigating to them with the keyboard arrows.
It is easiest to use the mouse to select cells.
To select cell A1, click on it:
More than one cell can be selected by pressing and holding down CTRL or Command and left clicking the cells. Once finished with selecting, you can let go of CTRL or Command.
Lets try an example: Select the cells A1, A7, C1, C7 and B4.
Did it look like the picture below?
Columns are selected by left clicking it. This will select all cells in the sheet related to the column.
To select column A, click on the letter A in the column bar:
Rows are selected by left clicking it. This will select all the cells in the sheet related to that row.
To select row 1, click on its number in the row bar:
The entire spreadsheet can be selected by clicking the triangle in the top-left corner of the spreadsheet:
Now, the whole spreadsheet is selected:
Note: You can also select the entire spreadsheet by pressing Ctrl+A for Windows, or Cmd+A for MacOS.
Selection of cell ranges has many use areas and it is one of the most important concepts of Excel. Do not think too much about how it is used with values. You will learn about this in a later chapter. For now let's focus on how to select ranges.
There are two ways to select a range of cells
Name Box
Drag to mark a range.
Name Box
Drag to mark a range.
The easiest way is drag and mark. Let's keep it simple and start there.
How to drag and mark a range, step-by-step:
Select a cell
Left click it and hold the mouse button down
Move your mouse pointer over the range that you want selected. The range that is marked will turn grey.
Let go of the mouse button when you have marked the range
Select a cell
Left click it and hold the mouse button down
Move your mouse pointer over the range that you want selected. The range that is marked will turn grey.
Let go of the mouse button when you have marked the range
Let's have a look at an example for how to mark the range A1:E10.
Note: You will learn about why the range is called A1:E10 after this example.
Select cell A1:
Press and hold A1 with the left mouse button. Move to the mouse pointer to mark the selection range. The grey area helps us to see the covered range.
Let go of the left mouse button when you have marked the range A1:E10:
You have successfully selected the range A1:E10. Well done!
The second way to select a range is to enter the range values in the Name Box. The range is set by first entering the cell reference for the top left corner, then the bottom right corner. The range is made using those two as coordinates. That is why the cell range has the reference of two cells and the
: in between.
Top left corner reference : Right bottom corner reference
The range shown in the picture has the value of A1:E10:
The best way for now is to use the drag and mark method as it is easier and more visual.
In the next chapter you will learn about filling and how this applies to the ranges that we have just learned.
Type the cell reference for Column A, Row 1:
A
Start the Exercise
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": 92,
"s": 0,
"text": "Range is an important part of Excel because it allows you to work with selections of cells."
},
{
"code": null,
"e": 144,
"s": 92,
"text": "There are four different operations for selection; "
},
{
"code": null,
"e": 161,
"s": 144,
"text": "Selecting a cell"
},
{
"code": null,
"e": 186,
"s": 161,
"text": "Selecting multiple cells"
},
{
"code": null,
"e": 206,
"s": 186,
"text": "Selecting a column "
},
{
"code": null,
"e": 222,
"s": 206,
"text": "Selecting a row"
},
{
"code": null,
"e": 319,
"s": 222,
"text": "Before having a look at the different operations for selection, we will introduce the Name Box. "
},
{
"code": null,
"e": 468,
"s": 319,
"text": "The Name Box shows you the reference of which cell or range you have selected. It can also be used to select cells or ranges by typing their values."
},
{
"code": null,
"e": 530,
"s": 468,
"text": "You will learn more about the Name Box later in this chapter."
},
{
"code": null,
"e": 644,
"s": 530,
"text": "Cells are selected by clicking them with the left mouse button or by navigating to them with the keyboard arrows."
},
{
"code": null,
"e": 692,
"s": 644,
"text": "It is easiest to use the mouse to select cells."
},
{
"code": null,
"e": 724,
"s": 692,
"text": "To select cell A1, click on it:"
},
{
"code": null,
"e": 898,
"s": 724,
"text": "More than one cell can be selected by pressing and holding down CTRL or Command and left clicking the cells. Once finished with selecting, you can let go of CTRL or Command."
},
{
"code": null,
"e": 959,
"s": 898,
"text": "Lets try an example: Select the cells A1, A7, C1, C7 and B4."
},
{
"code": null,
"e": 995,
"s": 959,
"text": "Did it look like the picture below?"
},
{
"code": null,
"e": 1100,
"s": 995,
"text": "Columns are selected by left clicking it. This will select all cells in the sheet related to the column."
},
{
"code": null,
"e": 1161,
"s": 1100,
"text": "To select column A, click on the letter A in the column bar:"
},
{
"code": null,
"e": 1265,
"s": 1161,
"text": "Rows are selected by left clicking it. This will select all the cells in the sheet related to that row."
},
{
"code": null,
"e": 1318,
"s": 1265,
"text": "To select row 1, click on its number in the row bar:"
},
{
"code": null,
"e": 1426,
"s": 1318,
"text": "The entire spreadsheet can be selected by clicking the triangle in the top-left corner of the spreadsheet: "
},
{
"code": null,
"e": 1466,
"s": 1426,
"text": "Now, the whole spreadsheet is selected:"
},
{
"code": null,
"e": 1567,
"s": 1466,
"text": "Note: You can also select the entire spreadsheet by pressing Ctrl+A for Windows, or Cmd+A for MacOS."
},
{
"code": null,
"e": 1813,
"s": 1567,
"text": "Selection of cell ranges has many use areas and it is one of the most important concepts of Excel. Do not think too much about how it is used with values. You will learn about this in a later chapter. For now let's focus on how to select ranges."
},
{
"code": null,
"e": 1859,
"s": 1813,
"text": "There are two ways to select a range of cells"
},
{
"code": null,
"e": 1892,
"s": 1859,
"text": "\nName Box\nDrag to mark a range.\n"
},
{
"code": null,
"e": 1901,
"s": 1892,
"text": "Name Box"
},
{
"code": null,
"e": 1923,
"s": 1901,
"text": "Drag to mark a range."
},
{
"code": null,
"e": 1995,
"s": 1923,
"text": "The easiest way is drag and mark. Let's keep it simple and start there."
},
{
"code": null,
"e": 2039,
"s": 1995,
"text": "How to drag and mark a range, step-by-step:"
},
{
"code": null,
"e": 2262,
"s": 2039,
"text": "\nSelect a cell\nLeft click it and hold the mouse button down\nMove your mouse pointer over the range that you want selected. The range that is marked will turn grey.\nLet go of the mouse button when you have marked the range\n"
},
{
"code": null,
"e": 2276,
"s": 2262,
"text": "Select a cell"
},
{
"code": null,
"e": 2321,
"s": 2276,
"text": "Left click it and hold the mouse button down"
},
{
"code": null,
"e": 2425,
"s": 2321,
"text": "Move your mouse pointer over the range that you want selected. The range that is marked will turn grey."
},
{
"code": null,
"e": 2483,
"s": 2425,
"text": "Let go of the mouse button when you have marked the range"
},
{
"code": null,
"e": 2549,
"s": 2483,
"text": "Let's have a look at an example for how to mark the range A1:E10."
},
{
"code": null,
"e": 2628,
"s": 2549,
"text": "Note: You will learn about why the range is called A1:E10 after this example.\n"
},
{
"code": null,
"e": 2644,
"s": 2628,
"text": "Select cell A1:"
},
{
"code": null,
"e": 2794,
"s": 2644,
"text": "Press and hold A1 with the left mouse button. Move to the mouse pointer to mark the selection range. The grey area helps us to see the covered range."
},
{
"code": null,
"e": 2865,
"s": 2794,
"text": "Let go of the left mouse button when you have marked the range A1:E10:"
},
{
"code": null,
"e": 2925,
"s": 2865,
"text": "You have successfully selected the range A1:E10. Well done!"
},
{
"code": null,
"e": 3245,
"s": 2925,
"text": "The second way to select a range is to enter the range values in the Name Box. The range is set by first entering the cell reference for the top left corner, then the bottom right corner. The range is made using those two as coordinates. That is why the cell range has the reference of two cells and the \n: in between.\n"
},
{
"code": null,
"e": 3303,
"s": 3245,
"text": "Top left corner reference : Right bottom corner reference"
},
{
"code": null,
"e": 3359,
"s": 3303,
"text": "The range shown in the picture has the value of A1:E10:"
},
{
"code": null,
"e": 3448,
"s": 3359,
"text": "The best way for now is to use the drag and mark method as it is easier and more visual."
},
{
"code": null,
"e": 3559,
"s": 3448,
"text": "In the next chapter you will learn about filling and how this applies to the ranges that we have just learned."
},
{
"code": null,
"e": 3604,
"s": 3559,
"text": "Type the cell reference for Column A, Row 1:"
},
{
"code": null,
"e": 3607,
"s": 3604,
"text": "A\n"
},
{
"code": null,
"e": 3626,
"s": 3607,
"text": "Start the Exercise"
},
{
"code": null,
"e": 3659,
"s": 3626,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3701,
"s": 3659,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3808,
"s": 3701,
"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": 3827,
"s": 3808,
"text": "help@w3schools.com"
}
] |
How to give dynamic height to UIlabel programmatically in swift?
|
To give a dynamic height to an UIlabel in swift we can use the frame property of UILabel. We can create a frame using the CGRect which allows us to give different variables like x position, y position, width, and height.
Let’s create a label and add it as a subview to our view.
let label = UILabel()
label.frame = CGRect(x: 10, y: 40, width: 200, height: 50)
label.backgroundColor = colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
label.textColor = colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1)
label.text = "Custom label"
self.view.addSubview(label)
We can embed this in a function as well, and create an extension too.
func makeLabel(atX x: Double, andY y: Double,width: Double, height: Double) -> UILabel {
let label = UILabel()
label.frame = CGRect(x: x, y: y, width: width, height: height)
label.backgroundColor = colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
label.textColor = colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1)
label.text = "Custom label"
return label
}
We can use it inside the view controller along with the previous code, and this is how it looks on the device.
self.view.addSubview(makeLabel(atX: 10, andY: 100, width: 250, height: 100))
|
[
{
"code": null,
"e": 1283,
"s": 1062,
"text": "To give a dynamic height to an UIlabel in swift we can use the frame property of UILabel. We can create a frame using the CGRect which allows us to give different variables like x position, y position, width, and height."
},
{
"code": null,
"e": 1341,
"s": 1283,
"text": "Let’s create a label and add it as a subview to our view."
},
{
"code": null,
"e": 1687,
"s": 1341,
"text": "let label = UILabel()\nlabel.frame = CGRect(x: 10, y: 40, width: 200, height: 50)\nlabel.backgroundColor = colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)\nlabel.textColor = colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1)\nlabel.text = \"Custom label\"\nself.view.addSubview(label)"
},
{
"code": null,
"e": 1757,
"s": 1687,
"text": "We can embed this in a function as well, and create an extension too."
},
{
"code": null,
"e": 2201,
"s": 1757,
"text": "func makeLabel(atX x: Double, andY y: Double,width: Double, height: Double) -> UILabel {\n let label = UILabel()\n label.frame = CGRect(x: x, y: y, width: width, height: height)\n label.backgroundColor = colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)\n label.textColor = colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1)\n label.text = \"Custom label\"\n return label\n}"
},
{
"code": null,
"e": 2312,
"s": 2201,
"text": "We can use it inside the view controller along with the previous code, and this is how it looks on the device."
},
{
"code": null,
"e": 2389,
"s": 2312,
"text": "self.view.addSubview(makeLabel(atX: 10, andY: 100, width: 250, height: 100))"
}
] |
Java - Basic Syntax
|
When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.
Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
Let us look at a simple code that will print the words Hello World.
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −
Open notepad and add the code as above.
Open notepad and add the code as above.
Save the file as: MyFirstJavaProgram.java.
Save the file as: MyFirstJavaProgram.java.
Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see ' Hello World ' printed on the window.
You will be able to see ' Hello World ' printed on the window.
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file then file name can be different than class name. It is also not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file then file name can be different than class name. It is also not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.
public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.
All Java components require names. Names used for classes, variables, and methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
After the first character, identifiers can have any combination of characters.
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Examples of illegal identifiers: 123abc, -salary.
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers −
Access Modifiers − default, public , protected, private
Access Modifiers − default, public , protected, private
Non-access Modifiers − final, abstract, strictfp
Non-access Modifiers − final, abstract, strictfp
We will be looking into more details about modifiers in the next section.
Following are the types of variables in Java −
Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static Variables)
Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct, and initialize in the upcoming chapters.
Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.
class FreshJuice {
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
FreshJuiceSize size;
}
public class FreshJuiceTest {
public static void main(String args[]) {
FreshJuice juice = new FreshJuice();
juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;
System.out.println("Size: " + juice.size);
}
}
The above example will produce the following result −
Size: MEDIUM
Note − Enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.
The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.
Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler.
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
public static void main(String []args) {
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}
Hello World
A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it.
In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass.
In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.
An interface defines the methods, a deriving class (subclass) should use. But the implementation of the methods is totally up to the subclass.
The next section explains about Objects and classes in Java programming. At the end of the session, you will be able to get a clear picture as to what are objects and what are classes in Java.
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": 2597,
"s": 2377,
"text": "When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean."
},
{
"code": null,
"e": 2790,
"s": 2597,
"text": "Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class."
},
{
"code": null,
"e": 2983,
"s": 2790,
"text": "Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class."
},
{
"code": null,
"e": 3110,
"s": 2983,
"text": "Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports."
},
{
"code": null,
"e": 3237,
"s": 3110,
"text": "Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports."
},
{
"code": null,
"e": 3416,
"s": 3237,
"text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 3595,
"s": 3416,
"text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 3751,
"s": 3595,
"text": "Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables."
},
{
"code": null,
"e": 3907,
"s": 3751,
"text": "Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables."
},
{
"code": null,
"e": 3975,
"s": 3907,
"text": "Let us look at a simple code that will print the words Hello World."
},
{
"code": null,
"e": 4219,
"s": 3975,
"text": "public class MyFirstJavaProgram {\n\n /* This is my first java program.\n * This will print 'Hello World' as the output\n */\n\n public static void main(String []args) {\n System.out.println(\"Hello World\"); // prints Hello World\n }\n}"
},
{
"code": null,
"e": 4322,
"s": 4219,
"text": "Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −"
},
{
"code": null,
"e": 4362,
"s": 4322,
"text": "Open notepad and add the code as above."
},
{
"code": null,
"e": 4402,
"s": 4362,
"text": "Open notepad and add the code as above."
},
{
"code": null,
"e": 4445,
"s": 4402,
"text": "Save the file as: MyFirstJavaProgram.java."
},
{
"code": null,
"e": 4488,
"s": 4445,
"text": "Save the file as: MyFirstJavaProgram.java."
},
{
"code": null,
"e": 4586,
"s": 4488,
"text": "Open a command prompt window and go to the directory where you saved the \tclass. Assume it's C:\\."
},
{
"code": null,
"e": 4684,
"s": 4586,
"text": "Open a command prompt window and go to the directory where you saved the \tclass. Assume it's C:\\."
},
{
"code": null,
"e": 4887,
"s": 4684,
"text": "Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set)."
},
{
"code": null,
"e": 5090,
"s": 4887,
"text": "Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set)."
},
{
"code": null,
"e": 5149,
"s": 5090,
"text": "Now, type ' java MyFirstJavaProgram ' to run your program."
},
{
"code": null,
"e": 5208,
"s": 5149,
"text": "Now, type ' java MyFirstJavaProgram ' to run your program."
},
{
"code": null,
"e": 5271,
"s": 5208,
"text": "You will be able to see ' Hello World ' printed on the window."
},
{
"code": null,
"e": 5334,
"s": 5271,
"text": "You will be able to see ' Hello World ' printed on the window."
},
{
"code": null,
"e": 5412,
"s": 5334,
"text": "C:\\> javac MyFirstJavaProgram.java\nC:\\> java MyFirstJavaProgram \nHello World\n"
},
{
"code": null,
"e": 5492,
"s": 5412,
"text": "About Java programs, it is very important to keep in mind the following points."
},
{
"code": null,
"e": 5612,
"s": 5492,
"text": "Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java."
},
{
"code": null,
"e": 5732,
"s": 5612,
"text": "Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java."
},
{
"code": null,
"e": 5951,
"s": 5732,
"text": "Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.\nExample: class MyFirstJavaClass"
},
{
"code": null,
"e": 6138,
"s": 5951,
"text": "Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case."
},
{
"code": null,
"e": 6170,
"s": 6138,
"text": "Example: class MyFirstJavaClass"
},
{
"code": null,
"e": 6397,
"s": 6170,
"text": "Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.\nExample: public void myMethodName()"
},
{
"code": null,
"e": 6588,
"s": 6397,
"text": "Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case."
},
{
"code": null,
"e": 6624,
"s": 6588,
"text": "Example: public void myMethodName()"
},
{
"code": null,
"e": 7241,
"s": 6624,
"text": "Program File Name − Name of the program file should exactly match the class name.\nWhen saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).\nBut please make a note that in case you do not have a public class present in the file then file name can be different than class name. It is also not mandatory to have a public class in the file.\nExample: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'"
},
{
"code": null,
"e": 7323,
"s": 7241,
"text": "Program File Name − Name of the program file should exactly match the class name."
},
{
"code": null,
"e": 7544,
"s": 7323,
"text": "When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile)."
},
{
"code": null,
"e": 7743,
"s": 7544,
"text": "But please make a note that in case you do not have a public class present in the file then file name can be different than class name. It is also not mandatory to have a public class in the file."
},
{
"code": null,
"e": 7858,
"s": 7743,
"text": "Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'"
},
{
"code": null,
"e": 8002,
"s": 7858,
"text": "public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program."
},
{
"code": null,
"e": 8146,
"s": 8002,
"text": "public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program."
},
{
"code": null,
"e": 8252,
"s": 8146,
"text": "All Java components require names. Names used for classes, variables, and methods are called identifiers."
},
{
"code": null,
"e": 8339,
"s": 8252,
"text": "In Java, there are several points to remember about identifiers. They are as follows −"
},
{
"code": null,
"e": 8447,
"s": 8339,
"text": "All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_)."
},
{
"code": null,
"e": 8555,
"s": 8447,
"text": "All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_)."
},
{
"code": null,
"e": 8634,
"s": 8555,
"text": "After the first character, identifiers can have any combination of characters."
},
{
"code": null,
"e": 8713,
"s": 8634,
"text": "After the first character, identifiers can have any combination of characters."
},
{
"code": null,
"e": 8757,
"s": 8713,
"text": "A key word cannot be used as an identifier."
},
{
"code": null,
"e": 8801,
"s": 8757,
"text": "A key word cannot be used as an identifier."
},
{
"code": null,
"e": 8851,
"s": 8801,
"text": "Most importantly, identifiers are case sensitive."
},
{
"code": null,
"e": 8901,
"s": 8851,
"text": "Most importantly, identifiers are case sensitive."
},
{
"code": null,
"e": 8965,
"s": 8901,
"text": "Examples of legal identifiers: age, $salary, _value, __1_value."
},
{
"code": null,
"e": 9029,
"s": 8965,
"text": "Examples of legal identifiers: age, $salary, _value, __1_value."
},
{
"code": null,
"e": 9079,
"s": 9029,
"text": "Examples of illegal identifiers: 123abc, -salary."
},
{
"code": null,
"e": 9129,
"s": 9079,
"text": "Examples of illegal identifiers: 123abc, -salary."
},
{
"code": null,
"e": 9260,
"s": 9129,
"text": "Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers −"
},
{
"code": null,
"e": 9316,
"s": 9260,
"text": "Access Modifiers − default, public , protected, private"
},
{
"code": null,
"e": 9372,
"s": 9316,
"text": "Access Modifiers − default, public , protected, private"
},
{
"code": null,
"e": 9421,
"s": 9372,
"text": "Non-access Modifiers − final, abstract, strictfp"
},
{
"code": null,
"e": 9470,
"s": 9421,
"text": "Non-access Modifiers − final, abstract, strictfp"
},
{
"code": null,
"e": 9544,
"s": 9470,
"text": "We will be looking into more details about modifiers in the next section."
},
{
"code": null,
"e": 9591,
"s": 9544,
"text": "Following are the types of variables in Java −"
},
{
"code": null,
"e": 9607,
"s": 9591,
"text": "Local Variables"
},
{
"code": null,
"e": 9642,
"s": 9607,
"text": "Class Variables (Static Variables)"
},
{
"code": null,
"e": 9684,
"s": 9642,
"text": "Instance Variables (Non-static Variables)"
},
{
"code": null,
"e": 9888,
"s": 9684,
"text": "Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct, and initialize in the upcoming chapters."
},
{
"code": null,
"e": 10047,
"s": 9888,
"text": "Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums."
},
{
"code": null,
"e": 10127,
"s": 10047,
"text": "With the use of enums it is possible to reduce the number of bugs in your code."
},
{
"code": null,
"e": 10377,
"s": 10127,
"text": "For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large."
},
{
"code": null,
"e": 10698,
"s": 10377,
"text": "class FreshJuice {\n enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }\n FreshJuiceSize size;\n}\n\npublic class FreshJuiceTest {\n\n public static void main(String args[]) {\n FreshJuice juice = new FreshJuice();\n juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;\n System.out.println(\"Size: \" + juice.size);\n }\n}"
},
{
"code": null,
"e": 10752,
"s": 10698,
"text": "The above example will produce the following result −"
},
{
"code": null,
"e": 10766,
"s": 10752,
"text": "Size: MEDIUM\n"
},
{
"code": null,
"e": 10897,
"s": 10766,
"text": "Note − Enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well."
},
{
"code": null,
"e": 11042,
"s": 10897,
"text": "The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names."
},
{
"code": null,
"e": 11193,
"s": 11042,
"text": "Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler."
},
{
"code": null,
"e": 11575,
"s": 11193,
"text": "public class MyFirstJavaProgram {\n\n /* This is my first java program.\n * This will print 'Hello World' as the output\n * This is an example of multi-line comments.\n */\n\n public static void main(String []args) {\n // This is an example of single line comment\n /* This is also an example of single line comment. */\n System.out.println(\"Hello World\");\n }\n}"
},
{
"code": null,
"e": 11588,
"s": 11575,
"text": "Hello World\n"
},
{
"code": null,
"e": 11704,
"s": 11588,
"text": "A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it."
},
{
"code": null,
"e": 11939,
"s": 11704,
"text": "In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code."
},
{
"code": null,
"e": 12176,
"s": 11939,
"text": "This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass."
},
{
"code": null,
"e": 12365,
"s": 12176,
"text": "In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance."
},
{
"code": null,
"e": 12508,
"s": 12365,
"text": "An interface defines the methods, a deriving class (subclass) should use. But the implementation of the methods is totally up to the subclass."
},
{
"code": null,
"e": 12701,
"s": 12508,
"text": "The next section explains about Objects and classes in Java programming. At the end of the session, you will be able to get a clear picture as to what are objects and what are classes in Java."
},
{
"code": null,
"e": 12734,
"s": 12701,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12750,
"s": 12734,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 12783,
"s": 12750,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 12799,
"s": 12783,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 12834,
"s": 12799,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12848,
"s": 12834,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 12882,
"s": 12848,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 12896,
"s": 12882,
"text": " Tushar Kale"
},
{
"code": null,
"e": 12933,
"s": 12896,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 12948,
"s": 12933,
"text": " Monica Mittal"
},
{
"code": null,
"e": 12981,
"s": 12948,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 13000,
"s": 12981,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 13007,
"s": 13000,
"text": " Print"
},
{
"code": null,
"e": 13018,
"s": 13007,
"text": " Add Notes"
}
] |
Chrono in C++
|
In this section we will see what is the Chrono library in C++. This Chrono library is used for date and time. Timers and clocks are different in different systems. So if we want to improve time over precision we can use this library.
In this library, it provides precision-neutral concept, by separating the durations and point of time.
The duration objects are used to express time span by means of a count like minute, two hours or ten minutes. For example, 30 seconds is represented by a duration consisting of 30 ticks of unit of 1 seconds.
Live Demo
#include <iostream>
#include <chrono>
using namespace std;
int main () {
using namespace std::chrono;
// chrono::milliseconds is an instantiation of std::chrono::duration
milliseconds mili(1000);
mili = mili*60;
cout << "Duration : ";
cout << mili.count() << " milliseconds.\n";
cout << "Duration : ";
cout << (mili.count() * milliseconds::period::num / milliseconds::period::den);
cout << " seconds.\n";
}
Duration : 60000 milliseconds.
Duration : 60 seconds.
|
[
{
"code": null,
"e": 1296,
"s": 1062,
"text": "In this section we will see what is the Chrono library in C++. This Chrono library is used for date and time. Timers and clocks are different in different systems. So if we want to improve time over precision we can use this library."
},
{
"code": null,
"e": 1399,
"s": 1296,
"text": "In this library, it provides precision-neutral concept, by separating the durations and point of time."
},
{
"code": null,
"e": 1607,
"s": 1399,
"text": "The duration objects are used to express time span by means of a count like minute, two hours or ten minutes. For example, 30 seconds is represented by a duration consisting of 30 ticks of unit of 1 seconds."
},
{
"code": null,
"e": 1618,
"s": 1607,
"text": " Live Demo"
},
{
"code": null,
"e": 2052,
"s": 1618,
"text": "#include <iostream>\n#include <chrono>\nusing namespace std;\nint main () {\n using namespace std::chrono;\n // chrono::milliseconds is an instantiation of std::chrono::duration\n milliseconds mili(1000);\n mili = mili*60;\n cout << \"Duration : \";\n cout << mili.count() << \" milliseconds.\\n\";\n cout << \"Duration : \";\n cout << (mili.count() * milliseconds::period::num / milliseconds::period::den);\n cout << \" seconds.\\n\";\n}"
},
{
"code": null,
"e": 2106,
"s": 2052,
"text": "Duration : 60000 milliseconds.\nDuration : 60 seconds."
}
] |
Class getTypeParameters() method in Java with Examples - GeeksforGeeks
|
27 Jan, 2022
The getTypeParameters() method of java.lang.Class class is used to get the type parameters of this entity. This entity can be a class, an array, an interface, etc. The method returns an array of TypeVariable objects representing the type variables.Syntax:
public TypeVariable<Class<T>> getTypeParameters()
Parameter: This method does not accept any parameter.Return Value: This method returns an array of TypeVariable objects representing the type variables.Below programs demonstrate the getTypeParameters() method.Example 1:
Java
// Java program to demonstrate getTypeParameters() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the type parameters of myClass // using getTypeParameters() method System.out.println( "TypeParameters of myClass: " + Arrays.toString( myClass.getTypeParameters())); }}
Class represented by myClass: class Test
TypeParameters of myClass: []
Example 2:
Java
// Java program to demonstrate getTypeParameters() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("java.lang.Integer"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the type parameters of myClass // using getTypeParameters() method System.out.println( "TypeParameters of myClass: " + Arrays.toString( myClass.getTypeParameters())); }}
Class represented by myClass: class java.lang.Integer
TypeParameters of myClass: []
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getTypeParameters–
adnanirshad158
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 25483,
"s": 25225,
"text": "The getTypeParameters() method of java.lang.Class class is used to get the type parameters of this entity. This entity can be a class, an array, an interface, etc. The method returns an array of TypeVariable objects representing the type variables.Syntax: "
},
{
"code": null,
"e": 25533,
"s": 25483,
"text": "public TypeVariable<Class<T>> getTypeParameters()"
},
{
"code": null,
"e": 25755,
"s": 25533,
"text": "Parameter: This method does not accept any parameter.Return Value: This method returns an array of TypeVariable objects representing the type variables.Below programs demonstrate the getTypeParameters() method.Example 1: "
},
{
"code": null,
"e": 25760,
"s": 25755,
"text": "Java"
},
{
"code": "// Java program to demonstrate getTypeParameters() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the type parameters of myClass // using getTypeParameters() method System.out.println( \"TypeParameters of myClass: \" + Arrays.toString( myClass.getTypeParameters())); }}",
"e": 26389,
"s": 25760,
"text": null
},
{
"code": null,
"e": 26460,
"s": 26389,
"text": "Class represented by myClass: class Test\nTypeParameters of myClass: []"
},
{
"code": null,
"e": 26474,
"s": 26462,
"text": "Example 2: "
},
{
"code": null,
"e": 26479,
"s": 26474,
"text": "Java"
},
{
"code": "// Java program to demonstrate getTypeParameters() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"java.lang.Integer\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the type parameters of myClass // using getTypeParameters() method System.out.println( \"TypeParameters of myClass: \" + Arrays.toString( myClass.getTypeParameters())); }}",
"e": 27121,
"s": 26479,
"text": null
},
{
"code": null,
"e": 27205,
"s": 27121,
"text": "Class represented by myClass: class java.lang.Integer\nTypeParameters of myClass: []"
},
{
"code": null,
"e": 27301,
"s": 27207,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getTypeParameters– "
},
{
"code": null,
"e": 27316,
"s": 27301,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27331,
"s": 27316,
"text": "Java-Functions"
},
{
"code": null,
"e": 27349,
"s": 27331,
"text": "Java-lang package"
},
{
"code": null,
"e": 27365,
"s": 27349,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 27370,
"s": 27365,
"text": "Java"
},
{
"code": null,
"e": 27375,
"s": 27370,
"text": "Java"
},
{
"code": null,
"e": 27473,
"s": 27375,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27488,
"s": 27473,
"text": "Stream In Java"
},
{
"code": null,
"e": 27509,
"s": 27488,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27528,
"s": 27509,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27558,
"s": 27528,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27604,
"s": 27558,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27621,
"s": 27604,
"text": "Generics in Java"
},
{
"code": null,
"e": 27642,
"s": 27621,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27685,
"s": 27642,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27721,
"s": 27685,
"text": "Internal Working of HashMap in Java"
}
] |
Python - turtle.clear() - GeeksforGeeks
|
17 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to delete the turtle’s drawings from the screen. Do not move state and position of the turtle as well as drawings of other turtles are not affected. It doesn’t require any argument.
Syntax : turtle.clear()Parameters : NoneReturns : Nothing
Below is the implementation of above method with some examples :
Example 1 :
# import packageimport turtle # motionturtle.forward(100)turtle.right(90)turtle.forward(100)turtle.right(90)turtle.forward(100) # clear the drawing# and remain turtle # as it isturtle.clear()
Output :
Example 2 :
# import packageimport turtle # make a turtle object# and do some drawingt1 = turtle.Turtle()t1.up()t1.setpos(-100, 50)t1.down()t1.circle(50) # make a turtle object# and do some drawingt2 = turtle.Turtle()t2.up()t2.setpos(50, 50)t2.down()t2.circle(50) # make a turtle object# and do some drawingt3 = turtle.Turtle()t3.up()t3.setpos(50, -100)t3.down()t3.circle(50) # make a turtle object# and do some drawingt4 = turtle.Turtle()t4.up()t4.setpos(-100, -100)t4.down()t4.circle(50) # here we clear the work done by turtle # objects : t1 and t3 only but turtle # shape remain as it ist1.clear()t3.clear()
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25562,
"s": 25534,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 25779,
"s": 25562,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 25983,
"s": 25779,
"text": "This function is used to delete the turtle’s drawings from the screen. Do not move state and position of the turtle as well as drawings of other turtles are not affected. It doesn’t require any argument."
},
{
"code": null,
"e": 26041,
"s": 25983,
"text": "Syntax : turtle.clear()Parameters : NoneReturns : Nothing"
},
{
"code": null,
"e": 26106,
"s": 26041,
"text": "Below is the implementation of above method with some examples :"
},
{
"code": null,
"e": 26118,
"s": 26106,
"text": "Example 1 :"
},
{
"code": "# import packageimport turtle # motionturtle.forward(100)turtle.right(90)turtle.forward(100)turtle.right(90)turtle.forward(100) # clear the drawing# and remain turtle # as it isturtle.clear()",
"e": 26312,
"s": 26118,
"text": null
},
{
"code": null,
"e": 26321,
"s": 26312,
"text": "Output :"
},
{
"code": null,
"e": 26333,
"s": 26321,
"text": "Example 2 :"
},
{
"code": "# import packageimport turtle # make a turtle object# and do some drawingt1 = turtle.Turtle()t1.up()t1.setpos(-100, 50)t1.down()t1.circle(50) # make a turtle object# and do some drawingt2 = turtle.Turtle()t2.up()t2.setpos(50, 50)t2.down()t2.circle(50) # make a turtle object# and do some drawingt3 = turtle.Turtle()t3.up()t3.setpos(50, -100)t3.down()t3.circle(50) # make a turtle object# and do some drawingt4 = turtle.Turtle()t4.up()t4.setpos(-100, -100)t4.down()t4.circle(50) # here we clear the work done by turtle # objects : t1 and t3 only but turtle # shape remain as it ist1.clear()t3.clear()",
"e": 26938,
"s": 26333,
"text": null
},
{
"code": null,
"e": 26947,
"s": 26938,
"text": "Output :"
},
{
"code": null,
"e": 26961,
"s": 26947,
"text": "Python-turtle"
},
{
"code": null,
"e": 26968,
"s": 26961,
"text": "Python"
},
{
"code": null,
"e": 27066,
"s": 26968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27098,
"s": 27066,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27140,
"s": 27098,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27182,
"s": 27140,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27238,
"s": 27182,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27265,
"s": 27238,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27304,
"s": 27265,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27335,
"s": 27304,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27357,
"s": 27335,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27386,
"s": 27357,
"text": "Create a directory in Python"
}
] |
Java program to convert Currency using AWT - GeeksforGeeks
|
08 May, 2020
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-independent, provide powerful components like tables, scroll panels, buttons, list, colour chooser, etc.
In this article, we’ll see how to make a currency converter which includes conversion between INR and Dollar. Two text fields are implemented with the labels Rupees and Dollar.
Note: It is assumed that 1 dollar is equal to 65.25 rupees.
Examples:
Input: INR = 130.5Output: 2.0Explanation:One dollar is 65.25 rupees. So, 130.5 rupees is two dollars.
Input: Dollar = 4.5Output: 293.625
Approach: To solve this problem, the following steps are followed:
First, we need to create a frame using JFrame.Then, create two labels, two textfields and three buttons(the first button for rupees and the second button is for the dollar) using JLabel, JTextField and JButton.Name these components accordingly and set their bounds.Now, in order to perform the conversion on button click, we need to add Event Handlers. In this case, we will add ActionListener to perform an action method known as actionPerformed in which first we need to get the values from the text fields which is default as a “string”.So, in order to perform mathematical operations, we need to convert them into double data type using Double.parseDouble(Object.getText()) and again converting from double to string to place the final value in the other text field using String.valueOf(object).Finally, for changing the values, we use Object.setText(object), the second object is for selecting which field we want to replace.
First, we need to create a frame using JFrame.
Then, create two labels, two textfields and three buttons(the first button for rupees and the second button is for the dollar) using JLabel, JTextField and JButton.
Name these components accordingly and set their bounds.
Now, in order to perform the conversion on button click, we need to add Event Handlers. In this case, we will add ActionListener to perform an action method known as actionPerformed in which first we need to get the values from the text fields which is default as a “string”.
So, in order to perform mathematical operations, we need to convert them into double data type using Double.parseDouble(Object.getText()) and again converting from double to string to place the final value in the other text field using String.valueOf(object).
Finally, for changing the values, we use Object.setText(object), the second object is for selecting which field we want to replace.
Below is the implementation of the above approach:
// Java program to convert from// rupee to the dollar and vice-versa// using Java Swing import javax.swing.*;import java.awt.*;import java.awt.event.*;public class GFG { // Function to convert from rupee // to the dollar and vice-versa // using Java Swing public static void converter() { // Creating a new frame using JFrame JFrame f = new JFrame("CONVERTER"); // Creating two labels JLabel l1, l2; // Creating two text fields. // One for rupee and one for // the dollar JTextField t1, t2; // Creating three buttons JButton b1, b2, b3; // Naming the labels and setting // the bounds for the labels l1 = new JLabel("Rupees:"); l1.setBounds(20, 40, 60, 30); l2 = new JLabel("Dollars:"); l2.setBounds(170, 40, 60, 30); // Initializing the text fields with // 0 by default and setting the // bounds for the text fields t1 = new JTextField("0"); t1.setBounds(80, 40, 50, 30); t2 = new JTextField("0"); t2.setBounds(240, 40, 50, 30); // Creating a button for INR, // one button for the dollar // and one button to close // and setting the bounds b1 = new JButton("INR"); b1.setBounds(50, 80, 60, 15); b2 = new JButton("Dollar"); b2.setBounds(190, 80, 60, 15); b3 = new JButton("close"); b3.setBounds(150, 150, 60, 30); // Adding action listener b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Converting to double double d = Double.parseDouble(t1.getText()); // Converting rupees to dollars double d1 = (d / 65.25); // Getting the string value of the // calculated value String str1 = String.valueOf(d1); // Placing it in the text box t2.setText(str1); } }); // Adding action listener b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Converting to double double d2 = Double.parseDouble(t2.getText()); // converting Dollars to rupees double d3 = (d2 * 65.25); // Getting the string value of the // calculated value String str2 = String.valueOf(d3); // Placing it in the text box t1.setText(str2); } }); // Action listener to close the form b3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); // Default method for closing the frame f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // Adding the created objects // to the form f.add(l1); f.add(t1); f.add(l2); f.add(t2); f.add(b1); f.add(b2); f.add(b3); f.setLayout(null); f.setSize(400, 300); f.setVisible(true); } // Driver code public static void main(String args[]) { converter(); }}
Output:
The window displayed on running the program:Converting from INR to the Dollar, i.e., when INR button is clicked:Converting from the Dollar to INR, i.e., when the dollar button is clicked:
The window displayed on running the program:
Converting from INR to the Dollar, i.e., when INR button is clicked:
Converting from the Dollar to INR, i.e., when the dollar button is clicked:
java-advanced
Java-AWT
java-swing
Java
Write From Home
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
|
[
{
"code": null,
"e": 25739,
"s": 25711,
"text": "\n08 May, 2020"
},
{
"code": null,
"e": 26192,
"s": 25739,
"text": "Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-independent, provide powerful components like tables, scroll panels, buttons, list, colour chooser, etc."
},
{
"code": null,
"e": 26369,
"s": 26192,
"text": "In this article, we’ll see how to make a currency converter which includes conversion between INR and Dollar. Two text fields are implemented with the labels Rupees and Dollar."
},
{
"code": null,
"e": 26429,
"s": 26369,
"text": "Note: It is assumed that 1 dollar is equal to 65.25 rupees."
},
{
"code": null,
"e": 26439,
"s": 26429,
"text": "Examples:"
},
{
"code": null,
"e": 26541,
"s": 26439,
"text": "Input: INR = 130.5Output: 2.0Explanation:One dollar is 65.25 rupees. So, 130.5 rupees is two dollars."
},
{
"code": null,
"e": 26576,
"s": 26541,
"text": "Input: Dollar = 4.5Output: 293.625"
},
{
"code": null,
"e": 26643,
"s": 26576,
"text": "Approach: To solve this problem, the following steps are followed:"
},
{
"code": null,
"e": 27574,
"s": 26643,
"text": "First, we need to create a frame using JFrame.Then, create two labels, two textfields and three buttons(the first button for rupees and the second button is for the dollar) using JLabel, JTextField and JButton.Name these components accordingly and set their bounds.Now, in order to perform the conversion on button click, we need to add Event Handlers. In this case, we will add ActionListener to perform an action method known as actionPerformed in which first we need to get the values from the text fields which is default as a “string”.So, in order to perform mathematical operations, we need to convert them into double data type using Double.parseDouble(Object.getText()) and again converting from double to string to place the final value in the other text field using String.valueOf(object).Finally, for changing the values, we use Object.setText(object), the second object is for selecting which field we want to replace."
},
{
"code": null,
"e": 27621,
"s": 27574,
"text": "First, we need to create a frame using JFrame."
},
{
"code": null,
"e": 27786,
"s": 27621,
"text": "Then, create two labels, two textfields and three buttons(the first button for rupees and the second button is for the dollar) using JLabel, JTextField and JButton."
},
{
"code": null,
"e": 27842,
"s": 27786,
"text": "Name these components accordingly and set their bounds."
},
{
"code": null,
"e": 28118,
"s": 27842,
"text": "Now, in order to perform the conversion on button click, we need to add Event Handlers. In this case, we will add ActionListener to perform an action method known as actionPerformed in which first we need to get the values from the text fields which is default as a “string”."
},
{
"code": null,
"e": 28378,
"s": 28118,
"text": "So, in order to perform mathematical operations, we need to convert them into double data type using Double.parseDouble(Object.getText()) and again converting from double to string to place the final value in the other text field using String.valueOf(object)."
},
{
"code": null,
"e": 28510,
"s": 28378,
"text": "Finally, for changing the values, we use Object.setText(object), the second object is for selecting which field we want to replace."
},
{
"code": null,
"e": 28561,
"s": 28510,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to convert from// rupee to the dollar and vice-versa// using Java Swing import javax.swing.*;import java.awt.*;import java.awt.event.*;public class GFG { // Function to convert from rupee // to the dollar and vice-versa // using Java Swing public static void converter() { // Creating a new frame using JFrame JFrame f = new JFrame(\"CONVERTER\"); // Creating two labels JLabel l1, l2; // Creating two text fields. // One for rupee and one for // the dollar JTextField t1, t2; // Creating three buttons JButton b1, b2, b3; // Naming the labels and setting // the bounds for the labels l1 = new JLabel(\"Rupees:\"); l1.setBounds(20, 40, 60, 30); l2 = new JLabel(\"Dollars:\"); l2.setBounds(170, 40, 60, 30); // Initializing the text fields with // 0 by default and setting the // bounds for the text fields t1 = new JTextField(\"0\"); t1.setBounds(80, 40, 50, 30); t2 = new JTextField(\"0\"); t2.setBounds(240, 40, 50, 30); // Creating a button for INR, // one button for the dollar // and one button to close // and setting the bounds b1 = new JButton(\"INR\"); b1.setBounds(50, 80, 60, 15); b2 = new JButton(\"Dollar\"); b2.setBounds(190, 80, 60, 15); b3 = new JButton(\"close\"); b3.setBounds(150, 150, 60, 30); // Adding action listener b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Converting to double double d = Double.parseDouble(t1.getText()); // Converting rupees to dollars double d1 = (d / 65.25); // Getting the string value of the // calculated value String str1 = String.valueOf(d1); // Placing it in the text box t2.setText(str1); } }); // Adding action listener b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Converting to double double d2 = Double.parseDouble(t2.getText()); // converting Dollars to rupees double d3 = (d2 * 65.25); // Getting the string value of the // calculated value String str2 = String.valueOf(d3); // Placing it in the text box t1.setText(str2); } }); // Action listener to close the form b3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); // Default method for closing the frame f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // Adding the created objects // to the form f.add(l1); f.add(t1); f.add(l2); f.add(t2); f.add(b1); f.add(b2); f.add(b3); f.setLayout(null); f.setSize(400, 300); f.setVisible(true); } // Driver code public static void main(String args[]) { converter(); }}",
"e": 32042,
"s": 28561,
"text": null
},
{
"code": null,
"e": 32050,
"s": 32042,
"text": "Output:"
},
{
"code": null,
"e": 32238,
"s": 32050,
"text": "The window displayed on running the program:Converting from INR to the Dollar, i.e., when INR button is clicked:Converting from the Dollar to INR, i.e., when the dollar button is clicked:"
},
{
"code": null,
"e": 32283,
"s": 32238,
"text": "The window displayed on running the program:"
},
{
"code": null,
"e": 32352,
"s": 32283,
"text": "Converting from INR to the Dollar, i.e., when INR button is clicked:"
},
{
"code": null,
"e": 32428,
"s": 32352,
"text": "Converting from the Dollar to INR, i.e., when the dollar button is clicked:"
},
{
"code": null,
"e": 32442,
"s": 32428,
"text": "java-advanced"
},
{
"code": null,
"e": 32451,
"s": 32442,
"text": "Java-AWT"
},
{
"code": null,
"e": 32462,
"s": 32451,
"text": "java-swing"
},
{
"code": null,
"e": 32467,
"s": 32462,
"text": "Java"
},
{
"code": null,
"e": 32483,
"s": 32467,
"text": "Write From Home"
},
{
"code": null,
"e": 32488,
"s": 32483,
"text": "Java"
},
{
"code": null,
"e": 32586,
"s": 32488,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32637,
"s": 32586,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 32667,
"s": 32637,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32682,
"s": 32667,
"text": "Stream In Java"
},
{
"code": null,
"e": 32701,
"s": 32682,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32732,
"s": 32701,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 32768,
"s": 32732,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 32804,
"s": 32768,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 32865,
"s": 32804,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 32881,
"s": 32865,
"text": "Python infinity"
}
] |
Configuration of Router on a stick - GeeksforGeeks
|
25 Oct, 2021
Prerequisite – Access and trunk portsSwitches divide broadcast domain through VLAN (Virtual LAN). VLAN is a partitioned broadcast domain from a single broadcast domain. Switch doesn’t forward packets across different VLANs by itself. If we want to make these virtual LANs communicate with each other, a concept of Inter VLAN Routing is used.
Inter VLAN Routing :
Inter VLAN routing is a process in which we make different virtual LANs communicate with each other irrespective of where the VLANs are present (on same switch or different switch). Inter VLAN Routing can be achieved through a layer-3 device i.e. Router or layer-3 Switch. When the Inter VLAN Routing is done through Router it is known as Router on a stick. Router On a Stick :
The Router’s interface is divided into sub-interfaces, which acts as a default gateway to their respective VLANs.
Configuration :
Here is a topology in which there is a router and a switch and some end hosts. 2 different VLANs have been created on the switch. The router’s interface is divided into 2 sub-interfaces (as there are 2 different VLANs) which will acts as a default gateway to their respective VLANs. Then router will perform Inter VLAN Routing and the VLANs will communicate with each other.
First we will assign IP address to the host PC1 as 192.168.1.10/24, Server 192.168.1.20/24, and the other host PC2 will have IP address 192.168.2.10/24 manually.
Now, we will make sub-interface of fa0/0 as fa0/0.1 and fa0/0.2 and assign IP addresses as 192.168.1.1/24 and 192.168.2.1/24 respectively on the router’s ports.
r1# int fa0/0.1
r1# encapsulation dot1q 2
r1# ip address 192.168.1.1 255.255.255.0
r1# int fa0/0.2
r1# encapsulation dot1q 3
r1# ip address 192.168.2.1 255.255.255.0
NOTE : Here encapsulation type dot1q is used for frame tagging between the 2 different VLAN. When the switch forwards packet of one VLAN to another, it inserts a VLAN into the Ethernet header.
Now, we will make 2 different VLANs on switch namely VLAN 2 and VLAN 3 giving names HR_dept and sales_dept.
Switch# vlan 2
Switch# name HR_dept
Switch# vlan 3
Switch# name sales_dept
Switch# int range fa0/1-2
Switch# switchport mode access
Switch# switchport access vlan 2
Switch# int fa0/3
Switch# switchport mode access
Switch# switchport access vlan 3
Here, we have assigned VLAN 2 to the specific switch ports fa0/1, fa0/2 and vlan 3 to fa0/3 respectively.
NOTE : int range fa0/1-2 command is used as there are more than one host present in a single VLAN. Now to check reachability of PC2 from PC1, we will try to PING PC2 from PC1.
From the above figures, we see that the packet is delivered to the router by the switch, because now the broadcast domain have been divided by the different VLANs present on the switch therefore, the packet will be delivered to the default gateway (as PC2 is present on different network) and then to the destination.
vaibhavsinghtanwar
Computer Networks-Network Layer
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Socket Programming in Python
Caesar Cipher in Cryptography
UDP Server-Client implementation in C
Socket Programming in Java
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Cryptography and its Types
Wireless Sensor Network (WSN)
|
[
{
"code": null,
"e": 37813,
"s": 37785,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 38155,
"s": 37813,
"text": "Prerequisite – Access and trunk portsSwitches divide broadcast domain through VLAN (Virtual LAN). VLAN is a partitioned broadcast domain from a single broadcast domain. Switch doesn’t forward packets across different VLANs by itself. If we want to make these virtual LANs communicate with each other, a concept of Inter VLAN Routing is used."
},
{
"code": null,
"e": 38176,
"s": 38155,
"text": "Inter VLAN Routing :"
},
{
"code": null,
"e": 38554,
"s": 38176,
"text": "Inter VLAN routing is a process in which we make different virtual LANs communicate with each other irrespective of where the VLANs are present (on same switch or different switch). Inter VLAN Routing can be achieved through a layer-3 device i.e. Router or layer-3 Switch. When the Inter VLAN Routing is done through Router it is known as Router on a stick. Router On a Stick :"
},
{
"code": null,
"e": 38668,
"s": 38554,
"text": "The Router’s interface is divided into sub-interfaces, which acts as a default gateway to their respective VLANs."
},
{
"code": null,
"e": 38686,
"s": 38670,
"text": "Configuration :"
},
{
"code": null,
"e": 39061,
"s": 38686,
"text": "Here is a topology in which there is a router and a switch and some end hosts. 2 different VLANs have been created on the switch. The router’s interface is divided into 2 sub-interfaces (as there are 2 different VLANs) which will acts as a default gateway to their respective VLANs. Then router will perform Inter VLAN Routing and the VLANs will communicate with each other."
},
{
"code": null,
"e": 39223,
"s": 39061,
"text": "First we will assign IP address to the host PC1 as 192.168.1.10/24, Server 192.168.1.20/24, and the other host PC2 will have IP address 192.168.2.10/24 manually."
},
{
"code": null,
"e": 39384,
"s": 39223,
"text": "Now, we will make sub-interface of fa0/0 as fa0/0.1 and fa0/0.2 and assign IP addresses as 192.168.1.1/24 and 192.168.2.1/24 respectively on the router’s ports."
},
{
"code": null,
"e": 39551,
"s": 39384,
"text": "r1# int fa0/0.1\nr1# encapsulation dot1q 2\nr1# ip address 192.168.1.1 255.255.255.0\nr1# int fa0/0.2\nr1# encapsulation dot1q 3\nr1# ip address 192.168.2.1 255.255.255.0"
},
{
"code": null,
"e": 39744,
"s": 39551,
"text": "NOTE : Here encapsulation type dot1q is used for frame tagging between the 2 different VLAN. When the switch forwards packet of one VLAN to another, it inserts a VLAN into the Ethernet header."
},
{
"code": null,
"e": 39852,
"s": 39744,
"text": "Now, we will make 2 different VLANs on switch namely VLAN 2 and VLAN 3 giving names HR_dept and sales_dept."
},
{
"code": null,
"e": 39927,
"s": 39852,
"text": "Switch# vlan 2\nSwitch# name HR_dept\nSwitch# vlan 3\nSwitch# name sales_dept"
},
{
"code": null,
"e": 40099,
"s": 39927,
"text": "Switch# int range fa0/1-2\nSwitch# switchport mode access\nSwitch# switchport access vlan 2\nSwitch# int fa0/3\nSwitch# switchport mode access\nSwitch# switchport access vlan 3"
},
{
"code": null,
"e": 40205,
"s": 40099,
"text": "Here, we have assigned VLAN 2 to the specific switch ports fa0/1, fa0/2 and vlan 3 to fa0/3 respectively."
},
{
"code": null,
"e": 40381,
"s": 40205,
"text": "NOTE : int range fa0/1-2 command is used as there are more than one host present in a single VLAN. Now to check reachability of PC2 from PC1, we will try to PING PC2 from PC1."
},
{
"code": null,
"e": 40699,
"s": 40381,
"text": "From the above figures, we see that the packet is delivered to the router by the switch, because now the broadcast domain have been divided by the different VLANs present on the switch therefore, the packet will be delivered to the default gateway (as PC2 is present on different network) and then to the destination."
},
{
"code": null,
"e": 40718,
"s": 40699,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 40750,
"s": 40718,
"text": "Computer Networks-Network Layer"
},
{
"code": null,
"e": 40768,
"s": 40750,
"text": "Computer Networks"
},
{
"code": null,
"e": 40786,
"s": 40768,
"text": "Computer Networks"
},
{
"code": null,
"e": 40884,
"s": 40786,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40918,
"s": 40884,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 40947,
"s": 40918,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 40977,
"s": 40947,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 41015,
"s": 40977,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 41042,
"s": 41015,
"text": "Socket Programming in Java"
},
{
"code": null,
"e": 41077,
"s": 41042,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 41110,
"s": 41077,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 41136,
"s": 41110,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 41163,
"s": 41136,
"text": "Cryptography and its Types"
}
] |
Online algorithm for checking palindrome in a stream - GeeksforGeeks
|
20 Nov, 2018
Given a stream of characters (characters are received one by one), write a function that prints ‘Yes’ if a character makes the complete string palindrome, else prints ‘No’.
Examples:
Input: str[] = "abcba"
Output: a Yes // "a" is palindrome
b No // "ab" is not palindrome
c No // "abc" is not palindrome
b No // "abcb" is not palindrome
a Yes // "abcba" is palindrome
Input: str[] = "aabaacaabaa"
Output: a Yes // "a" is palindrome
a Yes // "aa" is palindrome
b No // "aab" is not palindrome
a No // "aaba" is not palindrome
a Yes // "aabaa" is palindrome
c No // "aabaac" is not palindrome
a No // "aabaaca" is not palindrome
a No // "aabaacaa" is not palindrome
b No // "aabaacaab" is not palindrome
a No // "aabaacaaba" is not palindrome
a Yes // "aabaacaabaa" is palindrome
Let input string be str[0..n-1]. A Simple Solution is to do following for every character str[i] in input string. Check if substring str[0...i] is palindrome, then print yes, else print no.
A Better Solution is to use the idea of Rolling Hash used in Rabin Karp algorithm. The idea is to keep track of reverse of first half and second half (we also use first half and reverse of second half) for every index. Below is complete algorithm.
1) The first character is always a palindrome, so print yes for
first character.
2) Initialize reverse of first half as "a" and second half as "b".
Let the hash value of first half reverse be 'firstr' and that of
second half be 'second'.
3) Iterate through string starting from second character, do following
for every character str[i], i.e., i varies from 1 to n-1.
a) If 'firstr' and 'second' are same, then character by character
check the substring ending with current character and print
"Yes" if palindrome.
Note that if hash values match, then strings need not be same.
For example, hash values of "ab" and "ba" are same, but strings
are different. That is why we check complete string after hash.
b) Update 'firstr' and 'second' for next iteration.
If 'i' is even, then add next character to the beginning of
'firstr' and end of second half and update
hash values.
If 'i' is odd, then keep 'firstr' as it is, remove leading
character from second and append a next
character at end.
Let us see all steps for example string “abcba”
Initial values of ‘firstr’ and ‘second’ firstr’ = hash(“a”), ‘second’ = hash(“b”)
Start from second character, i.e.,i = 1 a) Compare ‘firstr’ and ‘second’, they don’t match, so print no. b) Calculate hash values for next iteration, i.e., i = 2 Since i is odd, ‘firstr’ is not changed and ‘second’ becomes hash(“c”)
i = 2 a) Compare ‘firstr’ and ‘second’, they don’t match, so print no. b) Calculate hash values for next iteration, i.e., i = 3 Since i is even, ‘firstr’ becomes hash(“ba”) and ‘second’ becomes hash(“cb”)
i = 3 a) Compare ‘first’ and ‘second’, they don’t match, so print no. b) Calculate hash values for next iteration, i.e., i = 4 Since i is odd, ‘firstr’ is not changed and ‘second’ becomes hash(“ba”)
i = 4 a) ‘firstr’ and ‘second’ match, compare the whole strings, they match, so print yes b) We don’t need to calculate next hash values as this is last index
The idea of using rolling hashes is, next hash value can be calculated from previous in O(1) time by just doing some constant number of arithmetic operations.
Below are the implementations of above approach.
C/C++
Java
Python
C#
// C program for online algorithm for palindrome checking#include<stdio.h>#include<string.h> // d is the number of characters in input alphabet#define d 256 // q is a prime number used for evaluating Rabin Karp's Rolling hash#define q 103 void checkPalindromes(char str[]){ // Length of input string int N = strlen(str); // A single character is always a palindrome printf("%c Yes\n", str[0]); // Return if string has only one character if (N == 1) return; // Initialize first half reverse and second half for // as firstr and second characters int firstr = str[0] % q; int second = str[1] % q; int h = 1, i, j; // Now check for palindromes from second character // onward for (i=1; i<N; i++) { // If the hash values of 'firstr' and 'second' // match, then only check individual characters if (firstr == second) { /* Check if str[0..i] is palindrome using simple character by character match */ for (j = 0; j < i/2; j++) { if (str[j] != str[i-j]) break; } (j == i/2)? printf("%c Yes\n", str[i]): printf("%c No\n", str[i]); } else printf("%c No\n", str[i]); // Calculate hash values for next iteration. // Don't calculate hash for next characters if // this is the last character of string if (i != N-1) { // If i is even (next i is odd) if (i%2 == 0) { // Add next character after first half at beginning // of 'firstr' h = (h*d) % q; firstr = (firstr + h*str[i/2])%q; // Add next character after second half at the end // of second half. second = (second*d + str[i+1])%q; } else { // If next i is odd (next i is even) then we // need not to change firstr, we need to remove // first character of second and append a // character to it. second = (d*(second + q - str[(i+1)/2]*h)%q + str[i+1])%q; } } }} /* Driver program to test above function */int main(){ char *txt = "aabaacaabaa"; checkPalindromes(txt); getchar(); return 0;}
// Java program for online algorithm for// palindrome checkingpublic class GFG { // d is the number of characters in // input alphabet static final int d = 256; // q is a prime number used for // evaluating Rabin Karp's Rolling hash static final int q = 103; static void checkPalindromes(String str) { // Length of input string int N = str.length(); // A single character is always a palindrome System.out.println(str.charAt(0)+" Yes"); // Return if string has only one character if (N == 1) return; // Initialize first half reverse and second // half for as firstr and second characters int firstr = str.charAt(0) % q; int second = str.charAt(1) % q; int h = 1, i, j; // Now check for palindromes from second // character onward for (i = 1; i < N; i++) { // If the hash values of 'firstr' and // 'second' match, then only check // individual characters if (firstr == second) { /* Check if str[0..i] is palindrome using simple character by character match */ for (j = 0; j < i/2; j++) { if (str.charAt(j) != str.charAt(i - j)) break; } System.out.println((j == i/2) ? str.charAt(i) + " Yes": str.charAt(i)+ " No"); } else System.out.println(str.charAt(i)+ " No"); // Calculate hash values for next iteration. // Don't calculate hash for next characters // if this is the last character of string if (i != N - 1) { // If i is even (next i is odd) if (i % 2 == 0) { // Add next character after first // half at beginning of 'firstr' h = (h * d) % q; firstr = (firstr + h *str.charAt(i / 2)) % q; // Add next character after second // half at the end of second half. second = (second * d + str.charAt(i + 1)) % q; } else { // If next i is odd (next i is even) // then we need not to change firstr, // we need to remove first character // of second and append a character // to it. second = (d * (second + q - str.charAt( (i + 1) / 2) * h) % q + str.charAt(i + 1)) % q; } } } } /* Driver program to test above function */ public static void main(String args[]) { String txt = "aabaacaabaa"; checkPalindromes(txt); }}// This code is contributed by Sumit Ghosh
# Python program Online algorithm for checking palindrome# in a stream # d is the number of characters in input alphabetd = 256 # q is a prime number used for evaluating Rabin Karp's# Rolling hashq = 103 def checkPalindromes(string): # Length of input string N = len(string) # A single character is always a palindrome print string[0] + " Yes" # Return if string has only one character if N == 1: return # Initialize first half reverse and second half for # as firstr and second characters firstr = ord(string[0]) % q second = ord(string[1]) % q h = 1 i = 0 j = 0 # Now check for palindromes from second character # onward for i in xrange(1,N): # If the hash values of 'firstr' and 'second' # match, then only check individual characters if firstr == second: # Check if str[0..i] is palindrome using # simple character by character match for j in xrange(0,i/2): if string[j] != string[i-j]: break j += 1 if j == i/2: print string[i] + " Yes" else: print string[i] + " No" else: print string[i] + " No" # Calculate hash values for next iteration. # Don't calculate hash for next characters if # this is the last character of string if i != N-1: # If i is even (next i is odd) if i % 2 == 0: # Add next character after first half at # beginning of 'firstr' h = (h*d) % q firstr = (firstr + h*ord(string[i/2]))%q # Add next character after second half at # the end of second half. second = (second*d + ord(string[i+1]))%q else: # If next i is odd (next i is even) then we # need not to change firstr, we need to remove # first character of second and append a # character to it. second = (d*(second + q - ord(string[(i+1)/2])*h)%q + ord(string[i+1]))%q # Driver programtxt = "aabaacaabaa"checkPalindromes(txt)# This code is contributed by Bhavya Jain
// C# program for online algorithm for // palindrome checking using System; class GFG{// d is the number of characters // in input alphabet public const int d = 256; // q is a prime number used for // evaluating Rabin Karp's Rolling hash public const int q = 103; public static void checkPalindromes(string str){ // Length of input string int N = str.Length; // A single character is always // a palindrome Console.WriteLine(str[0] + " Yes"); // Return if string has only // one character if (N == 1) { return; } // Initialize first half reverse and second // half for as firstr and second characters int firstr = str[0] % q; int second = str[1] % q; int h = 1, i, j; // Now check for palindromes from // second character onward for (i = 1; i < N; i++) { // If the hash values of 'firstr' // and 'second' match, then only // check individual characters if (firstr == second) { /* Check if str[0..i] is palindrome using simple character by character match */ for (j = 0; j < i / 2; j++) { if (str[j] != str[i - j]) { break; } } Console.WriteLine((j == i / 2) ? str[i] + " Yes": str[i] + " No"); } else { Console.WriteLine(str[i] + " No"); } // Calculate hash values for next iteration. // Don't calculate hash for next characters // if this is the last character of string if (i != N - 1) { // If i is even (next i is odd) if (i % 2 == 0) { // Add next character after first // half at beginning of 'firstr' h = (h * d) % q; firstr = (firstr + h * str[i / 2]) % q; // Add next character after second // half at the end of second half. second = (second * d + str[i + 1]) % q; } else { // If next i is odd (next i is even) // then we need not to change firstr, // we need to remove first character // of second and append a character // to it. second = (d * (second + q - str[(i + 1) / 2] * h) % q + str[i + 1]) % q; } } }} // Driver Codepublic static void Main(string[] args){ string txt = "aabaacaabaa"; checkPalindromes(txt);}} // This code is contributed by Shrikant13
a Yes
a Yes
b No
a No
a Yes
c No
a No
a No
b No
a No
a Yes
The worst case time complexity of the above solution remains O(n*n), but in general, it works much better than simple approach as we avoid complete substring comparison most of the time by first comparing hash values. The worst case occurs for input strings with all same characters like “aaaaaa”.
This article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
array-stream
palindrome
Pattern Searching
Strings
Strings
palindrome
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Removing string that is an anagram of an earlier string
Count N-length strings consisting only of vowels sorted lexicographically
Boyer Moore Algorithm | Good Suffix heuristic
Check whether two strings contain same characters in same order
How to check Aadhaar number is valid or not using Regular Expression
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 26653,
"s": 26625,
"text": "\n20 Nov, 2018"
},
{
"code": null,
"e": 26826,
"s": 26653,
"text": "Given a stream of characters (characters are received one by one), write a function that prints ‘Yes’ if a character makes the complete string palindrome, else prints ‘No’."
},
{
"code": null,
"e": 26836,
"s": 26826,
"text": "Examples:"
},
{
"code": null,
"e": 27615,
"s": 26836,
"text": "Input: str[] = \"abcba\"\nOutput: a Yes // \"a\" is palindrome\n b No // \"ab\" is not palindrome\n c No // \"abc\" is not palindrome\n b No // \"abcb\" is not palindrome\n a Yes // \"abcba\" is palindrome\n\nInput: str[] = \"aabaacaabaa\"\nOutput: a Yes // \"a\" is palindrome\n a Yes // \"aa\" is palindrome\n b No // \"aab\" is not palindrome \n a No // \"aaba\" is not palindrome \n a Yes // \"aabaa\" is palindrome \n c No // \"aabaac\" is not palindrome \n a No // \"aabaaca\" is not palindrome \n a No // \"aabaacaa\" is not palindrome \n b No // \"aabaacaab\" is not palindrome \n a No // \"aabaacaaba\" is not palindrome \n a Yes // \"aabaacaabaa\" is palindrome \n"
},
{
"code": null,
"e": 27805,
"s": 27615,
"text": "Let input string be str[0..n-1]. A Simple Solution is to do following for every character str[i] in input string. Check if substring str[0...i] is palindrome, then print yes, else print no."
},
{
"code": null,
"e": 28053,
"s": 27805,
"text": "A Better Solution is to use the idea of Rolling Hash used in Rabin Karp algorithm. The idea is to keep track of reverse of first half and second half (we also use first half and reverse of second half) for every index. Below is complete algorithm."
},
{
"code": null,
"e": 29268,
"s": 28053,
"text": " 1) The first character is always a palindrome, so print yes for \n first character.\n\n 2) Initialize reverse of first half as \"a\" and second half as \"b\". \n Let the hash value of first half reverse be 'firstr' and that of \n second half be 'second'.\n\n 3) Iterate through string starting from second character, do following\n for every character str[i], i.e., i varies from 1 to n-1.\n a) If 'firstr' and 'second' are same, then character by character \n check the substring ending with current character and print \n \"Yes\" if palindrome.\n Note that if hash values match, then strings need not be same.\n For example, hash values of \"ab\" and \"ba\" are same, but strings\n are different. That is why we check complete string after hash.\n\n b) Update 'firstr' and 'second' for next iteration. \n If 'i' is even, then add next character to the beginning of \n 'firstr' and end of second half and update \n hash values.\n If 'i' is odd, then keep 'firstr' as it is, remove leading \n character from second and append a next \n character at end.\n"
},
{
"code": null,
"e": 29316,
"s": 29268,
"text": "Let us see all steps for example string “abcba”"
},
{
"code": null,
"e": 29402,
"s": 29316,
"text": "Initial values of ‘firstr’ and ‘second’ firstr’ = hash(“a”), ‘second’ = hash(“b”)"
},
{
"code": null,
"e": 29647,
"s": 29402,
"text": "Start from second character, i.e.,i = 1 a) Compare ‘firstr’ and ‘second’, they don’t match, so print no. b) Calculate hash values for next iteration, i.e., i = 2 Since i is odd, ‘firstr’ is not changed and ‘second’ becomes hash(“c”)"
},
{
"code": null,
"e": 29864,
"s": 29647,
"text": "i = 2 a) Compare ‘firstr’ and ‘second’, they don’t match, so print no. b) Calculate hash values for next iteration, i.e., i = 3 Since i is even, ‘firstr’ becomes hash(“ba”) and ‘second’ becomes hash(“cb”)"
},
{
"code": null,
"e": 30075,
"s": 29864,
"text": "i = 3 a) Compare ‘first’ and ‘second’, they don’t match, so print no. b) Calculate hash values for next iteration, i.e., i = 4 Since i is odd, ‘firstr’ is not changed and ‘second’ becomes hash(“ba”)"
},
{
"code": null,
"e": 30242,
"s": 30075,
"text": "i = 4 a) ‘firstr’ and ‘second’ match, compare the whole strings, they match, so print yes b) We don’t need to calculate next hash values as this is last index"
},
{
"code": null,
"e": 30401,
"s": 30242,
"text": "The idea of using rolling hashes is, next hash value can be calculated from previous in O(1) time by just doing some constant number of arithmetic operations."
},
{
"code": null,
"e": 30450,
"s": 30401,
"text": "Below are the implementations of above approach."
},
{
"code": null,
"e": 30456,
"s": 30450,
"text": "C/C++"
},
{
"code": null,
"e": 30461,
"s": 30456,
"text": "Java"
},
{
"code": null,
"e": 30468,
"s": 30461,
"text": "Python"
},
{
"code": null,
"e": 30471,
"s": 30468,
"text": "C#"
},
{
"code": "// C program for online algorithm for palindrome checking#include<stdio.h>#include<string.h> // d is the number of characters in input alphabet#define d 256 // q is a prime number used for evaluating Rabin Karp's Rolling hash#define q 103 void checkPalindromes(char str[]){ // Length of input string int N = strlen(str); // A single character is always a palindrome printf(\"%c Yes\\n\", str[0]); // Return if string has only one character if (N == 1) return; // Initialize first half reverse and second half for // as firstr and second characters int firstr = str[0] % q; int second = str[1] % q; int h = 1, i, j; // Now check for palindromes from second character // onward for (i=1; i<N; i++) { // If the hash values of 'firstr' and 'second' // match, then only check individual characters if (firstr == second) { /* Check if str[0..i] is palindrome using simple character by character match */ for (j = 0; j < i/2; j++) { if (str[j] != str[i-j]) break; } (j == i/2)? printf(\"%c Yes\\n\", str[i]): printf(\"%c No\\n\", str[i]); } else printf(\"%c No\\n\", str[i]); // Calculate hash values for next iteration. // Don't calculate hash for next characters if // this is the last character of string if (i != N-1) { // If i is even (next i is odd) if (i%2 == 0) { // Add next character after first half at beginning // of 'firstr' h = (h*d) % q; firstr = (firstr + h*str[i/2])%q; // Add next character after second half at the end // of second half. second = (second*d + str[i+1])%q; } else { // If next i is odd (next i is even) then we // need not to change firstr, we need to remove // first character of second and append a // character to it. second = (d*(second + q - str[(i+1)/2]*h)%q + str[i+1])%q; } } }} /* Driver program to test above function */int main(){ char *txt = \"aabaacaabaa\"; checkPalindromes(txt); getchar(); return 0;}",
"e": 32882,
"s": 30471,
"text": null
},
{
"code": "// Java program for online algorithm for// palindrome checkingpublic class GFG { // d is the number of characters in // input alphabet static final int d = 256; // q is a prime number used for // evaluating Rabin Karp's Rolling hash static final int q = 103; static void checkPalindromes(String str) { // Length of input string int N = str.length(); // A single character is always a palindrome System.out.println(str.charAt(0)+\" Yes\"); // Return if string has only one character if (N == 1) return; // Initialize first half reverse and second // half for as firstr and second characters int firstr = str.charAt(0) % q; int second = str.charAt(1) % q; int h = 1, i, j; // Now check for palindromes from second // character onward for (i = 1; i < N; i++) { // If the hash values of 'firstr' and // 'second' match, then only check // individual characters if (firstr == second) { /* Check if str[0..i] is palindrome using simple character by character match */ for (j = 0; j < i/2; j++) { if (str.charAt(j) != str.charAt(i - j)) break; } System.out.println((j == i/2) ? str.charAt(i) + \" Yes\": str.charAt(i)+ \" No\"); } else System.out.println(str.charAt(i)+ \" No\"); // Calculate hash values for next iteration. // Don't calculate hash for next characters // if this is the last character of string if (i != N - 1) { // If i is even (next i is odd) if (i % 2 == 0) { // Add next character after first // half at beginning of 'firstr' h = (h * d) % q; firstr = (firstr + h *str.charAt(i / 2)) % q; // Add next character after second // half at the end of second half. second = (second * d + str.charAt(i + 1)) % q; } else { // If next i is odd (next i is even) // then we need not to change firstr, // we need to remove first character // of second and append a character // to it. second = (d * (second + q - str.charAt( (i + 1) / 2) * h) % q + str.charAt(i + 1)) % q; } } } } /* Driver program to test above function */ public static void main(String args[]) { String txt = \"aabaacaabaa\"; checkPalindromes(txt); }}// This code is contributed by Sumit Ghosh",
"e": 36085,
"s": 32882,
"text": null
},
{
"code": "# Python program Online algorithm for checking palindrome# in a stream # d is the number of characters in input alphabetd = 256 # q is a prime number used for evaluating Rabin Karp's# Rolling hashq = 103 def checkPalindromes(string): # Length of input string N = len(string) # A single character is always a palindrome print string[0] + \" Yes\" # Return if string has only one character if N == 1: return # Initialize first half reverse and second half for # as firstr and second characters firstr = ord(string[0]) % q second = ord(string[1]) % q h = 1 i = 0 j = 0 # Now check for palindromes from second character # onward for i in xrange(1,N): # If the hash values of 'firstr' and 'second' # match, then only check individual characters if firstr == second: # Check if str[0..i] is palindrome using # simple character by character match for j in xrange(0,i/2): if string[j] != string[i-j]: break j += 1 if j == i/2: print string[i] + \" Yes\" else: print string[i] + \" No\" else: print string[i] + \" No\" # Calculate hash values for next iteration. # Don't calculate hash for next characters if # this is the last character of string if i != N-1: # If i is even (next i is odd) if i % 2 == 0: # Add next character after first half at # beginning of 'firstr' h = (h*d) % q firstr = (firstr + h*ord(string[i/2]))%q # Add next character after second half at # the end of second half. second = (second*d + ord(string[i+1]))%q else: # If next i is odd (next i is even) then we # need not to change firstr, we need to remove # first character of second and append a # character to it. second = (d*(second + q - ord(string[(i+1)/2])*h)%q + ord(string[i+1]))%q # Driver programtxt = \"aabaacaabaa\"checkPalindromes(txt)# This code is contributed by Bhavya Jain",
"e": 38353,
"s": 36085,
"text": null
},
{
"code": "// C# program for online algorithm for // palindrome checking using System; class GFG{// d is the number of characters // in input alphabet public const int d = 256; // q is a prime number used for // evaluating Rabin Karp's Rolling hash public const int q = 103; public static void checkPalindromes(string str){ // Length of input string int N = str.Length; // A single character is always // a palindrome Console.WriteLine(str[0] + \" Yes\"); // Return if string has only // one character if (N == 1) { return; } // Initialize first half reverse and second // half for as firstr and second characters int firstr = str[0] % q; int second = str[1] % q; int h = 1, i, j; // Now check for palindromes from // second character onward for (i = 1; i < N; i++) { // If the hash values of 'firstr' // and 'second' match, then only // check individual characters if (firstr == second) { /* Check if str[0..i] is palindrome using simple character by character match */ for (j = 0; j < i / 2; j++) { if (str[j] != str[i - j]) { break; } } Console.WriteLine((j == i / 2) ? str[i] + \" Yes\": str[i] + \" No\"); } else { Console.WriteLine(str[i] + \" No\"); } // Calculate hash values for next iteration. // Don't calculate hash for next characters // if this is the last character of string if (i != N - 1) { // If i is even (next i is odd) if (i % 2 == 0) { // Add next character after first // half at beginning of 'firstr' h = (h * d) % q; firstr = (firstr + h * str[i / 2]) % q; // Add next character after second // half at the end of second half. second = (second * d + str[i + 1]) % q; } else { // If next i is odd (next i is even) // then we need not to change firstr, // we need to remove first character // of second and append a character // to it. second = (d * (second + q - str[(i + 1) / 2] * h) % q + str[i + 1]) % q; } } }} // Driver Codepublic static void Main(string[] args){ string txt = \"aabaacaabaa\"; checkPalindromes(txt);}} // This code is contributed by Shrikant13",
"e": 41034,
"s": 38353,
"text": null
},
{
"code": null,
"e": 41093,
"s": 41034,
"text": "a Yes\na Yes\nb No\na No\na Yes\nc No\na No\na No\nb No\na No\na Yes"
},
{
"code": null,
"e": 41391,
"s": 41093,
"text": "The worst case time complexity of the above solution remains O(n*n), but in general, it works much better than simple approach as we avoid complete substring comparison most of the time by first comparing hash values. The worst case occurs for input strings with all same characters like “aaaaaa”."
},
{
"code": null,
"e": 41553,
"s": 41391,
"text": "This article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 41565,
"s": 41553,
"text": "shrikanth13"
},
{
"code": null,
"e": 41578,
"s": 41565,
"text": "array-stream"
},
{
"code": null,
"e": 41589,
"s": 41578,
"text": "palindrome"
},
{
"code": null,
"e": 41607,
"s": 41589,
"text": "Pattern Searching"
},
{
"code": null,
"e": 41615,
"s": 41607,
"text": "Strings"
},
{
"code": null,
"e": 41623,
"s": 41615,
"text": "Strings"
},
{
"code": null,
"e": 41634,
"s": 41623,
"text": "palindrome"
},
{
"code": null,
"e": 41652,
"s": 41634,
"text": "Pattern Searching"
},
{
"code": null,
"e": 41750,
"s": 41652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41806,
"s": 41750,
"text": "Removing string that is an anagram of an earlier string"
},
{
"code": null,
"e": 41880,
"s": 41806,
"text": "Count N-length strings consisting only of vowels sorted lexicographically"
},
{
"code": null,
"e": 41926,
"s": 41880,
"text": "Boyer Moore Algorithm | Good Suffix heuristic"
},
{
"code": null,
"e": 41990,
"s": 41926,
"text": "Check whether two strings contain same characters in same order"
},
{
"code": null,
"e": 42059,
"s": 41990,
"text": "How to check Aadhaar number is valid or not using Regular Expression"
},
{
"code": null,
"e": 42105,
"s": 42059,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 42130,
"s": 42105,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 42190,
"s": 42130,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 42205,
"s": 42190,
"text": "C++ Data Types"
}
] |
Check whether N is a Factorion or not - GeeksforGeeks
|
13 Mar, 2022
Given an integer N and the task is to check whether N is a Factorion or not. A Factorion is a number which is equal to the sum of the factorials of its digits.Examples:
Input: N = 40585 Output: Yes 4! + 0! + 5! + 8! + 5! = 40585Input: N = 234 Output: No 2! + 3! + 4! = 32
Approach: Create an array fact[] of size 10 to store the factorials of all possible digits where fact[i] stores i!. Now for all the digits of the given number find the sum of factorials of the digits using the fact[] array computed earlier. If the sum if equal to the given number then the number is a Factorion else it is not.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 10 // Function that returns true// if n is a Factorionbool isFactorion(int n){ // fact[i] will store i! int fact[MAX]; fact[0] = 1; for (int i = 1; i < MAX; i++) fact[i] = i * fact[i - 1]; // A copy of the given integer int org = n; // To store the sum of factorials // of the digits of n int sum = 0; while (n > 0) { // Get the last digit int d = n % 10; // Add the factorial of the current // digit to the sum sum += fact[d]; // Remove the last digit n /= 10; } if (sum == org) return true; return false;} // Driver codeint main(){ int n = 40585; if (isFactorion(n)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the above approachclass GFG{ static int MAX = 10; // Function that returns true // if n is a Factorion static boolean isFactorion(int n) { // fact[i] will store i! int fact[] = new int[MAX]; fact[0] = 1; for (int i = 1; i < MAX; i++) fact[i] = i * fact[i - 1]; // A copy of the given integer int org = n; // To store the sum of factorials // of the digits of n int sum = 0; while (n > 0) { // Get the last digit int d = n % 10; // Add the factorial of the current // digit to the sum sum += fact[d]; // Remove the last digit n /= 10; } if (sum == org) return true; return false; } // Driver code public static void main (String[] args) { int n = 40585; if (isFactorion(n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approachMAX = 10 # Function that returns true# if n is a Factoriondef isFactorion(n) : # fact[i] will store i! fact = [0] * MAX fact[0] = 1 for i in range(1, MAX) : fact[i] = i * fact[i - 1] # A copy of the given integer org = n # To store the sum of factorials # of the digits of n sum = 0 while (n > 0) : # Get the last digit d = n % 10 # Add the factorial of the current # digit to the sum sum += fact[d] # Remove the last digit n = n // 10 if (sum == org): return True return False # Driver coden = 40585 if (isFactorion(n)): print("Yes")else: print("No") # This code is contributed by# divyamohan123
// C# implementation of the above approachusing System; class GFG{ static int MAX = 10; // Function that returns true // if n is a Factorion static bool isFactorion(int n) { // fact[i] will store i! int [] fact = new int[MAX]; fact[0] = 1; for (int i = 1; i < MAX; i++) fact[i] = i * fact[i - 1]; // A copy of the given integer int org = n; // To store the sum of factorials // of the digits of n int sum = 0; while (n > 0) { // Get the last digit int d = n % 10; // Add the factorial of the current // digit to the sum sum += fact[d]; // Remove the last digit n /= 10; } if (sum == org) return true; return false; } // Driver code public static void Main (String[] args) { int n = 40585; if (isFactorion(n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Mohit kumar
<script>// Javascript implementation of the approach const MAX = 10; // Function that returns true// if n is a Factorionfunction isFactorion(n){ // fact[i] will store i! let fact = new Array(MAX); fact[0] = 1; for (let i = 1; i < MAX; i++) fact[i] = i * fact[i - 1]; // A copy of the given integer let org = n; // To store the sum of factorials // of the digits of n let sum = 0; while (n > 0) { // Get the last digit let d = n % 10; // Add the factorial of the current // digit to the sum sum += fact[d]; // Remove the last digit n = parseInt(n / 10); } if (sum == org) return true; return false;} // Driver code let n = 40585; if (isFactorion(n)) document.write("Yes"); else document.write("No"); </script>
Yes
Time Complexity: O(log10n)
Auxiliary Space: O(MAX)
divyamohan123
ankthon
mohit kumar 29
subhammahato348
factorial
Arrays
Mathematical
Arrays
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Program for Fibonacci numbers
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
|
[
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n13 Mar, 2022"
},
{
"code": null,
"e": 26212,
"s": 26041,
"text": "Given an integer N and the task is to check whether N is a Factorion or not. A Factorion is a number which is equal to the sum of the factorials of its digits.Examples: "
},
{
"code": null,
"e": 26317,
"s": 26212,
"text": "Input: N = 40585 Output: Yes 4! + 0! + 5! + 8! + 5! = 40585Input: N = 234 Output: No 2! + 3! + 4! = 32 "
},
{
"code": null,
"e": 26697,
"s": 26317,
"text": "Approach: Create an array fact[] of size 10 to store the factorials of all possible digits where fact[i] stores i!. Now for all the digits of the given number find the sum of factorials of the digits using the fact[] array computed earlier. If the sum if equal to the given number then the number is a Factorion else it is not.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26701,
"s": 26697,
"text": "C++"
},
{
"code": null,
"e": 26706,
"s": 26701,
"text": "Java"
},
{
"code": null,
"e": 26714,
"s": 26706,
"text": "Python3"
},
{
"code": null,
"e": 26717,
"s": 26714,
"text": "C#"
},
{
"code": null,
"e": 26728,
"s": 26717,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 10 // Function that returns true// if n is a Factorionbool isFactorion(int n){ // fact[i] will store i! int fact[MAX]; fact[0] = 1; for (int i = 1; i < MAX; i++) fact[i] = i * fact[i - 1]; // A copy of the given integer int org = n; // To store the sum of factorials // of the digits of n int sum = 0; while (n > 0) { // Get the last digit int d = n % 10; // Add the factorial of the current // digit to the sum sum += fact[d]; // Remove the last digit n /= 10; } if (sum == org) return true; return false;} // Driver codeint main(){ int n = 40585; if (isFactorion(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 27573,
"s": 26728,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG{ static int MAX = 10; // Function that returns true // if n is a Factorion static boolean isFactorion(int n) { // fact[i] will store i! int fact[] = new int[MAX]; fact[0] = 1; for (int i = 1; i < MAX; i++) fact[i] = i * fact[i - 1]; // A copy of the given integer int org = n; // To store the sum of factorials // of the digits of n int sum = 0; while (n > 0) { // Get the last digit int d = n % 10; // Add the factorial of the current // digit to the sum sum += fact[d]; // Remove the last digit n /= 10; } if (sum == org) return true; return false; } // Driver code public static void main (String[] args) { int n = 40585; if (isFactorion(n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by AnkitRai01",
"e": 28699,
"s": 27573,
"text": null
},
{
"code": "# Python3 implementation of the approachMAX = 10 # Function that returns true# if n is a Factoriondef isFactorion(n) : # fact[i] will store i! fact = [0] * MAX fact[0] = 1 for i in range(1, MAX) : fact[i] = i * fact[i - 1] # A copy of the given integer org = n # To store the sum of factorials # of the digits of n sum = 0 while (n > 0) : # Get the last digit d = n % 10 # Add the factorial of the current # digit to the sum sum += fact[d] # Remove the last digit n = n // 10 if (sum == org): return True return False # Driver coden = 40585 if (isFactorion(n)): print(\"Yes\")else: print(\"No\") # This code is contributed by# divyamohan123",
"e": 29461,
"s": 28699,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ static int MAX = 10; // Function that returns true // if n is a Factorion static bool isFactorion(int n) { // fact[i] will store i! int [] fact = new int[MAX]; fact[0] = 1; for (int i = 1; i < MAX; i++) fact[i] = i * fact[i - 1]; // A copy of the given integer int org = n; // To store the sum of factorials // of the digits of n int sum = 0; while (n > 0) { // Get the last digit int d = n % 10; // Add the factorial of the current // digit to the sum sum += fact[d]; // Remove the last digit n /= 10; } if (sum == org) return true; return false; } // Driver code public static void Main (String[] args) { int n = 40585; if (isFactorion(n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Mohit kumar",
"e": 30596,
"s": 29461,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach const MAX = 10; // Function that returns true// if n is a Factorionfunction isFactorion(n){ // fact[i] will store i! let fact = new Array(MAX); fact[0] = 1; for (let i = 1; i < MAX; i++) fact[i] = i * fact[i - 1]; // A copy of the given integer let org = n; // To store the sum of factorials // of the digits of n let sum = 0; while (n > 0) { // Get the last digit let d = n % 10; // Add the factorial of the current // digit to the sum sum += fact[d]; // Remove the last digit n = parseInt(n / 10); } if (sum == org) return true; return false;} // Driver code let n = 40585; if (isFactorion(n)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 31438,
"s": 30596,
"text": null
},
{
"code": null,
"e": 31442,
"s": 31438,
"text": "Yes"
},
{
"code": null,
"e": 31471,
"s": 31444,
"text": "Time Complexity: O(log10n)"
},
{
"code": null,
"e": 31495,
"s": 31471,
"text": "Auxiliary Space: O(MAX)"
},
{
"code": null,
"e": 31509,
"s": 31495,
"text": "divyamohan123"
},
{
"code": null,
"e": 31517,
"s": 31509,
"text": "ankthon"
},
{
"code": null,
"e": 31532,
"s": 31517,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31548,
"s": 31532,
"text": "subhammahato348"
},
{
"code": null,
"e": 31558,
"s": 31548,
"text": "factorial"
},
{
"code": null,
"e": 31565,
"s": 31558,
"text": "Arrays"
},
{
"code": null,
"e": 31578,
"s": 31565,
"text": "Mathematical"
},
{
"code": null,
"e": 31585,
"s": 31578,
"text": "Arrays"
},
{
"code": null,
"e": 31598,
"s": 31585,
"text": "Mathematical"
},
{
"code": null,
"e": 31608,
"s": 31598,
"text": "factorial"
},
{
"code": null,
"e": 31706,
"s": 31608,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31733,
"s": 31706,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 31764,
"s": 31733,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 31789,
"s": 31764,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31827,
"s": 31789,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31848,
"s": 31827,
"text": "Next Greater Element"
},
{
"code": null,
"e": 31878,
"s": 31848,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31938,
"s": 31878,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31953,
"s": 31938,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31996,
"s": 31953,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to Get Centered Content in Bootstrap ? - GeeksforGeeks
|
24 Apr, 2021
The task is to center content using bootstrap. The approach of this article is to get a Centered Content in Bootstrap by using a simple in-built class .text-center to center align all the inline elements like text, images, links, etc. under a block element i.e <div> or <p> element.
Note: This solution only works in the Bootstrap 3 or 4 versions.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Text Centering in Bootstrap</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <style> .bs-example { margin: 20px; } </style></head> <body> <div class="bs-example"> <div class="container"> <div class="row"> <div class="col-lg-12 bg-light text-center"> <h1>GeeksforGeeks</h1> <h2>How to Get Centered Content in Bootstrap? . </h2> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo" height="200px"> </div> </div> </div> </div></body> </html>
Output:
Bootstrap-4
Bootstrap-Questions
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to keep gap between columns using Bootstrap?
Tailwind CSS vs Bootstrap
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26865,
"s": 26837,
"text": "\n24 Apr, 2021"
},
{
"code": null,
"e": 27149,
"s": 26865,
"text": "The task is to center content using bootstrap. The approach of this article is to get a Centered Content in Bootstrap by using a simple in-built class .text-center to center align all the inline elements like text, images, links, etc. under a block element i.e <div> or <p> element. "
},
{
"code": null,
"e": 27215,
"s": 27149,
"text": "Note: This solution only works in the Bootstrap 3 or 4 versions. "
},
{
"code": null,
"e": 27225,
"s": 27215,
"text": "Example: "
},
{
"code": null,
"e": 27230,
"s": 27225,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <title>Text Centering in Bootstrap</title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\"> <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\"></script> <style> .bs-example { margin: 20px; } </style></head> <body> <div class=\"bs-example\"> <div class=\"container\"> <div class=\"row\"> <div class=\"col-lg-12 bg-light text-center\"> <h1>GeeksforGeeks</h1> <h2>How to Get Centered Content in Bootstrap? . </h2> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\" height=\"200px\"> </div> </div> </div> </div></body> </html>",
"e": 28427,
"s": 27230,
"text": null
},
{
"code": null,
"e": 28435,
"s": 28427,
"text": "Output:"
},
{
"code": null,
"e": 28447,
"s": 28435,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 28467,
"s": 28447,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 28477,
"s": 28467,
"text": "Bootstrap"
},
{
"code": null,
"e": 28494,
"s": 28477,
"text": "Web Technologies"
},
{
"code": null,
"e": 28592,
"s": 28494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28633,
"s": 28592,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 28696,
"s": 28633,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 28729,
"s": 28696,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 28778,
"s": 28729,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 28804,
"s": 28778,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 28844,
"s": 28804,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28877,
"s": 28844,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28922,
"s": 28877,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28965,
"s": 28922,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Lodash _.defer() Method - GeeksforGeeks
|
29 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.defer() method in lodash is used to defer the calling of func parameter until the recent call stack is cleared. Moreover, any further arguments are provided to func parameter of this method when it is called.
Syntax:
_.defer(func, [args])
Parameters: This method accepts two parameters which are described below:
func: It is the function which is to be deferred.
[args]: It is the arguments with which the func is being called.
Return Value: This method returns the timer id.
Example 1:
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Calling defer() method with// its parameter_.defer(function(content) { console.log(content);}, 'GeeksforGeeks!'); // Prints content after thisconsole.log('Content:');
Output:
Content:
GeeksforGeeks!
Example 2:
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Defining func parameterlet func = number => { console.log(number);}; // Defining for loopfor(let i = 1; i <= 5; i++) { // Calling defer() method // with its parameter _.defer(func, i);} // Prints integer after thisconsole.log('Integers are as follows:');
Output:
Integers are as follows:
1
2
3
4
5
Reference: https://lodash.com/docs/4.17.15#defer
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 38681,
"s": 38653,
"text": "\n29 Sep, 2020"
},
{
"code": null,
"e": 38821,
"s": 38681,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 39036,
"s": 38821,
"text": "The _.defer() method in lodash is used to defer the calling of func parameter until the recent call stack is cleared. Moreover, any further arguments are provided to func parameter of this method when it is called."
},
{
"code": null,
"e": 39044,
"s": 39036,
"text": "Syntax:"
},
{
"code": null,
"e": 39066,
"s": 39044,
"text": "_.defer(func, [args])"
},
{
"code": null,
"e": 39140,
"s": 39066,
"text": "Parameters: This method accepts two parameters which are described below:"
},
{
"code": null,
"e": 39190,
"s": 39140,
"text": "func: It is the function which is to be deferred."
},
{
"code": null,
"e": 39255,
"s": 39190,
"text": "[args]: It is the arguments with which the func is being called."
},
{
"code": null,
"e": 39303,
"s": 39255,
"text": "Return Value: This method returns the timer id."
},
{
"code": null,
"e": 39314,
"s": 39303,
"text": "Example 1:"
},
{
"code": null,
"e": 39325,
"s": 39314,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Calling defer() method with// its parameter_.defer(function(content) { console.log(content);}, 'GeeksforGeeks!'); // Prints content after thisconsole.log('Content:');",
"e": 39554,
"s": 39325,
"text": null
},
{
"code": null,
"e": 39562,
"s": 39554,
"text": "Output:"
},
{
"code": null,
"e": 39586,
"s": 39562,
"text": "Content:\nGeeksforGeeks!"
},
{
"code": null,
"e": 39597,
"s": 39586,
"text": "Example 2:"
},
{
"code": null,
"e": 39608,
"s": 39597,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Defining func parameterlet func = number => { console.log(number);}; // Defining for loopfor(let i = 1; i <= 5; i++) { // Calling defer() method // with its parameter _.defer(func, i);} // Prints integer after thisconsole.log('Integers are as follows:');",
"e": 39941,
"s": 39608,
"text": null
},
{
"code": null,
"e": 39949,
"s": 39941,
"text": "Output:"
},
{
"code": null,
"e": 39984,
"s": 39949,
"text": "Integers are as follows:\n1\n2\n3\n4\n5"
},
{
"code": null,
"e": 40033,
"s": 39984,
"text": "Reference: https://lodash.com/docs/4.17.15#defer"
},
{
"code": null,
"e": 40051,
"s": 40033,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 40062,
"s": 40051,
"text": "JavaScript"
},
{
"code": null,
"e": 40079,
"s": 40062,
"text": "Web Technologies"
},
{
"code": null,
"e": 40177,
"s": 40079,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40217,
"s": 40177,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 40262,
"s": 40217,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40323,
"s": 40262,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 40395,
"s": 40323,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 40464,
"s": 40395,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 40504,
"s": 40464,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 40537,
"s": 40504,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 40582,
"s": 40537,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40625,
"s": 40582,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Print a pattern without using any loop - GeeksforGeeks
|
11 Sep, 2021
Given a number n, print following a pattern without using any loop.
Examples :
Input: n = 16
Output: 16, 11, 6, 1, -4, 1, 6, 11, 16
Input: n = 10
Output: 10, 5, 0, 5, 10
We basically first reduce 5 one by one until we reach a negative or 0. After we reach 0 or negative, we one add 5 until we reach n.Source: Microsoft Interview Question.
The idea is to use recursion. It is an interesting question to try on your own. Below is the Code. The code uses a flag variable to indicate whether we are moving toward 0 or we are moving toward the back to n.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print pattern that first reduces 5 one// by one, then adds 5. Without any loop#include <iostream>using namespace std; // Recursive function to print the pattern.// n indicates input value// m indicates current value to be printed// flag indicates whether we need to add 5 or// subtract 5. Initially flag is true.void printPattern(int n, int m, bool flag){ // Print m. cout << m << " "; // If we are moving back toward the n and // we have reached there, then we are done if (flag == false && n ==m) return; // If we are moving toward 0 or negative. if (flag) { // If m is greater, then 5, recur with true flag if (m-5 > 0) printPattern(n, m-5, true); else // recur with false flag printPattern(n, m-5, false); } else // If flag is false. printPattern(n, m+5, false);} // Recursive function to print the pattern// variance where m is the input int32 valuevoid PrintPattern(int m){ if (m > 0) { cout << m << '\n'; PrintPattern(m - 5); } cout << m << '\n';} // Driver Programint main(){ int n = 16; //printPattern(n, n, true); PrintPattern(n); return 0;}
// Java program to print pattern that first reduces 5 one// by one, then adds 5. Without any loopimport java.io.*; class GFG { // Recursive function to print the pattern. // n indicates input value // m indicates current value to be printed // flag indicates whether we need to add 5 or // subtract 5. Initially flag is true. static void printPattern(int n, int m, boolean flag) { // Print m. System.out.print(m + " "); // If we are moving back toward the n and // we have reached there, then we are done if (flag == false && n == m) return; // If we are moving toward 0 or negative. if (flag) { // If m is greater, then 5, recur with // true flag if (m - 5 > 0) printPattern(n, m - 5, true); else // recur with false flag printPattern(n, m - 5, false); } else // If flag is false. printPattern(n, m + 5, false); } // Driver Program public static void main(String[] args) { int n = 16; printPattern(n, n, true); }}// This code is contributed by vt_m
# Python program to print pattern# that first reduces 5 one by one,# then adds 5. Without any loop. # Recursive function to print# the pattern.n indicates# input value m indicates# current value to be printed# flag indicates whether we# need to add 5 or subtract 5.# Initially flag is True.def printPattern(n, m, flag): # Print m. print(m) # If we are moving back # toward the n and we # have reached there, # then we are done if flag == False and n == m: return # If we are moving # toward 0 or negative. if flag: # If m is greater, then 5, # recur with true flag if m - 5 > 0: printPattern(n, m - 5, True) else: # recur with false flag printPattern(n, m - 5, False) else: # If flag is false. printPattern(n, m + 5, False) # Driver Coden = 16printPattern(n, n, True) # This code is contributed# by HrushikeshChoudhary
// C# program to print pattern that first reduces 5 one// by one, then adds 5. Without any loopusing System; class GFG { // Recursive function to print the pattern. // n indicates input value // m indicates current value to be printed // flag indicates whether we need to add 5 or // subtract 5. Initially flag is true. static void printPattern(int n, int m, bool flag) { // Print m. Console.Write(m + " "); // If we are moving back toward the n and // we have reached there, then we are done if (flag == false && n == m) return; // If we are moving toward 0 or negative. if (flag) { // If m is greater, then 5, recur with // true flag if (m - 5 > 0) printPattern(n, m - 5, true); else // recur with false flag printPattern(n, m - 5, false); } else // If flag is false. printPattern(n, m + 5, false); } // Driver Program public static void Main() { int n = 16; printPattern(n, n, true); }}// This code is contributed by vt_m
<?php// PHP program to print pattern// that first reduces 5 one by one,// then adds 5. Without any loop // Recursive function to print// the pattern. n indicates input// value m indicates current value// to be printed flag indicates whether// we need to add 5 or subtract 5.// Initially flag is true.function printPattern($n, $m, $flag){ // Print m. echo $m ," "; // If we are moving back // toward the n and we // have reached there, // then we are done if ($flag == false && $n == $m) return; // If we are moving // toward 0 or negative. if ($flag) { // If m is greater, then 5, // recur with true flag if ($m - 5 > 0) printPattern($n, $m - 5, true); // recur with false flag else printPattern($n, $m - 5, false); } // If flag is false. else printPattern($n, $m + 5, false);} // Driver Code$n = 16;printPattern($n, $n, true); // This code is contributed by m_kit?>
<script> // Javascript program to print pattern that// first reduces 5 one by one, then adds 5.// Without any loop // Recursive function to print the pattern.// n indicates input value m indicates current// value to be printed flag indicates whether// we need to add 5 or subtract 5. Initially// flag is true.function printPattern(n, m, flag){ // Print m. document.write(m + " "); // If we are moving back toward the n and // we have reached there, then we are done if (flag == false && n == m) return; // If we are moving toward 0 or negative. if (flag) { // If m is greater, then 5, recur with // true flag if (m - 5 > 0) printPattern(n, m - 5, true); // Recur with false flag else printPattern(n, m - 5, false); } // If flag is false. else printPattern(n, m + 5, false);} // Driver codelet n = 16;printPattern(n, n, true); // This code is contributed by divyeshrabadiya07 </script>
Output :
16, 11, 6, 1, -4, 1, 6, 11, 16
How to print above pattern without any extra variable and loop? The above program works fine and prints the desired out but uses extra variables. We can use two print statements. First one before the recursive call that prints all decreasing sequence. The second one after the recursive call to print increasing sequence.
Below is the implementation of the idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print pattern that first reduces 5 one// by one, then adds 5. Without any loop an extra variable.#include <iostream>using namespace std; // Recursive function to print the pattern without any extra// variablevoid printPattern(int n){ // Base case (When n becomes 0 or negative) if (n ==0 || n<0) { cout << n << " "; return; } // First print decreasing order cout << n << " "; printPattern(n-5); // Then print increasing order cout << n << " ";} // Driver Programint main(){ int n = 16; printPattern(n); return 0;}
// Java program to print pattern that first// reduces 5 one by one, then adds 5.// Without any loop an extra variable. import java.io.*; class GFG { // Recursive function to print the // pattern without any extra variable static void printPattern(int n) { // Base case (When n becomes 0 or // negative) if (n == 0 || n < 0) { System.out.print(n + " "); return; } // First print decreasing order System.out.print(n + " "); printPattern(n - 5); // Then print increasing order System.out.print(n + " "); } // Driver Program public static void main(String[] args) { int n = 16; printPattern(n); }} // This code is contributed by vt_m
# Python3 program to print pattern that# first reduces 5 one by one, then adds 5.# Without any loop an extra variable. # Recursive function to print the pattern# without any extra variabledef printPattern(n): # Base case (When n becomes 0 or negative) if (n == 0 or n < 0): print(n, end = ", ") return # First print decreasing order print(n, end = ", ") printPattern(n - 5) # Then print increasing order print(n, end = ", ") # Driver Coden = 16printPattern(n) # This code is contributed by# Mohit kumar 29
// C# program to print pattern that first// reduces 5 one by one, then adds 5.// Without any loop an extra variable. using System; class GFG { // Recursive function to print the // pattern without any extra variable static void printPattern(int n) { // Base case (When n becomes 0 or // negative) if (n == 0 || n < 0) { Console.Write(n + " "); return; } // First print decreasing order Console.Write(n + " "); printPattern(n - 5); // Then print increasing order Console.Write(n + " "); } // Driver Program public static void Main() { int n = 16; printPattern(n); }} // This code is contributed by vt_m
<?php// PHP program to print pattern// that first reduces 5 one// by one, then adds 5. Without// any loop an extra variable. // Recursive function to print the// pattern without any extra variablefunction printPattern( $n){ // Base case (When n becomes // 0 or negative) if ($n == 0 or $n < 0) { echo $n , " "; return; } // First print decreasing order echo $n , " "; printPattern($n-5); // Then print increasing order echo $n , " ";} // Driver Code $n = 16; printPattern($n); // This code is contributed by anuj_67.?>
<script> // Javascript program to print pattern that first reduces 5 one // by one, then adds 5. Without any loop an extra variable. // Recursive function to print the pattern without any extra // variable function printPattern(n) { // Base case (When n becomes 0 or negative) if (n == 0 || n < 0) { document.write(n + ", "); return; } // First print decreasing order document.write(n + ", "); printPattern(n - 5); // Then print increasing order document.write(n + ", "); } let n = 16; printPattern(n); // This code is contributed by suresh07.</script>
Output:
16, 11, 6, 1, -4, 1, 6, 11, 16
Thanks to AKSHAY RATHORE for suggesting the above solution.This article is contributed by Gautham. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
vt_m
HrushikeshChoudhary
mohit kumar 29
AbhijeetHaldar
Enigma341
divyeshrabadiya07
suresh07
surinderdawra388
Microsoft
pattern-printing
Misc
Recursion
Microsoft
Misc
pattern-printing
Recursion
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
fgets() and gets() in C language
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)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
|
[
{
"code": null,
"e": 26463,
"s": 26435,
"text": "\n11 Sep, 2021"
},
{
"code": null,
"e": 26531,
"s": 26463,
"text": "Given a number n, print following a pattern without using any loop."
},
{
"code": null,
"e": 26543,
"s": 26531,
"text": "Examples : "
},
{
"code": null,
"e": 26635,
"s": 26543,
"text": "Input: n = 16\nOutput: 16, 11, 6, 1, -4, 1, 6, 11, 16\n\nInput: n = 10\nOutput: 10, 5, 0, 5, 10"
},
{
"code": null,
"e": 26804,
"s": 26635,
"text": "We basically first reduce 5 one by one until we reach a negative or 0. After we reach 0 or negative, we one add 5 until we reach n.Source: Microsoft Interview Question."
},
{
"code": null,
"e": 27016,
"s": 26804,
"text": "The idea is to use recursion. It is an interesting question to try on your own. Below is the Code. The code uses a flag variable to indicate whether we are moving toward 0 or we are moving toward the back to n. "
},
{
"code": null,
"e": 27020,
"s": 27016,
"text": "C++"
},
{
"code": null,
"e": 27025,
"s": 27020,
"text": "Java"
},
{
"code": null,
"e": 27033,
"s": 27025,
"text": "Python3"
},
{
"code": null,
"e": 27036,
"s": 27033,
"text": "C#"
},
{
"code": null,
"e": 27040,
"s": 27036,
"text": "PHP"
},
{
"code": null,
"e": 27051,
"s": 27040,
"text": "Javascript"
},
{
"code": "// C++ program to print pattern that first reduces 5 one// by one, then adds 5. Without any loop#include <iostream>using namespace std; // Recursive function to print the pattern.// n indicates input value// m indicates current value to be printed// flag indicates whether we need to add 5 or// subtract 5. Initially flag is true.void printPattern(int n, int m, bool flag){ // Print m. cout << m << \" \"; // If we are moving back toward the n and // we have reached there, then we are done if (flag == false && n ==m) return; // If we are moving toward 0 or negative. if (flag) { // If m is greater, then 5, recur with true flag if (m-5 > 0) printPattern(n, m-5, true); else // recur with false flag printPattern(n, m-5, false); } else // If flag is false. printPattern(n, m+5, false);} // Recursive function to print the pattern// variance where m is the input int32 valuevoid PrintPattern(int m){ if (m > 0) { cout << m << '\\n'; PrintPattern(m - 5); } cout << m << '\\n';} // Driver Programint main(){ int n = 16; //printPattern(n, n, true); PrintPattern(n); return 0;}",
"e": 28237,
"s": 27051,
"text": null
},
{
"code": "// Java program to print pattern that first reduces 5 one// by one, then adds 5. Without any loopimport java.io.*; class GFG { // Recursive function to print the pattern. // n indicates input value // m indicates current value to be printed // flag indicates whether we need to add 5 or // subtract 5. Initially flag is true. static void printPattern(int n, int m, boolean flag) { // Print m. System.out.print(m + \" \"); // If we are moving back toward the n and // we have reached there, then we are done if (flag == false && n == m) return; // If we are moving toward 0 or negative. if (flag) { // If m is greater, then 5, recur with // true flag if (m - 5 > 0) printPattern(n, m - 5, true); else // recur with false flag printPattern(n, m - 5, false); } else // If flag is false. printPattern(n, m + 5, false); } // Driver Program public static void main(String[] args) { int n = 16; printPattern(n, n, true); }}// This code is contributed by vt_m",
"e": 29416,
"s": 28237,
"text": null
},
{
"code": "# Python program to print pattern# that first reduces 5 one by one,# then adds 5. Without any loop. # Recursive function to print# the pattern.n indicates# input value m indicates# current value to be printed# flag indicates whether we# need to add 5 or subtract 5.# Initially flag is True.def printPattern(n, m, flag): # Print m. print(m) # If we are moving back # toward the n and we # have reached there, # then we are done if flag == False and n == m: return # If we are moving # toward 0 or negative. if flag: # If m is greater, then 5, # recur with true flag if m - 5 > 0: printPattern(n, m - 5, True) else: # recur with false flag printPattern(n, m - 5, False) else: # If flag is false. printPattern(n, m + 5, False) # Driver Coden = 16printPattern(n, n, True) # This code is contributed# by HrushikeshChoudhary",
"e": 30334,
"s": 29416,
"text": null
},
{
"code": "// C# program to print pattern that first reduces 5 one// by one, then adds 5. Without any loopusing System; class GFG { // Recursive function to print the pattern. // n indicates input value // m indicates current value to be printed // flag indicates whether we need to add 5 or // subtract 5. Initially flag is true. static void printPattern(int n, int m, bool flag) { // Print m. Console.Write(m + \" \"); // If we are moving back toward the n and // we have reached there, then we are done if (flag == false && n == m) return; // If we are moving toward 0 or negative. if (flag) { // If m is greater, then 5, recur with // true flag if (m - 5 > 0) printPattern(n, m - 5, true); else // recur with false flag printPattern(n, m - 5, false); } else // If flag is false. printPattern(n, m + 5, false); } // Driver Program public static void Main() { int n = 16; printPattern(n, n, true); }}// This code is contributed by vt_m",
"e": 31488,
"s": 30334,
"text": null
},
{
"code": "<?php// PHP program to print pattern// that first reduces 5 one by one,// then adds 5. Without any loop // Recursive function to print// the pattern. n indicates input// value m indicates current value// to be printed flag indicates whether// we need to add 5 or subtract 5.// Initially flag is true.function printPattern($n, $m, $flag){ // Print m. echo $m ,\" \"; // If we are moving back // toward the n and we // have reached there, // then we are done if ($flag == false && $n == $m) return; // If we are moving // toward 0 or negative. if ($flag) { // If m is greater, then 5, // recur with true flag if ($m - 5 > 0) printPattern($n, $m - 5, true); // recur with false flag else printPattern($n, $m - 5, false); } // If flag is false. else printPattern($n, $m + 5, false);} // Driver Code$n = 16;printPattern($n, $n, true); // This code is contributed by m_kit?>",
"e": 32460,
"s": 31488,
"text": null
},
{
"code": "<script> // Javascript program to print pattern that// first reduces 5 one by one, then adds 5.// Without any loop // Recursive function to print the pattern.// n indicates input value m indicates current// value to be printed flag indicates whether// we need to add 5 or subtract 5. Initially// flag is true.function printPattern(n, m, flag){ // Print m. document.write(m + \" \"); // If we are moving back toward the n and // we have reached there, then we are done if (flag == false && n == m) return; // If we are moving toward 0 or negative. if (flag) { // If m is greater, then 5, recur with // true flag if (m - 5 > 0) printPattern(n, m - 5, true); // Recur with false flag else printPattern(n, m - 5, false); } // If flag is false. else printPattern(n, m + 5, false);} // Driver codelet n = 16;printPattern(n, n, true); // This code is contributed by divyeshrabadiya07 </script>",
"e": 33483,
"s": 32460,
"text": null
},
{
"code": null,
"e": 33493,
"s": 33483,
"text": "Output : "
},
{
"code": null,
"e": 33524,
"s": 33493,
"text": "16, 11, 6, 1, -4, 1, 6, 11, 16"
},
{
"code": null,
"e": 33846,
"s": 33524,
"text": "How to print above pattern without any extra variable and loop? The above program works fine and prints the desired out but uses extra variables. We can use two print statements. First one before the recursive call that prints all decreasing sequence. The second one after the recursive call to print increasing sequence."
},
{
"code": null,
"e": 33887,
"s": 33846,
"text": "Below is the implementation of the idea."
},
{
"code": null,
"e": 33891,
"s": 33887,
"text": "C++"
},
{
"code": null,
"e": 33896,
"s": 33891,
"text": "Java"
},
{
"code": null,
"e": 33904,
"s": 33896,
"text": "Python3"
},
{
"code": null,
"e": 33907,
"s": 33904,
"text": "C#"
},
{
"code": null,
"e": 33911,
"s": 33907,
"text": "PHP"
},
{
"code": null,
"e": 33922,
"s": 33911,
"text": "Javascript"
},
{
"code": "// C++ program to print pattern that first reduces 5 one// by one, then adds 5. Without any loop an extra variable.#include <iostream>using namespace std; // Recursive function to print the pattern without any extra// variablevoid printPattern(int n){ // Base case (When n becomes 0 or negative) if (n ==0 || n<0) { cout << n << \" \"; return; } // First print decreasing order cout << n << \" \"; printPattern(n-5); // Then print increasing order cout << n << \" \";} // Driver Programint main(){ int n = 16; printPattern(n); return 0;}",
"e": 34510,
"s": 33922,
"text": null
},
{
"code": "// Java program to print pattern that first// reduces 5 one by one, then adds 5.// Without any loop an extra variable. import java.io.*; class GFG { // Recursive function to print the // pattern without any extra variable static void printPattern(int n) { // Base case (When n becomes 0 or // negative) if (n == 0 || n < 0) { System.out.print(n + \" \"); return; } // First print decreasing order System.out.print(n + \" \"); printPattern(n - 5); // Then print increasing order System.out.print(n + \" \"); } // Driver Program public static void main(String[] args) { int n = 16; printPattern(n); }} // This code is contributed by vt_m",
"e": 35336,
"s": 34510,
"text": null
},
{
"code": "# Python3 program to print pattern that# first reduces 5 one by one, then adds 5.# Without any loop an extra variable. # Recursive function to print the pattern# without any extra variabledef printPattern(n): # Base case (When n becomes 0 or negative) if (n == 0 or n < 0): print(n, end = \", \") return # First print decreasing order print(n, end = \", \") printPattern(n - 5) # Then print increasing order print(n, end = \", \") # Driver Coden = 16printPattern(n) # This code is contributed by# Mohit kumar 29",
"e": 35884,
"s": 35336,
"text": null
},
{
"code": "// C# program to print pattern that first// reduces 5 one by one, then adds 5.// Without any loop an extra variable. using System; class GFG { // Recursive function to print the // pattern without any extra variable static void printPattern(int n) { // Base case (When n becomes 0 or // negative) if (n == 0 || n < 0) { Console.Write(n + \" \"); return; } // First print decreasing order Console.Write(n + \" \"); printPattern(n - 5); // Then print increasing order Console.Write(n + \" \"); } // Driver Program public static void Main() { int n = 16; printPattern(n); }} // This code is contributed by vt_m",
"e": 36682,
"s": 35884,
"text": null
},
{
"code": "<?php// PHP program to print pattern// that first reduces 5 one// by one, then adds 5. Without// any loop an extra variable. // Recursive function to print the// pattern without any extra variablefunction printPattern( $n){ // Base case (When n becomes // 0 or negative) if ($n == 0 or $n < 0) { echo $n , \" \"; return; } // First print decreasing order echo $n , \" \"; printPattern($n-5); // Then print increasing order echo $n , \" \";} // Driver Code $n = 16; printPattern($n); // This code is contributed by anuj_67.?>",
"e": 37266,
"s": 36682,
"text": null
},
{
"code": "<script> // Javascript program to print pattern that first reduces 5 one // by one, then adds 5. Without any loop an extra variable. // Recursive function to print the pattern without any extra // variable function printPattern(n) { // Base case (When n becomes 0 or negative) if (n == 0 || n < 0) { document.write(n + \", \"); return; } // First print decreasing order document.write(n + \", \"); printPattern(n - 5); // Then print increasing order document.write(n + \", \"); } let n = 16; printPattern(n); // This code is contributed by suresh07.</script>",
"e": 37956,
"s": 37266,
"text": null
},
{
"code": null,
"e": 37965,
"s": 37956,
"text": "Output: "
},
{
"code": null,
"e": 37996,
"s": 37965,
"text": "16, 11, 6, 1, -4, 1, 6, 11, 16"
},
{
"code": null,
"e": 38220,
"s": 37996,
"text": "Thanks to AKSHAY RATHORE for suggesting the above solution.This article is contributed by Gautham. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 38226,
"s": 38220,
"text": "jit_t"
},
{
"code": null,
"e": 38231,
"s": 38226,
"text": "vt_m"
},
{
"code": null,
"e": 38251,
"s": 38231,
"text": "HrushikeshChoudhary"
},
{
"code": null,
"e": 38266,
"s": 38251,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 38281,
"s": 38266,
"text": "AbhijeetHaldar"
},
{
"code": null,
"e": 38291,
"s": 38281,
"text": "Enigma341"
},
{
"code": null,
"e": 38309,
"s": 38291,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 38318,
"s": 38309,
"text": "suresh07"
},
{
"code": null,
"e": 38335,
"s": 38318,
"text": "surinderdawra388"
},
{
"code": null,
"e": 38345,
"s": 38335,
"text": "Microsoft"
},
{
"code": null,
"e": 38362,
"s": 38345,
"text": "pattern-printing"
},
{
"code": null,
"e": 38367,
"s": 38362,
"text": "Misc"
},
{
"code": null,
"e": 38377,
"s": 38367,
"text": "Recursion"
},
{
"code": null,
"e": 38387,
"s": 38377,
"text": "Microsoft"
},
{
"code": null,
"e": 38392,
"s": 38387,
"text": "Misc"
},
{
"code": null,
"e": 38409,
"s": 38392,
"text": "pattern-printing"
},
{
"code": null,
"e": 38419,
"s": 38409,
"text": "Recursion"
},
{
"code": null,
"e": 38424,
"s": 38419,
"text": "Misc"
},
{
"code": null,
"e": 38522,
"s": 38424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38556,
"s": 38522,
"text": "How to write Regular Expressions?"
},
{
"code": null,
"e": 38637,
"s": 38556,
"text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)"
},
{
"code": null,
"e": 38670,
"s": 38637,
"text": "fgets() and gets() in C language"
},
{
"code": null,
"e": 38687,
"s": 38670,
"text": "Association Rule"
},
{
"code": null,
"e": 38707,
"s": 38687,
"text": "Recursive Functions"
},
{
"code": null,
"e": 38767,
"s": 38707,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38852,
"s": 38767,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 38862,
"s": 38852,
"text": "Recursion"
},
{
"code": null,
"e": 38889,
"s": 38862,
"text": "Program for Tower of Hanoi"
}
] |
Extract every Nth element of a vector in R - GeeksforGeeks
|
21 Apr, 2021
In this article, we will see how to extract every Nth element from a vector in R Programming Language.
Method 1: Using iteration
An iteration is performed over the vector while declaring a variable, counter initialized with 0. With each iteration, the counter is incremented and as soon as the nth element is accessed, it is printed and the counter is reinitialized to 0. As a result, a sequence of elements at every nth index is obtained. The time complexity required in this approach is O(n), where n is the length of the vector.
Example
R
# declaring a vector vec <- c(1,2,3,4,5,4,3,7,8,9) # accessing every third element # of the vector maintaining counter count = 0 # looping over the vector elementsfor (i in vec){ # incrementing count count= count + 1 # checking if count is equal to # third element if(count == 3){ # printing the specific element print (i) # reinitialising count to 0 count = 0 } }
Output
[1] 3
[1] 4
[1] 8
Method 2: Using iteration and modulo
An iteration is performed over the vector while declaring a variable, counter initialized with 0. With each iteration, the counter is incremented and its modulo is checked with the nth element specified. If the result of the module operation is 0, then the element is printed. The time complexity required in this approach is O(n), where n is the length of the vector.
Example
R
# declaring a vector vec <- c("geeks","for","geeks","is","a","unique", "portal","to","learn","and","grow") # accessing every second element of # the vector n = 2 # maintaining counter count = 0 # looping over the vector elementsfor (i in vec){ # incrementing count count= count + 1 # checking if count is equal to third # element if(count %% n == 0){ # printing the specific element print (i) } }
Output
[1] “for”
[1] “is”
[1] “unique”
[1] “to”
[1] “and”
Method 3: Using seq() function
The seq() method in R, is used to generate sequences, out of the objects they refer to. The seq() method, extracts a subset of the original vector, based on the constraints, that is the start and end index, as well as the number of steps to increment during each iteration. It accesses the element at the index of the given vector based on these constraints, and then appends it to a sequence object.
Syntax: seq (from, to , increment_step)
Parameters :
from – the starting index of the sequence.
to – the ending index of the sequence, till where we wish to iterate.
increment_step – how many elements to skip
Returns :
A sequence based on the constraints.
Example
R
# declaring a vectorvec <- 5:20 print("Original vector:")print(vec) print("Extracting every 4th element") # iterating over 1 to length of the # vector to extract elementsextracted_vec <- vec[seq(1, length(vec), 4)] print ("Resultant elements")print(extracted_vec)
Output
[1] “Original vector:”
[1] 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
[1] “Extracting every 4th element”
[1] “Resultant elements”
[1] 5 9 13 17
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
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?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 26590,
"s": 26487,
"text": "In this article, we will see how to extract every Nth element from a vector in R Programming Language."
},
{
"code": null,
"e": 26616,
"s": 26590,
"text": "Method 1: Using iteration"
},
{
"code": null,
"e": 27020,
"s": 26616,
"text": "An iteration is performed over the vector while declaring a variable, counter initialized with 0. With each iteration, the counter is incremented and as soon as the nth element is accessed, it is printed and the counter is reinitialized to 0. As a result, a sequence of elements at every nth index is obtained. The time complexity required in this approach is O(n), where n is the length of the vector. "
},
{
"code": null,
"e": 27028,
"s": 27020,
"text": "Example"
},
{
"code": null,
"e": 27030,
"s": 27028,
"text": "R"
},
{
"code": "# declaring a vector vec <- c(1,2,3,4,5,4,3,7,8,9) # accessing every third element # of the vector maintaining counter count = 0 # looping over the vector elementsfor (i in vec){ # incrementing count count= count + 1 # checking if count is equal to # third element if(count == 3){ # printing the specific element print (i) # reinitialising count to 0 count = 0 } }",
"e": 27474,
"s": 27030,
"text": null
},
{
"code": null,
"e": 27481,
"s": 27474,
"text": "Output"
},
{
"code": null,
"e": 27487,
"s": 27481,
"text": "[1] 3"
},
{
"code": null,
"e": 27493,
"s": 27487,
"text": "[1] 4"
},
{
"code": null,
"e": 27499,
"s": 27493,
"text": "[1] 8"
},
{
"code": null,
"e": 27536,
"s": 27499,
"text": "Method 2: Using iteration and modulo"
},
{
"code": null,
"e": 27906,
"s": 27536,
"text": "An iteration is performed over the vector while declaring a variable, counter initialized with 0. With each iteration, the counter is incremented and its modulo is checked with the nth element specified. If the result of the module operation is 0, then the element is printed. The time complexity required in this approach is O(n), where n is the length of the vector."
},
{
"code": null,
"e": 27914,
"s": 27906,
"text": "Example"
},
{
"code": null,
"e": 27916,
"s": 27914,
"text": "R"
},
{
"code": "# declaring a vector vec <- c(\"geeks\",\"for\",\"geeks\",\"is\",\"a\",\"unique\", \"portal\",\"to\",\"learn\",\"and\",\"grow\") # accessing every second element of # the vector n = 2 # maintaining counter count = 0 # looping over the vector elementsfor (i in vec){ # incrementing count count= count + 1 # checking if count is equal to third # element if(count %% n == 0){ # printing the specific element print (i) } }",
"e": 28377,
"s": 27916,
"text": null
},
{
"code": null,
"e": 28384,
"s": 28377,
"text": "Output"
},
{
"code": null,
"e": 28394,
"s": 28384,
"text": "[1] “for”"
},
{
"code": null,
"e": 28403,
"s": 28394,
"text": "[1] “is”"
},
{
"code": null,
"e": 28416,
"s": 28403,
"text": "[1] “unique”"
},
{
"code": null,
"e": 28425,
"s": 28416,
"text": "[1] “to”"
},
{
"code": null,
"e": 28435,
"s": 28425,
"text": "[1] “and”"
},
{
"code": null,
"e": 28467,
"s": 28435,
"text": "Method 3: Using seq() function "
},
{
"code": null,
"e": 28869,
"s": 28467,
"text": "The seq() method in R, is used to generate sequences, out of the objects they refer to. The seq() method, extracts a subset of the original vector, based on the constraints, that is the start and end index, as well as the number of steps to increment during each iteration. It accesses the element at the index of the given vector based on these constraints, and then appends it to a sequence object. "
},
{
"code": null,
"e": 28909,
"s": 28869,
"text": "Syntax: seq (from, to , increment_step)"
},
{
"code": null,
"e": 28922,
"s": 28909,
"text": "Parameters :"
},
{
"code": null,
"e": 28965,
"s": 28922,
"text": "from – the starting index of the sequence."
},
{
"code": null,
"e": 29035,
"s": 28965,
"text": "to – the ending index of the sequence, till where we wish to iterate."
},
{
"code": null,
"e": 29078,
"s": 29035,
"text": "increment_step – how many elements to skip"
},
{
"code": null,
"e": 29089,
"s": 29078,
"text": "Returns : "
},
{
"code": null,
"e": 29126,
"s": 29089,
"text": "A sequence based on the constraints."
},
{
"code": null,
"e": 29134,
"s": 29126,
"text": "Example"
},
{
"code": null,
"e": 29136,
"s": 29134,
"text": "R"
},
{
"code": "# declaring a vectorvec <- 5:20 print(\"Original vector:\")print(vec) print(\"Extracting every 4th element\") # iterating over 1 to length of the # vector to extract elementsextracted_vec <- vec[seq(1, length(vec), 4)] print (\"Resultant elements\")print(extracted_vec)",
"e": 29404,
"s": 29136,
"text": null
},
{
"code": null,
"e": 29411,
"s": 29404,
"text": "Output"
},
{
"code": null,
"e": 29434,
"s": 29411,
"text": "[1] “Original vector:”"
},
{
"code": null,
"e": 29486,
"s": 29434,
"text": "[1] 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"
},
{
"code": null,
"e": 29521,
"s": 29486,
"text": "[1] “Extracting every 4th element”"
},
{
"code": null,
"e": 29546,
"s": 29521,
"text": "[1] “Resultant elements”"
},
{
"code": null,
"e": 29562,
"s": 29546,
"text": "[1] 5 9 13 17"
},
{
"code": null,
"e": 29569,
"s": 29562,
"text": "Picked"
},
{
"code": null,
"e": 29587,
"s": 29569,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 29597,
"s": 29587,
"text": "R-Vectors"
},
{
"code": null,
"e": 29608,
"s": 29597,
"text": "R Language"
},
{
"code": null,
"e": 29619,
"s": 29608,
"text": "R Programs"
},
{
"code": null,
"e": 29717,
"s": 29619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29769,
"s": 29717,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29804,
"s": 29769,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29842,
"s": 29804,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29900,
"s": 29842,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29943,
"s": 29900,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30001,
"s": 29943,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30044,
"s": 30001,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30093,
"s": 30044,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30143,
"s": 30093,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
How to Apply View Animations Effects in Android? - GeeksforGeeks
|
27 Mar, 2021
Android View Animations are used to apply amazing animations on TextView and EditText in the android application. Such animations provide the app with a smooth look in a new way. In this article, we are going to develop the Android View Animation effect in Android Studio.
In this article, we will develop a sample application with the TextView animation effect over its activity. A sample gif is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency
Now, Navigate to the Gradle Scripts > build.gradle(Module:app) add the below dependencies in the dependencies section.
Java
implementation 'com.daimajia.androidanimations:library:2.4@aar'
Now, sync your project and now we have everything which we will need during implementation so now, move towards its implementation.
Step 3: Working with the activity_main.xml file
Now, go-to the app >res > layout > activity_main.xml and paste the below-written code in the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/relative_layout" tools:context=".MainActivity"> <!-- TextView to display text--> <TextView android:id="@+id/textView" android:layout_width="750px" android:layout_height="200px" android:layout_centerInParent="true" android:fontFamily="sans-serif-black" android:text="GeeksForGeeks" android:textColor="#4CAF50" android:textSize="35dp" /> <!--Button to perform click event--> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textView" android:layout_centerInParent="true" android:background="#4CAF50" android:text="Click Me" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity;import com.daimajia.androidanimations.library.Techniques;import com.daimajia.androidanimations.library.YoYo; public class MainActivity extends AppCompatActivity { // declaring textView TextView textView; // declaring button Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing textView by findViewById textView= findViewById(R.id.textView); // initializing button by findViewById button= findViewById(R.id.button); // apply click event to button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // making animated textView using YoYo.with() // Tada can be replaced with other animation Effects YoYo.with(Techniques.Tada) .duration(700) .repeat(5) .playOn(findViewById(R.id.textView)); } }); }}
We can also use other animation effects like Tada. A list of some beautiful effects are given below with their categories:
Attention: Flash, Pulse, RubberBand, Shake, Swing, Wobble, Bounce, Tada, StandUp, Wave
Special: Hinge, RollIn, RollOut,Landing,TakingOff,DropOut
Bounce: BounceIn, BounceInDown, BounceInLeft, BounceInRight, BounceInUp
Fade: FadeIn, FadeInUp, FadeInDown, FadeInLeft, FadeInRight, FadeOut, FadeOutDown, FadeOutLeft, FadeOutRight, FadeOutUp
Flip: FlipInX, FlipOutX, FlipOutY
Rotate: RotateIn, RotateInDownLeft, RotateInDownRight, RotateInUpLeft, RotateInUpRight, RotateOut, RotateOutDownLeft, RotateOutDownRight, RotateOutUpLeft, RotateOutUpRight
Slide: SlideInLeft, SlideInRight, SlideInUp, SlideInDown, SlideOutLeft, SlideOutRight, SlideOutUp, SlideOutDown
Zoom: ZoomIn, ZoomInDown, ZoomInLeft, ZoomInRight, ZoomInUp, ZoomOut, ZoomOutDown, ZoomOutLeft, ZoomOutRight, ZoomOutUp
That’s all, now the application is ready to install on the device. Here is what the output of the application looks like.
Output:
Android-Animation
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n27 Mar, 2021"
},
{
"code": null,
"e": 26654,
"s": 26381,
"text": "Android View Animations are used to apply amazing animations on TextView and EditText in the android application. Such animations provide the app with a smooth look in a new way. In this article, we are going to develop the Android View Animation effect in Android Studio."
},
{
"code": null,
"e": 26927,
"s": 26654,
"text": "In this article, we will develop a sample application with the TextView animation effect over its activity. A sample gif is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 26956,
"s": 26927,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27118,
"s": 26956,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 27141,
"s": 27118,
"text": "Step 2: Add dependency"
},
{
"code": null,
"e": 27260,
"s": 27141,
"text": "Now, Navigate to the Gradle Scripts > build.gradle(Module:app) add the below dependencies in the dependencies section."
},
{
"code": null,
"e": 27265,
"s": 27260,
"text": "Java"
},
{
"code": "implementation 'com.daimajia.androidanimations:library:2.4@aar'",
"e": 27329,
"s": 27265,
"text": null
},
{
"code": null,
"e": 27463,
"s": 27329,
"text": "Now, sync your project and now we have everything which we will need during implementation so now, move towards its implementation. "
},
{
"code": null,
"e": 27511,
"s": 27463,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27628,
"s": 27511,
"text": "Now, go-to the app >res > layout > activity_main.xml and paste the below-written code in the activity_main.xml file."
},
{
"code": null,
"e": 27632,
"s": 27628,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/relative_layout\" tools:context=\".MainActivity\"> <!-- TextView to display text--> <TextView android:id=\"@+id/textView\" android:layout_width=\"750px\" android:layout_height=\"200px\" android:layout_centerInParent=\"true\" android:fontFamily=\"sans-serif-black\" android:text=\"GeeksForGeeks\" android:textColor=\"#4CAF50\" android:textSize=\"35dp\" /> <!--Button to perform click event--> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/textView\" android:layout_centerInParent=\"true\" android:background=\"#4CAF50\" android:text=\"Click Me\" /> </RelativeLayout>",
"e": 28706,
"s": 27632,
"text": null
},
{
"code": null,
"e": 28754,
"s": 28706,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 28972,
"s": 28754,
"text": "Go to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 28977,
"s": 28972,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity;import com.daimajia.androidanimations.library.Techniques;import com.daimajia.androidanimations.library.YoYo; public class MainActivity extends AppCompatActivity { // declaring textView TextView textView; // declaring button Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing textView by findViewById textView= findViewById(R.id.textView); // initializing button by findViewById button= findViewById(R.id.button); // apply click event to button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // making animated textView using YoYo.with() // Tada can be replaced with other animation Effects YoYo.with(Techniques.Tada) .duration(700) .repeat(5) .playOn(findViewById(R.id.textView)); } }); }}",
"e": 30238,
"s": 28977,
"text": null
},
{
"code": null,
"e": 30361,
"s": 30238,
"text": "We can also use other animation effects like Tada. A list of some beautiful effects are given below with their categories:"
},
{
"code": null,
"e": 30448,
"s": 30361,
"text": "Attention: Flash, Pulse, RubberBand, Shake, Swing, Wobble, Bounce, Tada, StandUp, Wave"
},
{
"code": null,
"e": 30507,
"s": 30448,
"text": "Special: Hinge, RollIn, RollOut,Landing,TakingOff,DropOut"
},
{
"code": null,
"e": 30580,
"s": 30507,
"text": "Bounce: BounceIn, BounceInDown, BounceInLeft, BounceInRight, BounceInUp"
},
{
"code": null,
"e": 30701,
"s": 30580,
"text": "Fade: FadeIn, FadeInUp, FadeInDown, FadeInLeft, FadeInRight, FadeOut, FadeOutDown, FadeOutLeft, FadeOutRight, FadeOutUp"
},
{
"code": null,
"e": 30736,
"s": 30701,
"text": "Flip: FlipInX, FlipOutX, FlipOutY"
},
{
"code": null,
"e": 30909,
"s": 30736,
"text": "Rotate: RotateIn, RotateInDownLeft, RotateInDownRight, RotateInUpLeft, RotateInUpRight, RotateOut, RotateOutDownLeft, RotateOutDownRight, RotateOutUpLeft, RotateOutUpRight"
},
{
"code": null,
"e": 31022,
"s": 30909,
"text": "Slide: SlideInLeft, SlideInRight, SlideInUp, SlideInDown, SlideOutLeft, SlideOutRight, SlideOutUp, SlideOutDown"
},
{
"code": null,
"e": 31143,
"s": 31022,
"text": "Zoom: ZoomIn, ZoomInDown, ZoomInLeft, ZoomInRight, ZoomInUp, ZoomOut, ZoomOutDown, ZoomOutLeft, ZoomOutRight, ZoomOutUp"
},
{
"code": null,
"e": 31265,
"s": 31143,
"text": "That’s all, now the application is ready to install on the device. Here is what the output of the application looks like."
},
{
"code": null,
"e": 31273,
"s": 31265,
"text": "Output:"
},
{
"code": null,
"e": 31291,
"s": 31273,
"text": "Android-Animation"
},
{
"code": null,
"e": 31299,
"s": 31291,
"text": "Android"
},
{
"code": null,
"e": 31304,
"s": 31299,
"text": "Java"
},
{
"code": null,
"e": 31309,
"s": 31304,
"text": "Java"
},
{
"code": null,
"e": 31317,
"s": 31309,
"text": "Android"
},
{
"code": null,
"e": 31415,
"s": 31317,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31453,
"s": 31415,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 31492,
"s": 31453,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31542,
"s": 31492,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 31593,
"s": 31542,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 31635,
"s": 31593,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31650,
"s": 31635,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31694,
"s": 31650,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31716,
"s": 31694,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31767,
"s": 31716,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Python Program for Iterative Quick Sort - GeeksforGeeks
|
30 Dec, 2020
# Python program for implementation of Quicksort # This function is same in both iterative and recursivedef partition(arr,l,h): i = ( l - 1 ) x = arr[h] for j in range(l , h): if arr[j] <= x: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[h] = arr[h],arr[i+1] return (i+1) # Function to do Quick sort# arr[] --> Array to be sorted,# l --> Starting index,# h --> Ending indexdef quickSortIterative(arr,l,h): # Create an auxiliary stack size = h - l + 1 stack = [0] * (size) # initialize top of stack top = -1 # push initial values of l and h to stack top = top + 1 stack[top] = l top = top + 1 stack[top] = h # Keep popping from stack while is not empty while top >= 0: # Pop h and l h = stack[top] top = top - 1 l = stack[top] top = top - 1 # Set pivot element at its correct position in # sorted array p = partition( arr, l, h ) # If there are elements on left side of pivot, # then push left side to stack if p-1 > l: top = top + 1 stack[top] = l top = top + 1 stack[top] = p - 1 # If there are elements on right side of pivot, # then push right side to stack if p+1 < h: top = top + 1 stack[top] = p + 1 top = top + 1 stack[top] = h # Driver code to test abovearr = [4, 3, 5, 2, 1, 3, 2, 3]n = len(arr)quickSortIterative(arr, 0, n-1)print ("Sorted array is:")for i in range(n): print ("%d" %arr[i]), # This code is contributed by Mohit Kumra
Output:
Sorted array is:
1 2 2 3 3 3 4 5
The above mentioned optimizations for recursive quick sort can also be applied to iterative version.
1) Partition process is same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to iterative version.
2) To reduce the stack size, first push the indexes of smaller half.
3) Use insertion sort when the size reduces below a experimentally calculated threshold.Please refer complete article on Iterative Quick Sort for more details!
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python | Get the first key in dictionary
Python Program for Merge Sort
Python | Find most frequent element in a list
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python - Convert JSON to string
Python program to find smallest number in a list
|
[
{
"code": null,
"e": 26097,
"s": 26069,
"text": "\n30 Dec, 2020"
},
{
"code": "# Python program for implementation of Quicksort # This function is same in both iterative and recursivedef partition(arr,l,h): i = ( l - 1 ) x = arr[h] for j in range(l , h): if arr[j] <= x: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[h] = arr[h],arr[i+1] return (i+1) # Function to do Quick sort# arr[] --> Array to be sorted,# l --> Starting index,# h --> Ending indexdef quickSortIterative(arr,l,h): # Create an auxiliary stack size = h - l + 1 stack = [0] * (size) # initialize top of stack top = -1 # push initial values of l and h to stack top = top + 1 stack[top] = l top = top + 1 stack[top] = h # Keep popping from stack while is not empty while top >= 0: # Pop h and l h = stack[top] top = top - 1 l = stack[top] top = top - 1 # Set pivot element at its correct position in # sorted array p = partition( arr, l, h ) # If there are elements on left side of pivot, # then push left side to stack if p-1 > l: top = top + 1 stack[top] = l top = top + 1 stack[top] = p - 1 # If there are elements on right side of pivot, # then push right side to stack if p+1 < h: top = top + 1 stack[top] = p + 1 top = top + 1 stack[top] = h # Driver code to test abovearr = [4, 3, 5, 2, 1, 3, 2, 3]n = len(arr)quickSortIterative(arr, 0, n-1)print (\"Sorted array is:\")for i in range(n): print (\"%d\" %arr[i]), # This code is contributed by Mohit Kumra",
"e": 27794,
"s": 26097,
"text": null
},
{
"code": null,
"e": 27802,
"s": 27794,
"text": "Output:"
},
{
"code": null,
"e": 27836,
"s": 27802,
"text": "Sorted array is:\n1 2 2 3 3 3 4 5\n"
},
{
"code": null,
"e": 27937,
"s": 27836,
"text": "The above mentioned optimizations for recursive quick sort can also be applied to iterative version."
},
{
"code": null,
"e": 28085,
"s": 27937,
"text": "1) Partition process is same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to iterative version."
},
{
"code": null,
"e": 28154,
"s": 28085,
"text": "2) To reduce the stack size, first push the indexes of smaller half."
},
{
"code": null,
"e": 28314,
"s": 28154,
"text": "3) Use insertion sort when the size reduces below a experimentally calculated threshold.Please refer complete article on Iterative Quick Sort for more details!"
},
{
"code": null,
"e": 28339,
"s": 28314,
"text": "python sorting-exercises"
},
{
"code": null,
"e": 28355,
"s": 28339,
"text": "Python Programs"
},
{
"code": null,
"e": 28453,
"s": 28355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28492,
"s": 28453,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 28556,
"s": 28492,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 28592,
"s": 28556,
"text": "How to inverse a matrix using NumPy"
},
{
"code": null,
"e": 28666,
"s": 28592,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 28707,
"s": 28666,
"text": "Python | Get the first key in dictionary"
},
{
"code": null,
"e": 28737,
"s": 28707,
"text": "Python Program for Merge Sort"
},
{
"code": null,
"e": 28783,
"s": 28737,
"text": "Python | Find most frequent element in a list"
},
{
"code": null,
"e": 28868,
"s": 28783,
"text": "Python | Difference between two dates (in minutes) using datetime.timedelta() method"
},
{
"code": null,
"e": 28900,
"s": 28868,
"text": "Python - Convert JSON to string"
}
] |
Find the value of P and modular inverse of Q modulo 998244353 - GeeksforGeeks
|
27 Sep, 2021
Given two integer P and Q, the task is to find the value of P and modular inverse of Q modulo 998244353. That is
Note: P and Q are co-prime integersExamples:
Input: P = 1, Q = 4Output: 748683265Explanation:Refer below for the explanation of the example.
Input: P = 1, Q = 16Output: 935854081
Approach: The key observation in the problem is that Q is co-prime with the 998244353, Then Q-1 always exists which can be computed using Extended euclidean Algorithm
For Example:
For P = 1 and Q = 4We know that,
That is, 4 * 748683265 = 2994733060 equivalent to 1 mod 998244353Therefore, 1*4^(-1) = 748683265
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// value of P.Q -1 mod 998244353 #include <bits/stdc++.h>using namespace std; // Function to find the value of// P * Q^-1 mod 998244353long long calculate(long long p, long long q){ long long mod = 998244353, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo) { // Multiply p with q // if expo is odd if (expo & 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p;} // Driver codeint main(){ int p = 1, q = 4; // Function Call cout << calculate(p, q) << '\n'; return 0;}
// Java implementation to find the// value of P.Q -1 mod 998244353import java.util.*; class GFG{ // Function to find the value of// P * Q^-1 mod 998244353static long calculate(long p, long q){ long mod = 998244353, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p;} // Driver codepublic static void main(String[] args){ long p = 1, q = 4; // Function call System.out.println(calculate(p, q));}} // This code is contributed by offbeat
# Python3 implementation to find the# value of P.Q -1 mod 998244353 # Function to find the value of# P * Q^-1 mod 998244353def calculate(p, q): mod = 998244353 expo = 0 expo = mod - 2 # Loop to find the value # until the expo is not zero while (expo): # Multiply p with q # if expo is odd if (expo & 1): p = (p * q) % mod q = (q * q) % mod # Reduce the value of # expo by 2 expo >>= 1 return p # Driver codeif __name__ == '__main__': p = 1 q = 4 # Function call print(calculate(p, q)) # This code is contributed by mohit kumar 29
// C# implementation to find the// value of P.Q -1 mod 998244353using System;class GFG{ // Function to find the value of// P * Q^-1 mod 998244353static long calculate(long p, long q){ long mod = 998244353, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p;} // Driver codepublic static void Main(string[] args){ long p = 1, q = 4; // Function call Console.WriteLine(calculate(p, q));}} // This code is contributed by Ritik Bansal
<script> // Javascript implementation to find the // value of P.Q -1 mod 998244353 // Function to find the value of // P * Q^-1 mod 998244353 function calculate(P, Q) { let mod = 998244353, expo; expo = mod - 2; p = 748683265; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { P = (P * Q) % mod; } Q = (Q * Q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p; } let p = 1, q = 4; // Function call document.write(calculate(p, q)); // This code is contributed by decode2207.</script>
748683265
mohit kumar 29
offbeat
bansal_rtk_
decode2207
GCD-LCM
Modular Arithmetic
Competitive Programming
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multistage Graph (Shortest Path)
Breadth First Traversal ( BFS ) on a 2D array
Check whether bitwise AND of a number with any subset of an array is zero or not
Shortest path in a directed graph by Dijkstra’s algorithm
5 Best Books for Competitive Programming
Program for Fibonacci numbers
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
|
[
{
"code": null,
"e": 26357,
"s": 26329,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 26471,
"s": 26357,
"text": "Given two integer P and Q, the task is to find the value of P and modular inverse of Q modulo 998244353. That is "
},
{
"code": null,
"e": 26519,
"s": 26473,
"text": "Note: P and Q are co-prime integersExamples: "
},
{
"code": null,
"e": 26617,
"s": 26521,
"text": "Input: P = 1, Q = 4Output: 748683265Explanation:Refer below for the explanation of the example."
},
{
"code": null,
"e": 26656,
"s": 26617,
"text": "Input: P = 1, Q = 16Output: 935854081 "
},
{
"code": null,
"e": 26826,
"s": 26658,
"text": "Approach: The key observation in the problem is that Q is co-prime with the 998244353, Then Q-1 always exists which can be computed using Extended euclidean Algorithm"
},
{
"code": null,
"e": 26842,
"s": 26828,
"text": "For Example: "
},
{
"code": null,
"e": 26879,
"s": 26844,
"text": "For P = 1 and Q = 4We know that, "
},
{
"code": null,
"e": 26985,
"s": 26887,
"text": "That is, 4 * 748683265 = 2994733060 equivalent to 1 mod 998244353Therefore, 1*4^(-1) = 748683265"
},
{
"code": null,
"e": 27041,
"s": 26989,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27047,
"s": 27043,
"text": "C++"
},
{
"code": null,
"e": 27052,
"s": 27047,
"text": "Java"
},
{
"code": null,
"e": 27060,
"s": 27052,
"text": "Python3"
},
{
"code": null,
"e": 27063,
"s": 27060,
"text": "C#"
},
{
"code": null,
"e": 27074,
"s": 27063,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// value of P.Q -1 mod 998244353 #include <bits/stdc++.h>using namespace std; // Function to find the value of// P * Q^-1 mod 998244353long long calculate(long long p, long long q){ long long mod = 998244353, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo) { // Multiply p with q // if expo is odd if (expo & 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p;} // Driver codeint main(){ int p = 1, q = 4; // Function Call cout << calculate(p, q) << '\\n'; return 0;}",
"e": 27793,
"s": 27074,
"text": null
},
{
"code": "// Java implementation to find the// value of P.Q -1 mod 998244353import java.util.*; class GFG{ // Function to find the value of// P * Q^-1 mod 998244353static long calculate(long p, long q){ long mod = 998244353, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p;} // Driver codepublic static void main(String[] args){ long p = 1, q = 4; // Function call System.out.println(calculate(p, q));}} // This code is contributed by offbeat",
"e": 28552,
"s": 27793,
"text": null
},
{
"code": "# Python3 implementation to find the# value of P.Q -1 mod 998244353 # Function to find the value of# P * Q^-1 mod 998244353def calculate(p, q): mod = 998244353 expo = 0 expo = mod - 2 # Loop to find the value # until the expo is not zero while (expo): # Multiply p with q # if expo is odd if (expo & 1): p = (p * q) % mod q = (q * q) % mod # Reduce the value of # expo by 2 expo >>= 1 return p # Driver codeif __name__ == '__main__': p = 1 q = 4 # Function call print(calculate(p, q)) # This code is contributed by mohit kumar 29",
"e": 29190,
"s": 28552,
"text": null
},
{
"code": "// C# implementation to find the// value of P.Q -1 mod 998244353using System;class GFG{ // Function to find the value of// P * Q^-1 mod 998244353static long calculate(long p, long q){ long mod = 998244353, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p;} // Driver codepublic static void Main(string[] args){ long p = 1, q = 4; // Function call Console.WriteLine(calculate(p, q));}} // This code is contributed by Ritik Bansal",
"e": 29951,
"s": 29190,
"text": null
},
{
"code": "<script> // Javascript implementation to find the // value of P.Q -1 mod 998244353 // Function to find the value of // P * Q^-1 mod 998244353 function calculate(P, Q) { let mod = 998244353, expo; expo = mod - 2; p = 748683265; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { P = (P * Q) % mod; } Q = (Q * Q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p; } let p = 1, q = 4; // Function call document.write(calculate(p, q)); // This code is contributed by decode2207.</script>",
"e": 30765,
"s": 29951,
"text": null
},
{
"code": null,
"e": 30775,
"s": 30765,
"text": "748683265"
},
{
"code": null,
"e": 30790,
"s": 30775,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30798,
"s": 30790,
"text": "offbeat"
},
{
"code": null,
"e": 30810,
"s": 30798,
"text": "bansal_rtk_"
},
{
"code": null,
"e": 30821,
"s": 30810,
"text": "decode2207"
},
{
"code": null,
"e": 30829,
"s": 30821,
"text": "GCD-LCM"
},
{
"code": null,
"e": 30848,
"s": 30829,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 30872,
"s": 30848,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30885,
"s": 30872,
"text": "Mathematical"
},
{
"code": null,
"e": 30898,
"s": 30885,
"text": "Mathematical"
},
{
"code": null,
"e": 30917,
"s": 30898,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 31015,
"s": 30917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31048,
"s": 31015,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 31094,
"s": 31048,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 31175,
"s": 31094,
"text": "Check whether bitwise AND of a number with any subset of an array is zero or not"
},
{
"code": null,
"e": 31233,
"s": 31175,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 31274,
"s": 31233,
"text": "5 Best Books for Competitive Programming"
},
{
"code": null,
"e": 31304,
"s": 31274,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31364,
"s": 31304,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31379,
"s": 31364,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31422,
"s": 31379,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
C# | Queue Class - GeeksforGeeks
|
20 Feb, 2019
Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called dequeue . This class comes under System.Collections namespace and implements ICollection, IEnumerable, and ICloneable interfaces.
Characteristics of Queue Class:
Enqueue adds an element to the end of the Queue.
Dequeue removes the oldest element from the start of the Queue.
Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue.
The capacity of a Queue is the number of elements the Queue can hold.
As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array.
Queue accepts null as a valid value for reference types and allows duplicate elements.
Example:
// C# code to create a Queueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue("one"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("two"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("three"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("four"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("five"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("six"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); }}
Total number of elements in the Queue are : 1
Total number of elements in the Queue are : 2
Total number of elements in the Queue are : 3
Total number of elements in the Queue are : 4
Total number of elements in the Queue are : 5
Total number of elements in the Queue are : 6
Example:
// C# code to Get the number of// elements contained in the Queueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue("Chandigarh"); myQueue.Enqueue("Delhi"); myQueue.Enqueue("Noida"); myQueue.Enqueue("Himachal"); myQueue.Enqueue("Punjab"); myQueue.Enqueue("Jammu"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); }}
Total number of elements in the Queue are : 6
Example 1:
// C# code to Check if a Queue// contains an elementusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue(5); myQueue.Enqueue(10); myQueue.Enqueue(15); myQueue.Enqueue(20); myQueue.Enqueue(25); // Checking whether the element is // present in the Queue or not // The function returns True if the // element is present in the Queue, else // returns False Console.WriteLine(myQueue.Contains(7)); }}
False
Example 2:
// C# code to Convert Queue to arrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue("Geeks"); myQueue.Enqueue("Geeks Classes"); myQueue.Enqueue("Noida"); myQueue.Enqueue("Data Structures"); myQueue.Enqueue("GeeksforGeeks"); // Converting the Queue // into object array Object[] arr = myQueue.ToArray(); // Displaying the elements in array foreach(Object obj in arr) { Console.WriteLine(obj); } }}
Geeks
Geeks Classes
Noida
Data Structures
GeeksforGeeks
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Queue
CSharp-Queue-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
String.Split() Method in C# with Examples
C# | How to check whether a List contains a specified element
C# Dictionary with examples
C# | IsNullOrEmpty() Method
C# | Delegates
C# | Method Overriding
C# | Arrays of Strings
C# | Abstract Classes
Difference between Ref and Out keywords in C#
|
[
{
"code": null,
"e": 24453,
"s": 24425,
"text": "\n20 Feb, 2019"
},
{
"code": null,
"e": 24806,
"s": 24453,
"text": "Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called dequeue . This class comes under System.Collections namespace and implements ICollection, IEnumerable, and ICloneable interfaces."
},
{
"code": null,
"e": 24838,
"s": 24806,
"text": "Characteristics of Queue Class:"
},
{
"code": null,
"e": 24887,
"s": 24838,
"text": "Enqueue adds an element to the end of the Queue."
},
{
"code": null,
"e": 24951,
"s": 24887,
"text": "Dequeue removes the oldest element from the start of the Queue."
},
{
"code": null,
"e": 25056,
"s": 24951,
"text": "Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue."
},
{
"code": null,
"e": 25126,
"s": 25056,
"text": "The capacity of a Queue is the number of elements the Queue can hold."
},
{
"code": null,
"e": 25248,
"s": 25126,
"text": "As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array."
},
{
"code": null,
"e": 25335,
"s": 25248,
"text": "Queue accepts null as a valid value for reference types and allows duplicate elements."
},
{
"code": null,
"e": 25344,
"s": 25335,
"text": "Example:"
},
{
"code": "// C# code to create a Queueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue(\"one\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"two\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"three\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"four\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"five\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"six\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); }}",
"e": 26946,
"s": 25344,
"text": null
},
{
"code": null,
"e": 27223,
"s": 26946,
"text": "Total number of elements in the Queue are : 1\nTotal number of elements in the Queue are : 2\nTotal number of elements in the Queue are : 3\nTotal number of elements in the Queue are : 4\nTotal number of elements in the Queue are : 5\nTotal number of elements in the Queue are : 6\n"
},
{
"code": null,
"e": 27232,
"s": 27223,
"text": "Example:"
},
{
"code": "// C# code to Get the number of// elements contained in the Queueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue(\"Chandigarh\"); myQueue.Enqueue(\"Delhi\"); myQueue.Enqueue(\"Noida\"); myQueue.Enqueue(\"Himachal\"); myQueue.Enqueue(\"Punjab\"); myQueue.Enqueue(\"Jammu\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); }}",
"e": 27922,
"s": 27232,
"text": null
},
{
"code": null,
"e": 27969,
"s": 27922,
"text": "Total number of elements in the Queue are : 6\n"
},
{
"code": null,
"e": 27980,
"s": 27969,
"text": "Example 1:"
},
{
"code": "// C# code to Check if a Queue// contains an elementusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue(5); myQueue.Enqueue(10); myQueue.Enqueue(15); myQueue.Enqueue(20); myQueue.Enqueue(25); // Checking whether the element is // present in the Queue or not // The function returns True if the // element is present in the Queue, else // returns False Console.WriteLine(myQueue.Contains(7)); }}",
"e": 28642,
"s": 27980,
"text": null
},
{
"code": null,
"e": 28649,
"s": 28642,
"text": "False\n"
},
{
"code": null,
"e": 28660,
"s": 28649,
"text": "Example 2:"
},
{
"code": "// C# code to Convert Queue to arrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue(\"Geeks\"); myQueue.Enqueue(\"Geeks Classes\"); myQueue.Enqueue(\"Noida\"); myQueue.Enqueue(\"Data Structures\"); myQueue.Enqueue(\"GeeksforGeeks\"); // Converting the Queue // into object array Object[] arr = myQueue.ToArray(); // Displaying the elements in array foreach(Object obj in arr) { Console.WriteLine(obj); } }}",
"e": 29349,
"s": 28660,
"text": null
},
{
"code": null,
"e": 29406,
"s": 29349,
"text": "Geeks\nGeeks Classes\nNoida\nData Structures\nGeeksforGeeks\n"
},
{
"code": null,
"e": 29417,
"s": 29406,
"text": "Reference:"
},
{
"code": null,
"e": 29510,
"s": 29417,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue?view=netframework-4.7.2"
},
{
"code": null,
"e": 29539,
"s": 29510,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 29564,
"s": 29539,
"text": "CSharp-Collections-Queue"
},
{
"code": null,
"e": 29583,
"s": 29564,
"text": "CSharp-Queue-Class"
},
{
"code": null,
"e": 29586,
"s": 29583,
"text": "C#"
},
{
"code": null,
"e": 29684,
"s": 29586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29738,
"s": 29684,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 29780,
"s": 29738,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 29842,
"s": 29780,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 29870,
"s": 29842,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 29898,
"s": 29870,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 29913,
"s": 29898,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29936,
"s": 29913,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 29959,
"s": 29936,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 29981,
"s": 29959,
"text": "C# | Abstract Classes"
}
] |
Non-generic Vs Generic Collection in Java - GeeksforGeeks
|
01 Oct, 2021
We will be discussing differences later prior let us understand what is generic Collection and non-generic Collection, and most importantly dealing with the implementation part as during implementation one can only really get the real understanding of the concept, henceforth the differences between them.
Generics are basically the errors appearing are compile-time than at run-time. there are certain advantages of generics over non-generic are as follows:
Code Reuse: With help of Generics, one needs to write a method/class/interface only once and use it for any type whereas, in non-generics, the code needs to be written again and again whenever needed.Type Safety: Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time).
Code Reuse: With help of Generics, one needs to write a method/class/interface only once and use it for any type whereas, in non-generics, the code needs to be written again and again whenever needed.
Type Safety: Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time).
Example: To create an ArrayList that store name of students and if by mistake programmer adds an integer object instead of string, the compiler allows it. But, when this data is retrieved from ArrayList, it causes problems at runtime for Non-generic ArrayList
Implementation:
Example 1
Java
// Java program to Demonstrate that Not Using Generics// Can cause Run Time Exceptions // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList // Declaring object without any type specified ArrayList al = new ArrayList(); // Adding elements to the above object // Custom input elements al.add("Sachin"); al.add("Rahul"); // Compiler will allows this operation al.add(10); String s1 = (String)al.get(0); String s2 = (String)al.get(1); // Try block to check for exceptions try { // Causes Runtime Exception String s3 = (String)al.get(2); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception System.out.println("Exception: " + e); } }}
Output:
prog.java:19: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList
al.add("Sachin");
^
where E is a type-variable:
E extends Object declared in class ArrayList
prog.java:20: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList
al.add("Rahul");
^
where E is a type-variable:
E extends Object declared in class ArrayList
prog.java:23: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList
al.add(10);
^
where E is a type-variable:
E extends Object declared in class ArrayList
3 warnings
How generics solve this problem?
If this list was made Generic, then it would take only String objects and threw Compile Time Error in any other case.
Example 2
Java
// Java Program to Illustrate Conversion of// Runitime Exceptions into compile time errors// Using generics // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList // Declaring object of string type ArrayList<String> al = new ArrayList<String>(); // Adding elements to the ArrayList // Custom input elements al.add("Sachin"); al.add("Rahul"); // Now compiler does not allow this operation al.add(10); String s1 = al.get(0); String s2 = al.get(1); String s3 = al.get(2); }}
Output:
prog.java:24: error: incompatible types: int cannot be converted to String
al.add(10);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
Now moving forward, Individual Type Casting is not needed.
If Generics is not needed, then, in the above example every time the data is to be retrieved from ArrayList, it needs to be typecasted. Typecasting at every retrieval operation is a big headache. This can be avoided if somehow it is already known that the list only holds string data.
Example 3
Java
// Java program to Illustrate Type Casting is Needed// Everytime in Non-Generic // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList // Declaring object without any type specified ArrayList al = new ArrayList(); // Adding elements to the above object // using add() method al.add("Sachin"); al.add("Rahul"); // For every retrieval, // it needs to be casted to String for use String s1 = (String)al.get(0); String s2 = (String)al.get(1); }}
Output:
Geek, now you should be wondering how generics solve this problem?
If this list was made Generic, then it would take only String objects and would return only String objects while retrieval. And hence individual typecasting won’t be required. The above statement is justified
Example 4
Java
// A Simple Java program to demonstrate that// type casting is not needed in Generic import java.util.*; class Test { public static void main(String[] args) { // Creating an ArrayList // Declaring object of type String ArrayList<String> al = new ArrayList<String>(); // Custom input elements al.add("Sachin"); al.add("Rahul"); // Retrieval can be easily // without the trouble of casting String s1 = al.get(0); String s2 = al.get(1); // Print and display out the elements in objects System.out.print(al); }}
[Sachin, Rahul]
Note:
With the help of generics, while one can implement algorithms Implementing generic algorithms, one can have that work on different types of objects and at the same they are type-safe too.
Do remember that there are some points, which will describe the difference between Generics and Non-Generic which are tabulated below in order to get a crisp understanding between them.
aasthasingh1809
saurabh1990aror
sweetyty
Java-Collections
Technical Scripter 2018
Difference Between
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 26127,
"s": 26099,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 26433,
"s": 26127,
"text": "We will be discussing differences later prior let us understand what is generic Collection and non-generic Collection, and most importantly dealing with the implementation part as during implementation one can only really get the real understanding of the concept, henceforth the differences between them."
},
{
"code": null,
"e": 26587,
"s": 26433,
"text": "Generics are basically the errors appearing are compile-time than at run-time. there are certain advantages of generics over non-generic are as follows: "
},
{
"code": null,
"e": 26975,
"s": 26587,
"text": "Code Reuse: With help of Generics, one needs to write a method/class/interface only once and use it for any type whereas, in non-generics, the code needs to be written again and again whenever needed.Type Safety: Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time)."
},
{
"code": null,
"e": 27176,
"s": 26975,
"text": "Code Reuse: With help of Generics, one needs to write a method/class/interface only once and use it for any type whereas, in non-generics, the code needs to be written again and again whenever needed."
},
{
"code": null,
"e": 27364,
"s": 27176,
"text": "Type Safety: Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time)."
},
{
"code": null,
"e": 27624,
"s": 27364,
"text": "Example: To create an ArrayList that store name of students and if by mistake programmer adds an integer object instead of string, the compiler allows it. But, when this data is retrieved from ArrayList, it causes problems at runtime for Non-generic ArrayList"
},
{
"code": null,
"e": 27640,
"s": 27624,
"text": "Implementation:"
},
{
"code": null,
"e": 27650,
"s": 27640,
"text": "Example 1"
},
{
"code": null,
"e": 27655,
"s": 27650,
"text": "Java"
},
{
"code": "// Java program to Demonstrate that Not Using Generics// Can cause Run Time Exceptions // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList // Declaring object without any type specified ArrayList al = new ArrayList(); // Adding elements to the above object // Custom input elements al.add(\"Sachin\"); al.add(\"Rahul\"); // Compiler will allows this operation al.add(10); String s1 = (String)al.get(0); String s2 = (String)al.get(1); // Try block to check for exceptions try { // Causes Runtime Exception String s3 = (String)al.get(2); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception System.out.println(\"Exception: \" + e); } }}",
"e": 28616,
"s": 27655,
"text": null
},
{
"code": null,
"e": 28625,
"s": 28616,
"text": "Output: "
},
{
"code": null,
"e": 29286,
"s": 28625,
"text": "prog.java:19: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList\n al.add(\"Sachin\");\n ^\n where E is a type-variable:\n E extends Object declared in class ArrayList\nprog.java:20: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList\n al.add(\"Rahul\");\n ^\n where E is a type-variable:\n E extends Object declared in class ArrayList\nprog.java:23: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList\n al.add(10);\n ^\n where E is a type-variable:\n E extends Object declared in class ArrayList\n3 warnings"
},
{
"code": null,
"e": 29319,
"s": 29286,
"text": "How generics solve this problem?"
},
{
"code": null,
"e": 29437,
"s": 29319,
"text": "If this list was made Generic, then it would take only String objects and threw Compile Time Error in any other case."
},
{
"code": null,
"e": 29447,
"s": 29437,
"text": "Example 2"
},
{
"code": null,
"e": 29452,
"s": 29447,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Conversion of// Runitime Exceptions into compile time errors// Using generics // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList // Declaring object of string type ArrayList<String> al = new ArrayList<String>(); // Adding elements to the ArrayList // Custom input elements al.add(\"Sachin\"); al.add(\"Rahul\"); // Now compiler does not allow this operation al.add(10); String s1 = al.get(0); String s2 = al.get(1); String s3 = al.get(2); }}",
"e": 30134,
"s": 29452,
"text": null
},
{
"code": null,
"e": 30142,
"s": 30134,
"text": "Output:"
},
{
"code": null,
"e": 30354,
"s": 30142,
"text": "prog.java:24: error: incompatible types: int cannot be converted to String\n al.add(10);\n ^\nNote: Some messages have been simplified; recompile with -Xdiags:verbose to get full output\n1 error"
},
{
"code": null,
"e": 30413,
"s": 30354,
"text": "Now moving forward, Individual Type Casting is not needed."
},
{
"code": null,
"e": 30698,
"s": 30413,
"text": "If Generics is not needed, then, in the above example every time the data is to be retrieved from ArrayList, it needs to be typecasted. Typecasting at every retrieval operation is a big headache. This can be avoided if somehow it is already known that the list only holds string data."
},
{
"code": null,
"e": 30708,
"s": 30698,
"text": "Example 3"
},
{
"code": null,
"e": 30713,
"s": 30708,
"text": "Java"
},
{
"code": "// Java program to Illustrate Type Casting is Needed// Everytime in Non-Generic // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList // Declaring object without any type specified ArrayList al = new ArrayList(); // Adding elements to the above object // using add() method al.add(\"Sachin\"); al.add(\"Rahul\"); // For every retrieval, // it needs to be casted to String for use String s1 = (String)al.get(0); String s2 = (String)al.get(1); }}",
"e": 31355,
"s": 30713,
"text": null
},
{
"code": null,
"e": 31363,
"s": 31355,
"text": "Output:"
},
{
"code": null,
"e": 31430,
"s": 31363,
"text": "Geek, now you should be wondering how generics solve this problem?"
},
{
"code": null,
"e": 31640,
"s": 31430,
"text": "If this list was made Generic, then it would take only String objects and would return only String objects while retrieval. And hence individual typecasting won’t be required. The above statement is justified "
},
{
"code": null,
"e": 31650,
"s": 31640,
"text": "Example 4"
},
{
"code": null,
"e": 31655,
"s": 31650,
"text": "Java"
},
{
"code": "// A Simple Java program to demonstrate that// type casting is not needed in Generic import java.util.*; class Test { public static void main(String[] args) { // Creating an ArrayList // Declaring object of type String ArrayList<String> al = new ArrayList<String>(); // Custom input elements al.add(\"Sachin\"); al.add(\"Rahul\"); // Retrieval can be easily // without the trouble of casting String s1 = al.get(0); String s2 = al.get(1); // Print and display out the elements in objects System.out.print(al); }}",
"e": 32267,
"s": 31655,
"text": null
},
{
"code": null,
"e": 32283,
"s": 32267,
"text": "[Sachin, Rahul]"
},
{
"code": null,
"e": 32289,
"s": 32283,
"text": "Note:"
},
{
"code": null,
"e": 32477,
"s": 32289,
"text": "With the help of generics, while one can implement algorithms Implementing generic algorithms, one can have that work on different types of objects and at the same they are type-safe too."
},
{
"code": null,
"e": 32664,
"s": 32477,
"text": "Do remember that there are some points, which will describe the difference between Generics and Non-Generic which are tabulated below in order to get a crisp understanding between them. "
},
{
"code": null,
"e": 32682,
"s": 32666,
"text": "aasthasingh1809"
},
{
"code": null,
"e": 32698,
"s": 32682,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 32707,
"s": 32698,
"text": "sweetyty"
},
{
"code": null,
"e": 32724,
"s": 32707,
"text": "Java-Collections"
},
{
"code": null,
"e": 32748,
"s": 32724,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 32767,
"s": 32748,
"text": "Difference Between"
},
{
"code": null,
"e": 32772,
"s": 32767,
"text": "Java"
},
{
"code": null,
"e": 32791,
"s": 32772,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32796,
"s": 32791,
"text": "Java"
},
{
"code": null,
"e": 32813,
"s": 32796,
"text": "Java-Collections"
},
{
"code": null,
"e": 32911,
"s": 32813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32972,
"s": 32911,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33040,
"s": 32972,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 33098,
"s": 33040,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 33153,
"s": 33098,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 33219,
"s": 33153,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 33234,
"s": 33219,
"text": "Arrays in Java"
},
{
"code": null,
"e": 33278,
"s": 33234,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 33300,
"s": 33278,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 33351,
"s": 33300,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
How to create HTML list from JavaScript array ? - GeeksforGeeks
|
10 Mar, 2021
In this article, we will be creating an HTML list from a JavaScript array. This is needed sometimes when we fetch JSON from any source and displaying the data into the frontend and in many other cases also.
Problem statement: Display the array [‘Ram’, ‘Shyam’, ‘Sita’, ‘Gita’ ] into an HTML list.
To achieve this, we will follow the steps below.
Step 1: Create the HTML skeleton.HTMLHTML<!DOCTYPE html><html> <head> </head> <body> <center><h1>GeeksforGeeks</h1></center> <ul id="myList"></ul> </body></html>
Step 1: Create the HTML skeleton.
HTML
<!DOCTYPE html><html> <head> </head> <body> <center><h1>GeeksforGeeks</h1></center> <ul id="myList"></ul> </body></html>
Step 2: Create a variable named list and get the element whose id is “myList”.JavascriptJavascriptlet list = document.getElementById("myList");
Step 2: Create a variable named list and get the element whose id is “myList”.
Javascript
let list = document.getElementById("myList");
Step 3: Now iterate all the array items using JavaScript forEach and at each iteration, create a li element and put the innerText value the same as the current item, and append the li at the list.JavascriptJavascriptlet data = ['Ram', 'Shyam', 'Sita', 'Gita' ]; let list = document.getElementById("myList"); data.forEach((item)=>{ let li = document.createElement("li"); li.innerText = item; list.appendChild(li);})
Step 3: Now iterate all the array items using JavaScript forEach and at each iteration, create a li element and put the innerText value the same as the current item, and append the li at the list.
Javascript
let data = ['Ram', 'Shyam', 'Sita', 'Gita' ]; let list = document.getElementById("myList"); data.forEach((item)=>{ let li = document.createElement("li"); li.innerText = item; list.appendChild(li);})
Complete code:
HTML
<!DOCTYPE html><html> <head> </head> <body> <center><h1>GeeksforGeeks</h1></center> <ul id="myList"></ul> <script> let data = ["Ram", "Shyam", "Sita", "Gita"]; let list = document.getElementById("myList"); data.forEach((item) => { let li = document.createElement("li"); li.innerText = item; list.appendChild(li); }); </script> </body></html>
Output:
HTML-Questions
javascript-array
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
How to position a div at the bottom of its container using CSS?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 25847,
"s": 25819,
"text": "\n10 Mar, 2021"
},
{
"code": null,
"e": 26055,
"s": 25847,
"text": "In this article, we will be creating an HTML list from a JavaScript array. This is needed sometimes when we fetch JSON from any source and displaying the data into the frontend and in many other cases also. "
},
{
"code": null,
"e": 26145,
"s": 26055,
"text": "Problem statement: Display the array [‘Ram’, ‘Shyam’, ‘Sita’, ‘Gita’ ] into an HTML list."
},
{
"code": null,
"e": 26194,
"s": 26145,
"text": "To achieve this, we will follow the steps below."
},
{
"code": null,
"e": 26365,
"s": 26194,
"text": "Step 1: Create the HTML skeleton.HTMLHTML<!DOCTYPE html><html> <head> </head> <body> <center><h1>GeeksforGeeks</h1></center> <ul id=\"myList\"></ul> </body></html>"
},
{
"code": null,
"e": 26399,
"s": 26365,
"text": "Step 1: Create the HTML skeleton."
},
{
"code": null,
"e": 26404,
"s": 26399,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> </head> <body> <center><h1>GeeksforGeeks</h1></center> <ul id=\"myList\"></ul> </body></html>",
"e": 26534,
"s": 26404,
"text": null
},
{
"code": null,
"e": 26678,
"s": 26534,
"text": "Step 2: Create a variable named list and get the element whose id is “myList”.JavascriptJavascriptlet list = document.getElementById(\"myList\");"
},
{
"code": null,
"e": 26757,
"s": 26678,
"text": "Step 2: Create a variable named list and get the element whose id is “myList”."
},
{
"code": null,
"e": 26768,
"s": 26757,
"text": "Javascript"
},
{
"code": "let list = document.getElementById(\"myList\");",
"e": 26814,
"s": 26768,
"text": null
},
{
"code": null,
"e": 27234,
"s": 26814,
"text": "Step 3: Now iterate all the array items using JavaScript forEach and at each iteration, create a li element and put the innerText value the same as the current item, and append the li at the list.JavascriptJavascriptlet data = ['Ram', 'Shyam', 'Sita', 'Gita' ]; let list = document.getElementById(\"myList\"); data.forEach((item)=>{ let li = document.createElement(\"li\"); li.innerText = item; list.appendChild(li);})"
},
{
"code": null,
"e": 27431,
"s": 27234,
"text": "Step 3: Now iterate all the array items using JavaScript forEach and at each iteration, create a li element and put the innerText value the same as the current item, and append the li at the list."
},
{
"code": null,
"e": 27442,
"s": 27431,
"text": "Javascript"
},
{
"code": "let data = ['Ram', 'Shyam', 'Sita', 'Gita' ]; let list = document.getElementById(\"myList\"); data.forEach((item)=>{ let li = document.createElement(\"li\"); li.innerText = item; list.appendChild(li);})",
"e": 27646,
"s": 27442,
"text": null
},
{
"code": null,
"e": 27661,
"s": 27646,
"text": "Complete code:"
},
{
"code": null,
"e": 27666,
"s": 27661,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> </head> <body> <center><h1>GeeksforGeeks</h1></center> <ul id=\"myList\"></ul> <script> let data = [\"Ram\", \"Shyam\", \"Sita\", \"Gita\"]; let list = document.getElementById(\"myList\"); data.forEach((item) => { let li = document.createElement(\"li\"); li.innerText = item; list.appendChild(li); }); </script> </body></html>",
"e": 28068,
"s": 27666,
"text": null
},
{
"code": null,
"e": 28076,
"s": 28068,
"text": "Output:"
},
{
"code": null,
"e": 28091,
"s": 28076,
"text": "HTML-Questions"
},
{
"code": null,
"e": 28108,
"s": 28091,
"text": "javascript-array"
},
{
"code": null,
"e": 28113,
"s": 28108,
"text": "HTML"
},
{
"code": null,
"e": 28124,
"s": 28113,
"text": "JavaScript"
},
{
"code": null,
"e": 28141,
"s": 28124,
"text": "Web Technologies"
},
{
"code": null,
"e": 28146,
"s": 28141,
"text": "HTML"
},
{
"code": null,
"e": 28244,
"s": 28146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28292,
"s": 28244,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28316,
"s": 28292,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28366,
"s": 28316,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28416,
"s": 28366,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 28480,
"s": 28416,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 28520,
"s": 28480,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28565,
"s": 28520,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28626,
"s": 28565,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28698,
"s": 28626,
"text": "Differences between Functional Components and Class Components in React"
}
] |
How to create a sequence of dates by using starting date in R?
|
The best way to create a sequence of anything is creating it with the help of seq function and this also applies to sequences of dates. But in case of dates, we need to read the dates in date format so that R can understand the input type and create the appropriate vector. If we do not use the date format for the date value then it won’t make sense to R and it will result in error.
Live Demo
x1<-seq(as.Date("2020-01-01"),by="day",length.out=5)
x1
[1] "2020-01-01" "2020-01-02" "2020-01-03" "2020-01-04" "2020-01-05"
Live Demo
x2<-seq(as.Date("2020-02-01"),by="day",length.out=29)
x2
[1] "2020-02-01" "2020-02-02" "2020-02-03" "2020-02-04" "2020-02-05"
[6] "2020-02-06" "2020-02-07" "2020-02-08" "2020-02-09" "2020-02-10"
[11] "2020-02-11" "2020-02-12" "2020- 02-13" "2020-02-14" "2020-02-15"
[16] "2020-02-16" "2020-02-17" "2020-02-18" "2020-02-19" "2020-02-20"
[21] "2020-02-21" "2020-02-22" "2020-02-23" "2020-02-24" "2020-02-25"
[26] "2020-02-26" "2020-02-27" "2020-02-28" "2020-02-29"
Live Demo
x3<-seq(as.Date("2020-02-01"),by="day",length.out=30)
x3
[1] "2020-02-01" "2020-02-02" "2020-02-03" "2020-02-04" "2020-02-05"
[6] "2020-02-06" "2020-02-07" "2020-02-08" "2020-02-09" "2020-02-10"
[11] "2020-02-11" "2020-02-12" "2020-02-13" "2020-02-14" "2020-02-15"
[16] "2020-02-16" "2020-02-17" "2020-02-18" "2020-02-19" "2020-02-20"
[21] "2020-02-21" "2020-02-22" "2020-02-23" "2020-02-24" "2020-02-25"
[26] "2020-02-26" "2020-02-27" "2020-02-28" "2020-02-29" "2020-03-01"
Live Demo
x4<-seq(as.Date("2020-03-01"),by="day",length.out=31)
x4
[1] "2020-03-01" "2020-03-02" "2020-03-03" "2020-03-04" "2020-03-05"
[6] "2020-03-06" "2020-03-07" "2020-03-08" "2020-03-09" "2020-03-10"
[11] "2020-03-11" "2020-03-12" "2020-03-13" "2020-03-14" "2020-03-15"
[16] "2020-03-16" "2020-03-17" "2020-03-18" "2020-03-19" "2020-03-20"
[21] "2020-03-21" "2020-03-22" "2020-03-23" "2020-03-24" "2020-03-25"
[26] "2020-03-26" "2020-03-27" "2020-03-28" "2020-03-29" "2020-03-30"
[31] "2020-03-31"
Live Demo
x5<-seq(as.Date("2020-04-01"),by="day",length.out=60)
x5
[1] "2020-04-01" "2020-04-02" "2020-04-03" "2020-04-04" "2020-04-05"
[6] "2020-04-06" "2020-04-07" "2020-04-08" "2020-04-09" "2020-04-10"
[11] "2020-04-11" "2020-04-12" "2020-04-13" "2020-04-14" "2020-04-15"
[16] "2020-04-16" "2020-04-17" "2020-04-18" "2020-04-19" "2020-04-20"
[21] "2020-04-21" "2020-04-22" "2020-04-23" "2020-04-24" "2020-04-25"
[26] "2020-04-26" "2020-04-27" "2020-04-28" "2020-04-29" "2020-04-30"
[31] "2020-05-01" "2020-05-02" "2020-05-03" "2020-05-04" "2020-05-05"
[36] "2020-05-06" "2020-05-07" "2020-05-08" "2020-05-09" "2020-05-10"
[41] "2020-05-11" "2020-05-12" "2020-05-13" "2020-05-14" "2020-05-15"
[46] "2020-05-16" "2020-05-17" "2020-05-18" "2020-05-19" "2020-05-20"
[51] "2020-05-21" "2020-05-22" "2020-05-23" "2020-05-24" "2020-05-25"
[56] "2020-05-26" "2020-05-27" "2020-05-28" "2020-05-29" "2020-05-30"
Live Demo
x6<-seq(as.Date("2020-05-15"),by="day",length.out=30)
x6
[1] "2020-05-15" "2020-05-16" "2020-05-17" "2020-05-18" "2020-05-19"
[6] "2020-05-20" "2020-05-21" "2020-05-22" "2020-05-23" "2020-05-24"
[11] "2020-05-25" "2020-05-26" "2020-05-27" "2020-05-28" "2020-05-29"
[16] "2020-05-30" "2020-05-31" "2020-06-01" "2020-06-02" "2020-06-03"
[21] "2020-06-04" "2020-06-05" "2020-06-06" "2020-06-07" "2020-06-08"
[26] "2020-06-09" "2020-06-10" "2020-06-11" "2020-06-12" "2020-06-13"
Live Demo
x7<-seq(as.Date("2020-05-15"),by="day",length.out=15)
x7
[1] "2020-05-15" "2020-05-16" "2020-05-17" "2020-05-18" "2020-05-19"
[6] "2020-05-20" "2020-05-21" "2020-05-22" "2020-05-23" "2020-05-24"
[11] "2020-05-25" "2020-05-26" "2020-05-27" "2020-05-28" "2020-05-29"
Live Demo
x8<-seq(as.Date("2020-06-14"),by="day",length.out=31)
x8
[1] "2020-06-14" "2020-06-15" "2020-06-16" "2020-06-17" "2020-06-18"
[6] "2020-06-19" "2020-06-20" "2020-06-21" "2020-06-22" "2020-06-23"
[11] "2020-06-24" "2020-06-25" "2020-06-26" "2020-06-27" "2020-06-28"
[16] "2020-06-29" "2020-06-30" "2020-07-01" "2020-07-02" "2020-07-03"
[21] "2020-07-04" "2020-07-05" "2020-07-06" "2020-07-07" "2020-07-08"
[26] "2020-07-09" "2020-07-10" "2020-07-11" "2020-07-12" "2020-07-13"
[31] "2020-07-14"
Live Demo
x9<-seq(as.Date("2020-11-01"),by="day",length.out=30)
x9
[1] "2020-11-01" "2020-11-02" "2020-11-03" "2020-11-04" "2020-11-05"
[6] "2020-11-06" "2020-11-07" "2020-11-08" "2020-11-09" "2020-11-10"
[11] "2020-11-11" "2020-11-12" "2020-11-13" "2020-11-14" "2020-11-15"
[16] "2020-11-16" "2020-11-17" "2020-11-18" "2020-11-19" "2020-11-20"
[21] "2020-11-21" "2020-11-22" "2020-11-23" "2020-11-24" "2020-11-25"
[26] "2020-11-26" "2020-11-27" "2020-11-28" "2020-11-29" "2020-11-30"
Live Demo
x10<-seq(as.Date("2020-12-01"),by="day",length.out=62)
x10
[1] "2020-12-01" "2020-12-02" "2020-12-03" "2020-12-04" "2020-12-05"
[6] "2020-12-06" "2020-12-07" "2020-12-08" "2020-12-09" "2020-12-10"
[11] "2020-12-11" "2020-12-12" "2020-12-13" "2020-12-14" "2020-12-15"
[16] "2020-12-16" "2020-12-17" "2020-12-18" "2020-12-19" "2020-12-20"
[21] "2020-12-21" "2020-12-22" "2020-12-23" "2020-12-24" "2020-12-25"
[26] "2020-12-26" "2020-12-27" "2020-12-28" "2020-12-29" "2020-12-30"
[31] "2020-12-31" "2021-01-01" "2021-01-02" "2021-01-03" "2021-01-04"
[36] "2021-01-05" "2021-01-06" "2021-01-07" "2021-01-08" "2021-01-09"
[41] "2021-01-10" "2021-01-11" "2021-01-12" "2021-01-13" "2021-01-14"
[46] "2021-01-15" "2021-01-16" "2021-01-17" "2021-01-18" "2021-01-19"
[51] "2021-01-20" "2021-01-21" "2021-01-22" "2021-01-23" "2021-01-24"
[56] "2021-01-25" "2021-01-26" "2021-01-27" "2021-01-28" "2021-01-29"
[61] "2021-01-30" "2021-01-31"
|
[
{
"code": null,
"e": 1447,
"s": 1062,
"text": "The best way to create a sequence of anything is creating it with the help of seq function and this also applies to sequences of dates. But in case of dates, we need to read the dates in date format so that R can understand the input type and create the appropriate vector. If we do not use the date format for the date value then it won’t make sense to R and it will result in error."
},
{
"code": null,
"e": 1458,
"s": 1447,
"text": " Live Demo"
},
{
"code": null,
"e": 1514,
"s": 1458,
"text": "x1<-seq(as.Date(\"2020-01-01\"),by=\"day\",length.out=5)\nx1"
},
{
"code": null,
"e": 1583,
"s": 1514,
"text": "[1] \"2020-01-01\" \"2020-01-02\" \"2020-01-03\" \"2020-01-04\" \"2020-01-05\""
},
{
"code": null,
"e": 1594,
"s": 1583,
"text": " Live Demo"
},
{
"code": null,
"e": 1651,
"s": 1594,
"text": "x2<-seq(as.Date(\"2020-02-01\"),by=\"day\",length.out=29)\nx2"
},
{
"code": null,
"e": 2059,
"s": 1651,
"text": "[1] \"2020-02-01\" \"2020-02-02\" \"2020-02-03\" \"2020-02-04\" \"2020-02-05\"\n[6] \"2020-02-06\" \"2020-02-07\" \"2020-02-08\" \"2020-02-09\" \"2020-02-10\"\n[11] \"2020-02-11\" \"2020-02-12\" \"2020- 02-13\" \"2020-02-14\" \"2020-02-15\"\n[16] \"2020-02-16\" \"2020-02-17\" \"2020-02-18\" \"2020-02-19\" \"2020-02-20\"\n[21] \"2020-02-21\" \"2020-02-22\" \"2020-02-23\" \"2020-02-24\" \"2020-02-25\"\n[26] \"2020-02-26\" \"2020-02-27\" \"2020-02-28\" \"2020-02-29\""
},
{
"code": null,
"e": 2070,
"s": 2059,
"text": " Live Demo"
},
{
"code": null,
"e": 2127,
"s": 2070,
"text": "x3<-seq(as.Date(\"2020-02-01\"),by=\"day\",length.out=30)\nx3"
},
{
"code": null,
"e": 2547,
"s": 2127,
"text": "[1] \"2020-02-01\" \"2020-02-02\" \"2020-02-03\" \"2020-02-04\" \"2020-02-05\"\n[6] \"2020-02-06\" \"2020-02-07\" \"2020-02-08\" \"2020-02-09\" \"2020-02-10\"\n[11] \"2020-02-11\" \"2020-02-12\" \"2020-02-13\" \"2020-02-14\" \"2020-02-15\"\n[16] \"2020-02-16\" \"2020-02-17\" \"2020-02-18\" \"2020-02-19\" \"2020-02-20\"\n[21] \"2020-02-21\" \"2020-02-22\" \"2020-02-23\" \"2020-02-24\" \"2020-02-25\"\n[26] \"2020-02-26\" \"2020-02-27\" \"2020-02-28\" \"2020-02-29\" \"2020-03-01\""
},
{
"code": null,
"e": 2558,
"s": 2547,
"text": " Live Demo"
},
{
"code": null,
"e": 2615,
"s": 2558,
"text": "x4<-seq(as.Date(\"2020-03-01\"),by=\"day\",length.out=31)\nx4"
},
{
"code": null,
"e": 3051,
"s": 2615,
"text": "[1] \"2020-03-01\" \"2020-03-02\" \"2020-03-03\" \"2020-03-04\" \"2020-03-05\"\n[6] \"2020-03-06\" \"2020-03-07\" \"2020-03-08\" \"2020-03-09\" \"2020-03-10\"\n[11] \"2020-03-11\" \"2020-03-12\" \"2020-03-13\" \"2020-03-14\" \"2020-03-15\"\n[16] \"2020-03-16\" \"2020-03-17\" \"2020-03-18\" \"2020-03-19\" \"2020-03-20\"\n[21] \"2020-03-21\" \"2020-03-22\" \"2020-03-23\" \"2020-03-24\" \"2020-03-25\"\n[26] \"2020-03-26\" \"2020-03-27\" \"2020-03-28\" \"2020-03-29\" \"2020-03-30\"\n[31] \"2020-03-31\""
},
{
"code": null,
"e": 3062,
"s": 3051,
"text": " Live Demo"
},
{
"code": null,
"e": 3119,
"s": 3062,
"text": "x5<-seq(as.Date(\"2020-04-01\"),by=\"day\",length.out=60)\nx5"
},
{
"code": null,
"e": 3957,
"s": 3119,
"text": "[1] \"2020-04-01\" \"2020-04-02\" \"2020-04-03\" \"2020-04-04\" \"2020-04-05\"\n[6] \"2020-04-06\" \"2020-04-07\" \"2020-04-08\" \"2020-04-09\" \"2020-04-10\"\n[11] \"2020-04-11\" \"2020-04-12\" \"2020-04-13\" \"2020-04-14\" \"2020-04-15\"\n[16] \"2020-04-16\" \"2020-04-17\" \"2020-04-18\" \"2020-04-19\" \"2020-04-20\"\n[21] \"2020-04-21\" \"2020-04-22\" \"2020-04-23\" \"2020-04-24\" \"2020-04-25\"\n[26] \"2020-04-26\" \"2020-04-27\" \"2020-04-28\" \"2020-04-29\" \"2020-04-30\"\n[31] \"2020-05-01\" \"2020-05-02\" \"2020-05-03\" \"2020-05-04\" \"2020-05-05\"\n[36] \"2020-05-06\" \"2020-05-07\" \"2020-05-08\" \"2020-05-09\" \"2020-05-10\"\n[41] \"2020-05-11\" \"2020-05-12\" \"2020-05-13\" \"2020-05-14\" \"2020-05-15\"\n[46] \"2020-05-16\" \"2020-05-17\" \"2020-05-18\" \"2020-05-19\" \"2020-05-20\"\n[51] \"2020-05-21\" \"2020-05-22\" \"2020-05-23\" \"2020-05-24\" \"2020-05-25\"\n[56] \"2020-05-26\" \"2020-05-27\" \"2020-05-28\" \"2020-05-29\" \"2020-05-30\""
},
{
"code": null,
"e": 3968,
"s": 3957,
"text": " Live Demo"
},
{
"code": null,
"e": 4025,
"s": 3968,
"text": "x6<-seq(as.Date(\"2020-05-15\"),by=\"day\",length.out=30)\nx6"
},
{
"code": null,
"e": 4443,
"s": 4025,
"text": "[1] \"2020-05-15\" \"2020-05-16\" \"2020-05-17\" \"2020-05-18\" \"2020-05-19\"\n[6] \"2020-05-20\" \"2020-05-21\" \"2020-05-22\" \"2020-05-23\" \"2020-05-24\"\n[11] \"2020-05-25\" \"2020-05-26\" \"2020-05-27\" \"2020-05-28\" \"2020-05-29\"\n[16] \"2020-05-30\" \"2020-05-31\" \"2020-06-01\" \"2020-06-02\" \"2020-06-03\"\n[21] \"2020-06-04\" \"2020-06-05\" \"2020-06-06\" \"2020-06-07\" \"2020-06-08\"\n[26] \"2020-06-09\" \"2020-06-10\" \"2020-06-11\" \"2020-06-12\" \"2020-06-13\""
},
{
"code": null,
"e": 4454,
"s": 4443,
"text": " Live Demo"
},
{
"code": null,
"e": 4511,
"s": 4454,
"text": "x7<-seq(as.Date(\"2020-05-15\"),by=\"day\",length.out=15)\nx7"
},
{
"code": null,
"e": 4719,
"s": 4511,
"text": "[1] \"2020-05-15\" \"2020-05-16\" \"2020-05-17\" \"2020-05-18\" \"2020-05-19\"\n[6] \"2020-05-20\" \"2020-05-21\" \"2020-05-22\" \"2020-05-23\" \"2020-05-24\"\n[11] \"2020-05-25\" \"2020-05-26\" \"2020-05-27\" \"2020-05-28\" \"2020-05-29\""
},
{
"code": null,
"e": 4730,
"s": 4719,
"text": " Live Demo"
},
{
"code": null,
"e": 4787,
"s": 4730,
"text": "x8<-seq(as.Date(\"2020-06-14\"),by=\"day\",length.out=31)\nx8"
},
{
"code": null,
"e": 5223,
"s": 4787,
"text": "[1] \"2020-06-14\" \"2020-06-15\" \"2020-06-16\" \"2020-06-17\" \"2020-06-18\"\n[6] \"2020-06-19\" \"2020-06-20\" \"2020-06-21\" \"2020-06-22\" \"2020-06-23\"\n[11] \"2020-06-24\" \"2020-06-25\" \"2020-06-26\" \"2020-06-27\" \"2020-06-28\"\n[16] \"2020-06-29\" \"2020-06-30\" \"2020-07-01\" \"2020-07-02\" \"2020-07-03\"\n[21] \"2020-07-04\" \"2020-07-05\" \"2020-07-06\" \"2020-07-07\" \"2020-07-08\"\n[26] \"2020-07-09\" \"2020-07-10\" \"2020-07-11\" \"2020-07-12\" \"2020-07-13\"\n[31] \"2020-07-14\""
},
{
"code": null,
"e": 5234,
"s": 5223,
"text": " Live Demo"
},
{
"code": null,
"e": 5291,
"s": 5234,
"text": "x9<-seq(as.Date(\"2020-11-01\"),by=\"day\",length.out=30)\nx9"
},
{
"code": null,
"e": 5709,
"s": 5291,
"text": "[1] \"2020-11-01\" \"2020-11-02\" \"2020-11-03\" \"2020-11-04\" \"2020-11-05\"\n[6] \"2020-11-06\" \"2020-11-07\" \"2020-11-08\" \"2020-11-09\" \"2020-11-10\"\n[11] \"2020-11-11\" \"2020-11-12\" \"2020-11-13\" \"2020-11-14\" \"2020-11-15\"\n[16] \"2020-11-16\" \"2020-11-17\" \"2020-11-18\" \"2020-11-19\" \"2020-11-20\"\n[21] \"2020-11-21\" \"2020-11-22\" \"2020-11-23\" \"2020-11-24\" \"2020-11-25\"\n[26] \"2020-11-26\" \"2020-11-27\" \"2020-11-28\" \"2020-11-29\" \"2020-11-30\""
},
{
"code": null,
"e": 5720,
"s": 5709,
"text": " Live Demo"
},
{
"code": null,
"e": 5779,
"s": 5720,
"text": "x10<-seq(as.Date(\"2020-12-01\"),by=\"day\",length.out=62)\nx10"
},
{
"code": null,
"e": 6648,
"s": 5779,
"text": "[1] \"2020-12-01\" \"2020-12-02\" \"2020-12-03\" \"2020-12-04\" \"2020-12-05\"\n[6] \"2020-12-06\" \"2020-12-07\" \"2020-12-08\" \"2020-12-09\" \"2020-12-10\"\n[11] \"2020-12-11\" \"2020-12-12\" \"2020-12-13\" \"2020-12-14\" \"2020-12-15\"\n[16] \"2020-12-16\" \"2020-12-17\" \"2020-12-18\" \"2020-12-19\" \"2020-12-20\"\n[21] \"2020-12-21\" \"2020-12-22\" \"2020-12-23\" \"2020-12-24\" \"2020-12-25\"\n[26] \"2020-12-26\" \"2020-12-27\" \"2020-12-28\" \"2020-12-29\" \"2020-12-30\"\n[31] \"2020-12-31\" \"2021-01-01\" \"2021-01-02\" \"2021-01-03\" \"2021-01-04\"\n[36] \"2021-01-05\" \"2021-01-06\" \"2021-01-07\" \"2021-01-08\" \"2021-01-09\"\n[41] \"2021-01-10\" \"2021-01-11\" \"2021-01-12\" \"2021-01-13\" \"2021-01-14\"\n[46] \"2021-01-15\" \"2021-01-16\" \"2021-01-17\" \"2021-01-18\" \"2021-01-19\"\n[51] \"2021-01-20\" \"2021-01-21\" \"2021-01-22\" \"2021-01-23\" \"2021-01-24\"\n[56] \"2021-01-25\" \"2021-01-26\" \"2021-01-27\" \"2021-01-28\" \"2021-01-29\"\n[61] \"2021-01-30\" \"2021-01-31\""
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.