title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Understanding DICOMs. An In Depth Hands On approach to how to... | by Amrit Virdee | Towards Data Science
September 2020 Update: fast.ai version 2 was officially released in August 2020. The use of fastai below refers to the latest version which is currently 2.0.9 An In Depth Hands On approach to how to view and manipulate DICOM images using fastai’s medical imaging module and get them ready for machine learning. DICOM(Digital Imaging and COmmunications in Medicine) is the de-facto standard that establishes rules that allow medical images(X-Ray, MRI, CT) and associated information to be exchanged between imaging equipment from different vendors, computers, and hospitals. The DICOM format provides a suitable means that meets health information exchange (HIE) standards for transmission of health related data among facilities and HL7 standards which is the messaging standard that enables clinical applications to exchange data. DICOM files typically have a .dcm extension and provides a means of storing data in separate ‘tags’ such as patient information, image/pixel data, the machine used and alot more information (explained below). A DICOM file predominantly consists of a header and image pixel intensity data packed into a single file. The information within the header is organized as a standardized series of tags. By extracting data from these tags one can access important information regarding the patient demographics, study parameters and a lot more. 16 bit DICOM images have values ranging from -32768 to 32768 while 8-bit grey-scale images store values from 0 to 255. The value ranges in DICOM images are useful as they correlate with the Hounsfield Scale which is a quantitative scale for describing radio-density (or a way of viewing different tissues densities — more explained below) These are the dependencies you will need to have installed on your computer to be able to go through this tutorial fastai installation instructions can be viewed on their Github page: fastai Also requires installing pydicom(Pydicom is a python package for parsing DICOM files and makes it easy to covert DICOM files into pythonic structures for easier manipulation. pip install pydicom and scikit-image(is a collection of algorithms for image processing) pip install scikit-image and kornia(is a library of packages containing operators that can be inserted within neural networks to train models to perform image transformations, epipolar geometry, depth estimation, and low-level image processing such as filtering and edge detection that operate directly on tensors pip install kornia For more information on how to use fastai’s medical imaging module head over to my github page or my tutorial blog on medical imaging(which is better for viewing notebook tutorials :)) Here is a list of 3 DICOM datasets that you can play around with. Each of these 3 datasets have different attributes and shows the vast diversity of what information can be contained within different DICOM datasets. the SIIM_SMALL dataset ((250 DICOM files, ~30MB) is conveniently provided in the fastai library but is limited in some of its attributes, for example, it does not have RescaleIntercept or RescaleSlope and its pixel range is limited in the range of 0 and 255 Kaggle has an easily accessible (437MB) CT medical image dataset from the cancer imaging archive. The dataset consists of 100 images (512px by 512px) with pixel ranges from -2000 to +2000 The Thyroid Segmentation in Ultrasonography Dataset provides low quality (ranging from 253px by 253px) DICOM images where each DICOM image has multiple frames (average of 1000) Let's load the dependencies: #Load the dependanciesfrom fastai.basics import *from fastai.callback.all import *from fastai.vision.all import *from fastai.medical.imaging import *import pydicomimport seaborn as snsmatplotlib.rcParams['image.cmap'] = 'bone'from matplotlib.colors import ListedColormap, LinearSegmentedColormap Having some knowledge about fast.ai is beneficial and beyond the scope of this tutorial, the fast.ai docs page has some excellent tutorials to get you started quickly. DICOM files are opened using pydicom.dcmread for example using the SIMM_SMALL dataset: #get dicom filesitems = get_dicom_files(pneumothorax_source, recurse=True, folders='train')#now lets read a file:img = items[10]dimg = dcmread(img) You can now view all the information contained within the DICOM file. Explanation of each element is beyond the scope of this tutorial but this site has some excellent information about each of the entries. Information is listed by the DICOM tag (eg: 0008, 0005) or DICOM keyword (eg: Specific Character Set). So for example: dimg Now generates: Here are some key points on the tag information above: Pixel Data (7fe0 0010)(last entry) — This is where the raw pixel data is stored. The order of pixels encoded for each image plane is left to right, top to bottom, i.e., the upper left pixel (labeled 1,1) is encoded first Photometric Interpretation (0028, 0004) — aka color space. In this case it is MONOCHROME2 where pixel data is represented as a single monochrome image plane where the minimum sample value is intended to be displayed as black info Samples per Pixel (0028, 0002) — This should be 1 as this image is monochrome. This value would be 3 if the color space was RGB for example Bits Stored (0028 0101) — Number of bits stored for each pixel sample Pixel Represenation (0028 0103) — can either be unsigned(0) or signed(1) Lossy Image Compression (0028 2110) — 00 image has not been subjected to lossy compression. 01 image has been subjected to lossy compression. Lossy Image Compression Method (0028 2114) — states the type of lossy compression used (in this case JPEG Lossy Compression, as denotated by CS:ISO_10918_1) Important tags that are not included in the SIMM_SMALL dataset: Rescale Intercept (0028, 1052) — where the value b in relationship between stored values (SV) and the output units. Output units = m*SV + b. Rescale Slope (0028, 1053) — m in the equation specified by Rescale Intercept (0028,1052). The RescaleIntercept and RescaleSlope are applied to transform the pixel values of the image into values that are meaningful to the application. Calculating the new values usually follow a linear formula: NewValue = (RawPixelValue * RescaleSlope) + RescaleIntercept and when the relationship is not linear a LUT(LookUp Table) is utilized. All this will become clearer when we view another dataset later below The list above is limited and playing around with the other 2 datasets will show you that there can be a vast number of tags per file. Its worth pointing out that there may be additional information (however not always the case) where there may be a tag for ImageComments. This tag may contain information that may be useful in the modelling. By default pydicom reads pixel data as the raw bytes found in the file and typically PixelData is often not immediately useful as data may be stored in a variety of different ways: The pixel values may be signed or unsigned integers, or floats There may be multiple image frames There may be multiple planes per frame (i.e. RGB) and the order of the pixels may be different These are only a few examples and more information can be found on the pycidom website This is what PixelData looks like: dimg.PixelData[:200] Because of the complexity in interpreting PixelData, pydicom provides an easy way to get it in a convenient form: pixel_array which returns a numpy.ndarray containing the pixel data: dimg.pixel_array, dimg.pixel_array.shape The SIIM_SMALL dataset is a DICOM dataset where each DICOM file has a pixel_array that contains 1 image. In this case the show function within fastai.medical.imaging conveniently displays the image source = untar_data(URLs.SIIM_SMALL)items = get_dicom_files(source)patient1 = dcmread(items[0])patient1.show() How about loading an image from the CT medical image dataset which also contains 1 frame per DICOM file. This image is a slice of a CT scan looking at the lungs with the heart in the middle. csource = Path('C:/PillView/NIH/data/dicoms')citems = get_dicom_files(csource)patient2 = dcmread(citems[0])patient2.show() However what if a DICOM dataset has multiple frames per file? The Thyroid Segmentation in Ultrasonography Dataset is a dataset where each DICOM file has multiple frames per file. Out of the box you cannot view images from DICOM files with multiple frames with fastai as this will result in a TypeError but we can customize theshow function so that it will check to see if a file has more than 1 frame and if it does you can choose how many frames to view (default is 1) as well as print how many frames there are in each file. September 2020 update: I submitted a PR to the library and this is now part of the show function in the fastai.medical.imaging module so will work out of the box. #updating to handle multiple frames@patch@delegates(show_image, show_images)def show(self:DcmDataset, frames=1, scale=True, cmap=plt.cm.bone, min_px=-1100, max_px=None, **kwargs): px = (self.windowed(*scale) if isinstance(scale,tuple) else self.hist_scaled(min_px=min_px,max_px=max_px,brks=scale) if isinstance(scale,(ndarray,Tensor)) else self.hist_scaled(min_px=min_px,max_px=max_px) if scale else self.scaled_px) if px.ndim > 2: gh=[] p = px.shape; print(f'{p[0]} frames per file') for i in range(frames): u = px[i]; gh.append(u) show_images(gh, cmap=cmap, **kwargs) else: print('1 frame per file') show_image(px, cmap=cmap, **kwargs) Fastai has a very intuitive way where you can patch code hence the @patch above so you can easily add different functionality to the code So now we can load the thyroid dataset: tsource = Path('C:/PillView/NIH/data/thyroid')titems = get_dicom_files(tsource)patient3 = dcmread(titems[0])patient3.show(10) Using the CT medical image dataset we can now play around with other useful fastai.medical.imaging functionality. As mentioned before 16 bit DICOM images can have pixel values ranging from -32768 to 32768 patient2 above is a DICOM file from this dataset. #lets convert the pixel_array into a tensor. Fastai can #conveniently do this for ustensor_dicom = pixels(patient2) #convert into tensorprint(f'RescaleIntercept: {patient2.RescaleIntercept:1f}\nRescaleSlope: {patient2.RescaleSlope:1f}\nMax pixel: ' f'{tensor_dicom.max()}\nMin pixel: {tensor_dicom.min()}\nShape: {tensor_dicom.shape}') In this image the RescaleIntercept is -1024, the RescaleSlope is 1, the max and min pixels are 1918 and 0 respectively and the image size is 512 by 512 Plotting a histogram of pixel intensities you can see where the bulk of pixels are located plt.hist(tensor_dicom.flatten(), color='c') The histogram shows that the minimal pixel value is 0 and the maximum pixel value is 1918. The histogram is predominantly bi-modal with the majority of pixels between the 0 and 100 pixels and between 750 and 1100 pixels. This image has a RescaleIntercept of -1024 and a RescaleSlope of 1. These two values allows for transforming pixel values into Hounsfield Units(HU). Densities of different tissues on CT scans are measured in HUs Most CT scans range from -1000HUs to +1000HUs where water is 0HUs, air is -1000HUs and the denser the tissues the higher the HU value. Metals have a much higher HU range +2000HUs so for medical imaging a range of -1000 to +1000HUs is suitable The pixel values above do not correctly correspond to tissue densities. For example most of the pixels are between pixel values 0 and 100 which correspond to water but this image is predominantly showing the lungs which are filled with air. Air on the Hounsfield scale is -1000 HUs. This is where RescaleIntercept and RescaleSlope are important. Fastai2 provides a convenient way scaled_px to rescale the pixels with respect to RescaleIntercept and RescaleSlope. Remember that: rescaled pixel = pixel * RescaleSlope + RescaleIntercept Fastai again provides a covenient method scaled_px of converting a pixel_array into a tensor and scaling the values by taking RescaleIntercept and RescaleSlope into consideration. #convert into tensor taking RescaleIntercept and RescaleSlope into #considerationtensor_dicom_scaled = scaled_px(patient2)plt.hist(tensor_dicom_scaled.flatten(), color='c') Now lets look at the maximum and minimum pixel values: print(f'Max pixel: {tensor_dicom_scaled.max()}\nMin pixel: {tensor_dicom_scaled.min()}') After re-scaling the maximum pixel value is 894 and the minimum value is -1024 and we can now correctly see what parts of the image correspond to what parts of the body based on the Hounsfield scale. Looking at the top end of the histogram what does the image look like with values over 300 HUs? The show function has the capability of specifying max and min values patient2.show(max_px=894, min_px=300, figsize=(5,5)) Recall we had patched the show function and it now shows that this dataset has 1 frame per file. HU values above +300 typically will show the bone structures within the image What about within the range of -250 and 250 where we have a spike to pixels? patient2.show(max_px=250, min_px=-250, figsize=(5,5)) Within this range you can now see the aorta and the parts of the heart(image middle) as well as muscle and fat. What about between -250px and -600px where we notice there are a low distribution of pixels patient2.show(max_px=-250, min_px=-600, figsize=(5,5)) In this range you just make out outlines. The histogram does show that within this range there are not many pixels What about between -1000px and -600px? patient2.show(max_px=-600, min_px=-1000, figsize=(5,5)) Within this range you can clearly see the bronchi within the lungs patient2.show(max_px=-900, min_px=-1024, figsize=(5,5)) At this range you can now also clearly see the curve of the scanner. The show function by default has a max_px value of None and a min_px value of -1100 patient2.show(max_px=None, min_px=-1100, figsize=(5,5)) Image re-scaling as done above is really for the benefit of humans. Computer screens can display about 256 shades of grey and the human eye is only capable of detecting about a 6% change in greyscale (ref) meaning the human eye can only detect about 17 different shades of grey. DICOM images may have a wide range from -1000 to +1000 and for humans to be able to see relevant structures within the image a process of windowing is utilized. Fastai provides various dicom_windows so that only specific HU values are displayed on the screen. More about windowing can be found here DICOM images can contain a high amount of pixel values and windowing can be thought of as a means of manipulating these values in order to change the appearance of the image so particular structures are highlighted. A window has 2 values: l = window level or center aka brightness w = window width or range aka contrast Example: from here Brain Matter window l = 40 (window center) w = 80 (window width) Voxels displayed range from 0 to 80 Calculating voxel values: lowest_visible_value = window_center — window_width / 2 highest_visible_value = window_center + window_width / 2 (lowest_visible_value = 40 — (80/2), highest_visible_value = 40 + (80/2)) Hence all values above >80 will be white and all values below 0 are black. Where windowing is for the benefit of the human, computers produce better results from training when the data has a uniform distribution as mentioned in this article don't see like a radiologist Looking back at the pixel distribution we can see that the image does not have a uniform distribution fastai has a function freqhist_hist that splits the range of pixel values into groups depending on what value you set for n_bins, such that each group has around the same number of pixels. For example if you set n_bins to 1, the pixel values are split into 2 distinct pixel bins. ten_freq = tensor_dicom_scaled.freqhist_bins(n_bins=1)fh = patient2.hist_scaled(ten_freq)plt.hist(ten_freq.flatten(), color='c'); show_image(fh, figsize=(7,7)) In this case you see the 2 polar sides of the image at -1000HUs you see the air portions and at 500HUs you see the bone structures clearly but the distribution is still not fully acceptable for the machine learning model. with n_bins at 100(this is the default number used by show) What about with n_bins at 100000 the pixels are showing a more uniform distribution What effect does this have on training outcomes. That will be the topic of the next tutorial.
[ { "code": null, "e": 206, "s": 47, "text": "September 2020 Update: fast.ai version 2 was officially released in August 2020. The use of fastai below refers to the latest version which is currently 2.0.9" }, { "code": null, "e": 358, "s": 206, "text": "An In Depth Hands On approach to how to view and manipulate DICOM images using fastai’s medical imaging module and get them ready for machine learning." }, { "code": null, "e": 879, "s": 358, "text": "DICOM(Digital Imaging and COmmunications in Medicine) is the de-facto standard that establishes rules that allow medical images(X-Ray, MRI, CT) and associated information to be exchanged between imaging equipment from different vendors, computers, and hospitals. The DICOM format provides a suitable means that meets health information exchange (HIE) standards for transmission of health related data among facilities and HL7 standards which is the messaging standard that enables clinical applications to exchange data." }, { "code": null, "e": 1088, "s": 879, "text": "DICOM files typically have a .dcm extension and provides a means of storing data in separate ‘tags’ such as patient information, image/pixel data, the machine used and alot more information (explained below)." }, { "code": null, "e": 1416, "s": 1088, "text": "A DICOM file predominantly consists of a header and image pixel intensity data packed into a single file. The information within the header is organized as a standardized series of tags. By extracting data from these tags one can access important information regarding the patient demographics, study parameters and a lot more." }, { "code": null, "e": 1755, "s": 1416, "text": "16 bit DICOM images have values ranging from -32768 to 32768 while 8-bit grey-scale images store values from 0 to 255. The value ranges in DICOM images are useful as they correlate with the Hounsfield Scale which is a quantitative scale for describing radio-density (or a way of viewing different tissues densities — more explained below)" }, { "code": null, "e": 1870, "s": 1755, "text": "These are the dependencies you will need to have installed on your computer to be able to go through this tutorial" }, { "code": null, "e": 1946, "s": 1870, "text": "fastai installation instructions can be viewed on their Github page: fastai" }, { "code": null, "e": 2121, "s": 1946, "text": "Also requires installing pydicom(Pydicom is a python package for parsing DICOM files and makes it easy to covert DICOM files into pythonic structures for easier manipulation." }, { "code": null, "e": 2141, "s": 2121, "text": "pip install pydicom" }, { "code": null, "e": 2210, "s": 2141, "text": "and scikit-image(is a collection of algorithms for image processing)" }, { "code": null, "e": 2235, "s": 2210, "text": "pip install scikit-image" }, { "code": null, "e": 2524, "s": 2235, "text": "and kornia(is a library of packages containing operators that can be inserted within neural networks to train models to perform image transformations, epipolar geometry, depth estimation, and low-level image processing such as filtering and edge detection that operate directly on tensors" }, { "code": null, "e": 2543, "s": 2524, "text": "pip install kornia" }, { "code": null, "e": 2728, "s": 2543, "text": "For more information on how to use fastai’s medical imaging module head over to my github page or my tutorial blog on medical imaging(which is better for viewing notebook tutorials :))" }, { "code": null, "e": 2944, "s": 2728, "text": "Here is a list of 3 DICOM datasets that you can play around with. Each of these 3 datasets have different attributes and shows the vast diversity of what information can be contained within different DICOM datasets." }, { "code": null, "e": 3202, "s": 2944, "text": "the SIIM_SMALL dataset ((250 DICOM files, ~30MB) is conveniently provided in the fastai library but is limited in some of its attributes, for example, it does not have RescaleIntercept or RescaleSlope and its pixel range is limited in the range of 0 and 255" }, { "code": null, "e": 3390, "s": 3202, "text": "Kaggle has an easily accessible (437MB) CT medical image dataset from the cancer imaging archive. The dataset consists of 100 images (512px by 512px) with pixel ranges from -2000 to +2000" }, { "code": null, "e": 3567, "s": 3390, "text": "The Thyroid Segmentation in Ultrasonography Dataset provides low quality (ranging from 253px by 253px) DICOM images where each DICOM image has multiple frames (average of 1000)" }, { "code": null, "e": 3596, "s": 3567, "text": "Let's load the dependencies:" }, { "code": null, "e": 3892, "s": 3596, "text": "#Load the dependanciesfrom fastai.basics import *from fastai.callback.all import *from fastai.vision.all import *from fastai.medical.imaging import *import pydicomimport seaborn as snsmatplotlib.rcParams['image.cmap'] = 'bone'from matplotlib.colors import ListedColormap, LinearSegmentedColormap" }, { "code": null, "e": 4060, "s": 3892, "text": "Having some knowledge about fast.ai is beneficial and beyond the scope of this tutorial, the fast.ai docs page has some excellent tutorials to get you started quickly." }, { "code": null, "e": 4147, "s": 4060, "text": "DICOM files are opened using pydicom.dcmread for example using the SIMM_SMALL dataset:" }, { "code": null, "e": 4295, "s": 4147, "text": "#get dicom filesitems = get_dicom_files(pneumothorax_source, recurse=True, folders='train')#now lets read a file:img = items[10]dimg = dcmread(img)" }, { "code": null, "e": 4605, "s": 4295, "text": "You can now view all the information contained within the DICOM file. Explanation of each element is beyond the scope of this tutorial but this site has some excellent information about each of the entries. Information is listed by the DICOM tag (eg: 0008, 0005) or DICOM keyword (eg: Specific Character Set)." }, { "code": null, "e": 4621, "s": 4605, "text": "So for example:" }, { "code": null, "e": 4626, "s": 4621, "text": "dimg" }, { "code": null, "e": 4641, "s": 4626, "text": "Now generates:" }, { "code": null, "e": 4696, "s": 4641, "text": "Here are some key points on the tag information above:" }, { "code": null, "e": 4917, "s": 4696, "text": "Pixel Data (7fe0 0010)(last entry) — This is where the raw pixel data is stored. The order of pixels encoded for each image plane is left to right, top to bottom, i.e., the upper left pixel (labeled 1,1) is encoded first" }, { "code": null, "e": 5147, "s": 4917, "text": "Photometric Interpretation (0028, 0004) — aka color space. In this case it is MONOCHROME2 where pixel data is represented as a single monochrome image plane where the minimum sample value is intended to be displayed as black info" }, { "code": null, "e": 5287, "s": 5147, "text": "Samples per Pixel (0028, 0002) — This should be 1 as this image is monochrome. This value would be 3 if the color space was RGB for example" }, { "code": null, "e": 5357, "s": 5287, "text": "Bits Stored (0028 0101) — Number of bits stored for each pixel sample" }, { "code": null, "e": 5430, "s": 5357, "text": "Pixel Represenation (0028 0103) — can either be unsigned(0) or signed(1)" }, { "code": null, "e": 5572, "s": 5430, "text": "Lossy Image Compression (0028 2110) — 00 image has not been subjected to lossy compression. 01 image has been subjected to lossy compression." }, { "code": null, "e": 5729, "s": 5572, "text": "Lossy Image Compression Method (0028 2114) — states the type of lossy compression used (in this case JPEG Lossy Compression, as denotated by CS:ISO_10918_1)" }, { "code": null, "e": 5793, "s": 5729, "text": "Important tags that are not included in the SIMM_SMALL dataset:" }, { "code": null, "e": 5934, "s": 5793, "text": "Rescale Intercept (0028, 1052) — where the value b in relationship between stored values (SV) and the output units. Output units = m*SV + b." }, { "code": null, "e": 6025, "s": 5934, "text": "Rescale Slope (0028, 1053) — m in the equation specified by Rescale Intercept (0028,1052)." }, { "code": null, "e": 6230, "s": 6025, "text": "The RescaleIntercept and RescaleSlope are applied to transform the pixel values of the image into values that are meaningful to the application. Calculating the new values usually follow a linear formula:" }, { "code": null, "e": 6291, "s": 6230, "text": "NewValue = (RawPixelValue * RescaleSlope) + RescaleIntercept" }, { "code": null, "e": 6364, "s": 6291, "text": "and when the relationship is not linear a LUT(LookUp Table) is utilized." }, { "code": null, "e": 6434, "s": 6364, "text": "All this will become clearer when we view another dataset later below" }, { "code": null, "e": 6777, "s": 6434, "text": "The list above is limited and playing around with the other 2 datasets will show you that there can be a vast number of tags per file. Its worth pointing out that there may be additional information (however not always the case) where there may be a tag for ImageComments. This tag may contain information that may be useful in the modelling." }, { "code": null, "e": 6958, "s": 6777, "text": "By default pydicom reads pixel data as the raw bytes found in the file and typically PixelData is often not immediately useful as data may be stored in a variety of different ways:" }, { "code": null, "e": 7021, "s": 6958, "text": "The pixel values may be signed or unsigned integers, or floats" }, { "code": null, "e": 7056, "s": 7021, "text": "There may be multiple image frames" }, { "code": null, "e": 7238, "s": 7056, "text": "There may be multiple planes per frame (i.e. RGB) and the order of the pixels may be different These are only a few examples and more information can be found on the pycidom website" }, { "code": null, "e": 7273, "s": 7238, "text": "This is what PixelData looks like:" }, { "code": null, "e": 7294, "s": 7273, "text": "dimg.PixelData[:200]" }, { "code": null, "e": 7477, "s": 7294, "text": "Because of the complexity in interpreting PixelData, pydicom provides an easy way to get it in a convenient form: pixel_array which returns a numpy.ndarray containing the pixel data:" }, { "code": null, "e": 7518, "s": 7477, "text": "dimg.pixel_array, dimg.pixel_array.shape" }, { "code": null, "e": 7716, "s": 7518, "text": "The SIIM_SMALL dataset is a DICOM dataset where each DICOM file has a pixel_array that contains 1 image. In this case the show function within fastai.medical.imaging conveniently displays the image" }, { "code": null, "e": 7827, "s": 7716, "text": "source = untar_data(URLs.SIIM_SMALL)items = get_dicom_files(source)patient1 = dcmread(items[0])patient1.show()" }, { "code": null, "e": 8018, "s": 7827, "text": "How about loading an image from the CT medical image dataset which also contains 1 frame per DICOM file. This image is a slice of a CT scan looking at the lungs with the heart in the middle." }, { "code": null, "e": 8141, "s": 8018, "text": "csource = Path('C:/PillView/NIH/data/dicoms')citems = get_dicom_files(csource)patient2 = dcmread(citems[0])patient2.show()" }, { "code": null, "e": 8203, "s": 8141, "text": "However what if a DICOM dataset has multiple frames per file?" }, { "code": null, "e": 8320, "s": 8203, "text": "The Thyroid Segmentation in Ultrasonography Dataset is a dataset where each DICOM file has multiple frames per file." }, { "code": null, "e": 8668, "s": 8320, "text": "Out of the box you cannot view images from DICOM files with multiple frames with fastai as this will result in a TypeError but we can customize theshow function so that it will check to see if a file has more than 1 frame and if it does you can choose how many frames to view (default is 1) as well as print how many frames there are in each file." }, { "code": null, "e": 8831, "s": 8668, "text": "September 2020 update: I submitted a PR to the library and this is now part of the show function in the fastai.medical.imaging module so will work out of the box." }, { "code": null, "e": 9553, "s": 8831, "text": "#updating to handle multiple frames@patch@delegates(show_image, show_images)def show(self:DcmDataset, frames=1, scale=True, cmap=plt.cm.bone, min_px=-1100, max_px=None, **kwargs): px = (self.windowed(*scale) if isinstance(scale,tuple) else self.hist_scaled(min_px=min_px,max_px=max_px,brks=scale) if isinstance(scale,(ndarray,Tensor)) else self.hist_scaled(min_px=min_px,max_px=max_px) if scale else self.scaled_px) if px.ndim > 2: gh=[] p = px.shape; print(f'{p[0]} frames per file') for i in range(frames): u = px[i]; gh.append(u) show_images(gh, cmap=cmap, **kwargs) else: print('1 frame per file') show_image(px, cmap=cmap, **kwargs)" }, { "code": null, "e": 9691, "s": 9553, "text": "Fastai has a very intuitive way where you can patch code hence the @patch above so you can easily add different functionality to the code" }, { "code": null, "e": 9731, "s": 9691, "text": "So now we can load the thyroid dataset:" }, { "code": null, "e": 9857, "s": 9731, "text": "tsource = Path('C:/PillView/NIH/data/thyroid')titems = get_dicom_files(tsource)patient3 = dcmread(titems[0])patient3.show(10)" }, { "code": null, "e": 10062, "s": 9857, "text": "Using the CT medical image dataset we can now play around with other useful fastai.medical.imaging functionality. As mentioned before 16 bit DICOM images can have pixel values ranging from -32768 to 32768" }, { "code": null, "e": 10112, "s": 10062, "text": "patient2 above is a DICOM file from this dataset." }, { "code": null, "e": 10454, "s": 10112, "text": "#lets convert the pixel_array into a tensor. Fastai can #conveniently do this for ustensor_dicom = pixels(patient2) #convert into tensorprint(f'RescaleIntercept: {patient2.RescaleIntercept:1f}\\nRescaleSlope: {patient2.RescaleSlope:1f}\\nMax pixel: ' f'{tensor_dicom.max()}\\nMin pixel: {tensor_dicom.min()}\\nShape: {tensor_dicom.shape}')" }, { "code": null, "e": 10606, "s": 10454, "text": "In this image the RescaleIntercept is -1024, the RescaleSlope is 1, the max and min pixels are 1918 and 0 respectively and the image size is 512 by 512" }, { "code": null, "e": 10697, "s": 10606, "text": "Plotting a histogram of pixel intensities you can see where the bulk of pixels are located" }, { "code": null, "e": 10741, "s": 10697, "text": "plt.hist(tensor_dicom.flatten(), color='c')" }, { "code": null, "e": 10962, "s": 10741, "text": "The histogram shows that the minimal pixel value is 0 and the maximum pixel value is 1918. The histogram is predominantly bi-modal with the majority of pixels between the 0 and 100 pixels and between 750 and 1100 pixels." }, { "code": null, "e": 11174, "s": 10962, "text": "This image has a RescaleIntercept of -1024 and a RescaleSlope of 1. These two values allows for transforming pixel values into Hounsfield Units(HU). Densities of different tissues on CT scans are measured in HUs" }, { "code": null, "e": 11417, "s": 11174, "text": "Most CT scans range from -1000HUs to +1000HUs where water is 0HUs, air is -1000HUs and the denser the tissues the higher the HU value. Metals have a much higher HU range +2000HUs so for medical imaging a range of -1000 to +1000HUs is suitable" }, { "code": null, "e": 11700, "s": 11417, "text": "The pixel values above do not correctly correspond to tissue densities. For example most of the pixels are between pixel values 0 and 100 which correspond to water but this image is predominantly showing the lungs which are filled with air. Air on the Hounsfield scale is -1000 HUs." }, { "code": null, "e": 11880, "s": 11700, "text": "This is where RescaleIntercept and RescaleSlope are important. Fastai2 provides a convenient way scaled_px to rescale the pixels with respect to RescaleIntercept and RescaleSlope." }, { "code": null, "e": 11895, "s": 11880, "text": "Remember that:" }, { "code": null, "e": 11952, "s": 11895, "text": "rescaled pixel = pixel * RescaleSlope + RescaleIntercept" }, { "code": null, "e": 12132, "s": 11952, "text": "Fastai again provides a covenient method scaled_px of converting a pixel_array into a tensor and scaling the values by taking RescaleIntercept and RescaleSlope into consideration." }, { "code": null, "e": 12305, "s": 12132, "text": "#convert into tensor taking RescaleIntercept and RescaleSlope into #considerationtensor_dicom_scaled = scaled_px(patient2)plt.hist(tensor_dicom_scaled.flatten(), color='c')" }, { "code": null, "e": 12360, "s": 12305, "text": "Now lets look at the maximum and minimum pixel values:" }, { "code": null, "e": 12449, "s": 12360, "text": "print(f'Max pixel: {tensor_dicom_scaled.max()}\\nMin pixel: {tensor_dicom_scaled.min()}')" }, { "code": null, "e": 12649, "s": 12449, "text": "After re-scaling the maximum pixel value is 894 and the minimum value is -1024 and we can now correctly see what parts of the image correspond to what parts of the body based on the Hounsfield scale." }, { "code": null, "e": 12745, "s": 12649, "text": "Looking at the top end of the histogram what does the image look like with values over 300 HUs?" }, { "code": null, "e": 12815, "s": 12745, "text": "The show function has the capability of specifying max and min values" }, { "code": null, "e": 12868, "s": 12815, "text": "patient2.show(max_px=894, min_px=300, figsize=(5,5))" }, { "code": null, "e": 13043, "s": 12868, "text": "Recall we had patched the show function and it now shows that this dataset has 1 frame per file. HU values above +300 typically will show the bone structures within the image" }, { "code": null, "e": 13120, "s": 13043, "text": "What about within the range of -250 and 250 where we have a spike to pixels?" }, { "code": null, "e": 13174, "s": 13120, "text": "patient2.show(max_px=250, min_px=-250, figsize=(5,5))" }, { "code": null, "e": 13286, "s": 13174, "text": "Within this range you can now see the aorta and the parts of the heart(image middle) as well as muscle and fat." }, { "code": null, "e": 13378, "s": 13286, "text": "What about between -250px and -600px where we notice there are a low distribution of pixels" }, { "code": null, "e": 13433, "s": 13378, "text": "patient2.show(max_px=-250, min_px=-600, figsize=(5,5))" }, { "code": null, "e": 13548, "s": 13433, "text": "In this range you just make out outlines. The histogram does show that within this range there are not many pixels" }, { "code": null, "e": 13587, "s": 13548, "text": "What about between -1000px and -600px?" }, { "code": null, "e": 13643, "s": 13587, "text": "patient2.show(max_px=-600, min_px=-1000, figsize=(5,5))" }, { "code": null, "e": 13710, "s": 13643, "text": "Within this range you can clearly see the bronchi within the lungs" }, { "code": null, "e": 13766, "s": 13710, "text": "patient2.show(max_px=-900, min_px=-1024, figsize=(5,5))" }, { "code": null, "e": 13835, "s": 13766, "text": "At this range you can now also clearly see the curve of the scanner." }, { "code": null, "e": 13919, "s": 13835, "text": "The show function by default has a max_px value of None and a min_px value of -1100" }, { "code": null, "e": 13975, "s": 13919, "text": "patient2.show(max_px=None, min_px=-1100, figsize=(5,5))" }, { "code": null, "e": 14254, "s": 13975, "text": "Image re-scaling as done above is really for the benefit of humans. Computer screens can display about 256 shades of grey and the human eye is only capable of detecting about a 6% change in greyscale (ref) meaning the human eye can only detect about 17 different shades of grey." }, { "code": null, "e": 14553, "s": 14254, "text": "DICOM images may have a wide range from -1000 to +1000 and for humans to be able to see relevant structures within the image a process of windowing is utilized. Fastai provides various dicom_windows so that only specific HU values are displayed on the screen. More about windowing can be found here" }, { "code": null, "e": 14792, "s": 14553, "text": "DICOM images can contain a high amount of pixel values and windowing can be thought of as a means of manipulating these values in order to change the appearance of the image so particular structures are highlighted. A window has 2 values:" }, { "code": null, "e": 14834, "s": 14792, "text": "l = window level or center aka brightness" }, { "code": null, "e": 14873, "s": 14834, "text": "w = window width or range aka contrast" }, { "code": null, "e": 14892, "s": 14873, "text": "Example: from here" }, { "code": null, "e": 14912, "s": 14892, "text": "Brain Matter window" }, { "code": null, "e": 14957, "s": 14912, "text": "l = 40 (window center) w = 80 (window width)" }, { "code": null, "e": 14993, "s": 14957, "text": "Voxels displayed range from 0 to 80" }, { "code": null, "e": 15019, "s": 14993, "text": "Calculating voxel values:" }, { "code": null, "e": 15075, "s": 15019, "text": "lowest_visible_value = window_center — window_width / 2" }, { "code": null, "e": 15132, "s": 15075, "text": "highest_visible_value = window_center + window_width / 2" }, { "code": null, "e": 15206, "s": 15132, "text": "(lowest_visible_value = 40 — (80/2), highest_visible_value = 40 + (80/2))" }, { "code": null, "e": 15281, "s": 15206, "text": "Hence all values above >80 will be white and all values below 0 are black." }, { "code": null, "e": 15476, "s": 15281, "text": "Where windowing is for the benefit of the human, computers produce better results from training when the data has a uniform distribution as mentioned in this article don't see like a radiologist" }, { "code": null, "e": 15578, "s": 15476, "text": "Looking back at the pixel distribution we can see that the image does not have a uniform distribution" }, { "code": null, "e": 15767, "s": 15578, "text": "fastai has a function freqhist_hist that splits the range of pixel values into groups depending on what value you set for n_bins, such that each group has around the same number of pixels." }, { "code": null, "e": 15858, "s": 15767, "text": "For example if you set n_bins to 1, the pixel values are split into 2 distinct pixel bins." }, { "code": null, "e": 16018, "s": 15858, "text": "ten_freq = tensor_dicom_scaled.freqhist_bins(n_bins=1)fh = patient2.hist_scaled(ten_freq)plt.hist(ten_freq.flatten(), color='c'); show_image(fh, figsize=(7,7))" }, { "code": null, "e": 16240, "s": 16018, "text": "In this case you see the 2 polar sides of the image at -1000HUs you see the air portions and at 500HUs you see the bone structures clearly but the distribution is still not fully acceptable for the machine learning model." }, { "code": null, "e": 16300, "s": 16240, "text": "with n_bins at 100(this is the default number used by show)" }, { "code": null, "e": 16384, "s": 16300, "text": "What about with n_bins at 100000 the pixels are showing a more uniform distribution" } ]
Grav - Themes Basics
Themes control the looks of your Grav site. Themes in Grav are built with the powerful Twig Templating engine. The pages that you create, references a specific template file by name or by setting the template header variable for the page. Using the page name is advised for simpler maintenance. After installing Grav Base package, you will find the defauld.md file in user/pages/01.home folder. The name of the file, i.e., default tells Grav that this page should be rendered with the twig template default.html.twig placed inside the themes/<mytheme>/templates folder. For example, if you have a file called contact.md, it will be rendered with twig template as themes/<mytheme>/templates/contact.html.twig. In the following sections, we will discuss about theme organization, i.e., its definition, configuration and more. The information about the theme will be defined in user/themes/antimatter/blueprints.yaml file and form definitions to be used in Administration panel are provided optionally. You will see the following content in user/themes/antimatter/blueprints.yaml file for Antimatter theme. name: Antimatter version: 1.6.0 description: "Antimatter is the default theme included with **Grav**" icon: empire author: name: Team Grav email: [email protected] url: http://getgrav.org homepage: https://github.com/getgrav/grav-theme-antimatter demo: http://demo.getgrav.org/blog-skeleton keywords: antimatter, theme, core, modern, fast, responsive, html5, css3 bugs: https://github.com/getgrav/grav-theme-antimatter/issues license: MIT form: validation: loose fields: dropdown.enabled: type: toggle label: Dropdown in navbar highlight: 1 default: 1 options: 1: Enabled 0: Disabled validate: type: bool In order to use theme configuration options, you need to provide the default settings in a file called user/themes/<mytheme>/<mytheme>.yaml. Example enable: true The ability of theme to interact with Grav via the plugins architecture is another powerful feature of Grav. To achieve this, simply create user/themes/<mytheme>/<mytheme>.php (for example, antimatter.php for default Antimatter theme) file and use the following format. <?php namespace Grav\Theme; use Grav\Common\Theme; class MyTheme extends Theme { public static function getSubscribedEvents() { return [ 'onThemeInitialized' => ['onThemeInitialized', 0] ]; } public function onThemeInitialized() { if ($this->isAdmin()) { $this->active = false; return; } $this->enable([ 'onTwigSiteVariables' => ['onTwigSiteVariables', 0] ]); } public function onTwigSiteVariables() { $this->grav['assets'] ->addCss('plugin://css/mytheme-core.css') ->addCss('plugin://css/mytheme-custom.css'); $this->grav['assets'] ->add('jquery', 101) ->addJs('theme://js/jquery.myscript.min.js'); } } The structure of Grav theme has no set rules except that there must be associated twig templates in templates/ folder for each and every page types content. Due to this tight coupling between page content and twig template, it's good to create general themes based on the Skeleton packages available in downloads page. Suppose you want to support modular template in your theme, you have to create modular/ folder and store twig templates files inside it. If you want to support forms, then you should create form/ folder and store form templates in it. To define forms for options and configuration for every single template files blueprints/ folder is used. These will not be editable via the Administrator Panel and it is optionally used. The theme is fully functional without blueprints folder. If you want to develop site with SASS or LESS, then you have to create sub-folders in user/themes/<mytheme>/scss/, or less/ if you want LESS along with a css/ folder. For automatically generated files which are compiled from SASS or LESS, the css-compiled/ folder is used. In Antimatter theme, scss variant of SASS is used. Follow these steps to install SASS in your machine. At the root of the theme, type the command given below to execute scss shell script. At the root of the theme, type the command given below to execute scss shell script. $ ./scss.sh Type the following command to directly run it. $ scss --sourcemap --watch scss:css-compiled The css-compiled/ will contain all the compiled scss files and css file will be generated inside your theme. It is recommended to create separate images/, fonts/ and js/ folders in your user/themes/<mytheme>/ folder for any images, fonts and JavaScript files used in your theme. The overall folder structure of the Antimatter theme that we discussed so far is shown below. 19 Lectures 3 hours Mr. Pradeep Kshetrapal 30 Lectures 4 hours Priyanka Choudhary 55 Lectures 4.5 hours University Code 24 Lectures 1 hours Mike Clayton Print Add Notes Bookmark this page
[ { "code": null, "e": 2613, "s": 2502, "text": "Themes control the looks of your Grav site. Themes in Grav are built with the powerful Twig Templating engine." }, { "code": null, "e": 2797, "s": 2613, "text": "The pages that you create, references a specific template file by name or by setting the template header variable for the page. Using the page name is advised for simpler maintenance." }, { "code": null, "e": 3072, "s": 2797, "text": "After installing Grav Base package, you will find the defauld.md file in user/pages/01.home folder. The name of the file, i.e., default tells Grav that this page should be rendered with the twig template default.html.twig placed inside the themes/<mytheme>/templates folder." }, { "code": null, "e": 3211, "s": 3072, "text": "For example, if you have a file called contact.md, it will be rendered with twig template as themes/<mytheme>/templates/contact.html.twig." }, { "code": null, "e": 3326, "s": 3211, "text": "In the following sections, we will discuss about theme organization, i.e., its definition, configuration and more." }, { "code": null, "e": 3606, "s": 3326, "text": "The information about the theme will be defined in user/themes/antimatter/blueprints.yaml file and form definitions to be used in Administration panel are provided optionally. You will see the following content in user/themes/antimatter/blueprints.yaml file for Antimatter theme." }, { "code": null, "e": 4322, "s": 3606, "text": "name: Antimatter\nversion: 1.6.0\ndescription: \"Antimatter is the default theme included with **Grav**\"\nicon: empire\nauthor:\n name: Team Grav\n email: [email protected]\n url: http://getgrav.org\nhomepage: https://github.com/getgrav/grav-theme-antimatter\ndemo: http://demo.getgrav.org/blog-skeleton\nkeywords: antimatter, theme, core, modern, fast, responsive, html5, css3\nbugs: https://github.com/getgrav/grav-theme-antimatter/issues\nlicense: MIT\n\nform:\n validation: loose\n fields:\n dropdown.enabled:\n type: toggle\n label: Dropdown in navbar\n highlight: 1\n default: 1\n options:\n 1: Enabled\n 0: Disabled\n validate:\n type: bool" }, { "code": null, "e": 4463, "s": 4322, "text": "In order to use theme configuration options, you need to provide the default settings in a file called user/themes/<mytheme>/<mytheme>.yaml." }, { "code": null, "e": 4471, "s": 4463, "text": "Example" }, { "code": null, "e": 4485, "s": 4471, "text": "enable: true\n" }, { "code": null, "e": 4755, "s": 4485, "text": "The ability of theme to interact with Grav via the plugins architecture is another powerful feature of Grav. To achieve this, simply create user/themes/<mytheme>/<mytheme>.php (for example, antimatter.php for default Antimatter theme) file and use the following format." }, { "code": null, "e": 5507, "s": 4755, "text": "<?php\nnamespace Grav\\Theme;\n\nuse Grav\\Common\\Theme;\n\nclass MyTheme extends Theme {\n public static function getSubscribedEvents() {\n return [\n 'onThemeInitialized' => ['onThemeInitialized', 0]\n ];\n }\n public function onThemeInitialized() {\n if ($this->isAdmin()) {\n $this->active = false;\n return;\n }\n \n $this->enable([\n 'onTwigSiteVariables' => ['onTwigSiteVariables', 0]\n ]);\n }\n public function onTwigSiteVariables() {\n $this->grav['assets']\n ->addCss('plugin://css/mytheme-core.css')\n ->addCss('plugin://css/mytheme-custom.css');\n\n $this->grav['assets']\n ->add('jquery', 101)\n ->addJs('theme://js/jquery.myscript.min.js');\n }\n}" }, { "code": null, "e": 5664, "s": 5507, "text": "The structure of Grav theme has no set rules except that there must be associated twig templates in templates/ folder for each and every page types content." }, { "code": null, "e": 5826, "s": 5664, "text": "Due to this tight coupling between page content and twig template, it's good to create general themes based on the Skeleton packages available in downloads page." }, { "code": null, "e": 6061, "s": 5826, "text": "Suppose you want to support modular template in your theme, you have to create modular/ folder and store twig templates files inside it. If you want to support forms, then you should create form/ folder and store form templates in it." }, { "code": null, "e": 6306, "s": 6061, "text": "To define forms for options and configuration for every single template files blueprints/ folder is used. These will not be editable via the Administrator Panel and it is optionally used. The theme is fully functional without blueprints folder." }, { "code": null, "e": 6473, "s": 6306, "text": "If you want to develop site with SASS or LESS, then you have to create sub-folders in user/themes/<mytheme>/scss/, or less/ if you want LESS along with a css/ folder." }, { "code": null, "e": 6630, "s": 6473, "text": "For automatically generated files which are compiled from SASS or LESS, the css-compiled/ folder is used. In Antimatter theme, scss variant of SASS is used." }, { "code": null, "e": 6682, "s": 6630, "text": "Follow these steps to install SASS in your machine." }, { "code": null, "e": 6767, "s": 6682, "text": "At the root of the theme, type the command given below to execute scss shell script." }, { "code": null, "e": 6852, "s": 6767, "text": "At the root of the theme, type the command given below to execute scss shell script." }, { "code": null, "e": 6865, "s": 6852, "text": "$ ./scss.sh\n" }, { "code": null, "e": 6912, "s": 6865, "text": "Type the following command to directly run it." }, { "code": null, "e": 6957, "s": 6912, "text": "$ scss --sourcemap --watch scss:css-compiled" }, { "code": null, "e": 7066, "s": 6957, "text": "The css-compiled/ will contain all the compiled scss files and css file will be generated inside your theme." }, { "code": null, "e": 7236, "s": 7066, "text": "It is recommended to create separate images/, fonts/ and js/ folders in your user/themes/<mytheme>/ folder for any images, fonts and JavaScript files used in your theme." }, { "code": null, "e": 7330, "s": 7236, "text": "The overall folder structure of the Antimatter theme that we discussed so far is shown below." }, { "code": null, "e": 7363, "s": 7330, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 7387, "s": 7363, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 7420, "s": 7387, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 7440, "s": 7420, "text": " Priyanka Choudhary" }, { "code": null, "e": 7475, "s": 7440, "text": "\n 55 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7492, "s": 7475, "text": " University Code" }, { "code": null, "e": 7525, "s": 7492, "text": "\n 24 Lectures \n 1 hours \n" }, { "code": null, "e": 7539, "s": 7525, "text": " Mike Clayton" }, { "code": null, "e": 7546, "s": 7539, "text": " Print" }, { "code": null, "e": 7557, "s": 7546, "text": " Add Notes" } ]
How to create a fixed/sticky footer with CSS?
To create fixed footer with CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } .footer { font-size: 20px; position: fixed; left: 0; bottom: 0; width: 100%; background-color: rgb(50, 6, 100); color: white; text-align: center; } </style> </head> <body> <h1>Fixed/Sticky Footer Example</h1> <div class="footer"> <p>All rights reserved ©</p> </div> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1120, "s": 1062, "text": "To create fixed footer with CSS, the code is as follows −" }, { "code": null, "e": 1131, "s": 1120, "text": " Live Demo" }, { "code": null, "e": 1656, "s": 1131, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\n body{\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n }\n .footer {\n font-size: 20px;\n position: fixed;\n left: 0;\n bottom: 0;\n width: 100%;\n background-color: rgb(50, 6, 100);\n color: white;\n text-align: center;\n }\n</style>\n</head>\n<body>\n<h1>Fixed/Sticky Footer Example</h1>\n<div class=\"footer\">\n<p>All rights reserved ©</p>\n</div>\n</body>\n</html>" }, { "code": null, "e": 1707, "s": 1656, "text": "The above code will produce the following output −" } ]
JSTL - fn:containsIgnoreCase() Function
The fn:containsIgnoreCase() function determines whether an input string contains a specified substring. While doing search it ignores the case. The fn:containsIgnoreCase() function has the following syntax − boolean containsIgnoreCase(java.lang.String, java.lang.String) Following is the example to explain the functionality of the fn:containsIgnoreCase() function − <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %> <html> <head> <title>Using JSTL Functions</title> </head> <body> <c:set var = "theString" value = "I am a test String"/> <c:if test = "${fn:containsIgnoreCase(theString, 'test')}"> <p>Found test string<p> </c:if> <c:if test = "${fn:containsIgnoreCase(theString, 'TEST')}"> <p>Found TEST string<p> </c:if> </body> </html> You will receive the following result − Found test string Found TEST string 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2383, "s": 2239, "text": "The fn:containsIgnoreCase() function determines whether an input string contains a specified substring. While doing search it ignores the case." }, { "code": null, "e": 2447, "s": 2383, "text": "The fn:containsIgnoreCase() function has the following syntax −" }, { "code": null, "e": 2511, "s": 2447, "text": "boolean containsIgnoreCase(java.lang.String, java.lang.String)\n" }, { "code": null, "e": 2607, "s": 2511, "text": "Following is the example to explain the functionality of the fn:containsIgnoreCase() function −" }, { "code": null, "e": 3143, "s": 2607, "text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/functions\" prefix = \"fn\" %>\n\n<html>\n <head>\n <title>Using JSTL Functions</title>\n </head>\n\n <body>\n <c:set var = \"theString\" value = \"I am a test String\"/>\n\n <c:if test = \"${fn:containsIgnoreCase(theString, 'test')}\">\n <p>Found test string<p>\n </c:if>\n\n <c:if test = \"${fn:containsIgnoreCase(theString, 'TEST')}\">\n <p>Found TEST string<p>\n </c:if>\n\n </body>\n</html>" }, { "code": null, "e": 3183, "s": 3143, "text": "You will receive the following result −" }, { "code": null, "e": 3220, "s": 3183, "text": "Found test string\nFound TEST string\n" }, { "code": null, "e": 3255, "s": 3220, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 3270, "s": 3255, "text": " Chaand Sheikh" }, { "code": null, "e": 3305, "s": 3270, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 3320, "s": 3305, "text": " Chaand Sheikh" }, { "code": null, "e": 3355, "s": 3320, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3369, "s": 3355, "text": " Karthikeya T" }, { "code": null, "e": 3404, "s": 3369, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3420, "s": 3404, "text": " TELCOMA Global" }, { "code": null, "e": 3453, "s": 3420, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 3469, "s": 3453, "text": " TELCOMA Global" }, { "code": null, "e": 3503, "s": 3469, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 3511, "s": 3503, "text": " Uplatz" }, { "code": null, "e": 3518, "s": 3511, "text": " Print" }, { "code": null, "e": 3529, "s": 3518, "text": " Add Notes" } ]
Adding Customized Color Theme in PySimpleGUI - GeeksforGeeks
05 Aug, 2020 PySimpleGUI allows users to choose Themes for its Theme list. Also, it allows users to specify and customize the Theme according to their choice. The User only should know the Color shades i.e the hex codes of the Colors. Accordingly, he/she can customize the Theme by new Colors. Example: import PySimpleGUI as sg # Add your new theme colors and settingssg.LOOK_AND_FEEL_TABLE['MyCreatedTheme'] = {'BACKGROUND': '# 000066', 'TEXT': '# FFCC66', 'INPUT': '# 339966', 'TEXT_INPUT': '# 000000', 'SCROLL': '# 99CC99', 'BUTTON': ('# 003333', '# FFCC66'), 'PROGRESS': ('# D1826B', '# CC8019'), 'BORDER': 1, 'SLIDER_DEPTH': 0, 'PROGRESS_DEPTH': 0, } # Switch to use your newly created themesg.theme('MyCreatedTheme') # Call a popup to show what the theme looks likesg.popup_get_text('This how the MyNewTheme is created') Output: Python-gui Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24644, "s": 24616, "text": "\n05 Aug, 2020" }, { "code": null, "e": 24925, "s": 24644, "text": "PySimpleGUI allows users to choose Themes for its Theme list. Also, it allows users to specify and customize the Theme according to their choice. The User only should know the Color shades i.e the hex codes of the Colors. Accordingly, he/she can customize the Theme by new Colors." }, { "code": null, "e": 24934, "s": 24925, "text": "Example:" }, { "code": "import PySimpleGUI as sg # Add your new theme colors and settingssg.LOOK_AND_FEEL_TABLE['MyCreatedTheme'] = {'BACKGROUND': '# 000066', 'TEXT': '# FFCC66', 'INPUT': '# 339966', 'TEXT_INPUT': '# 000000', 'SCROLL': '# 99CC99', 'BUTTON': ('# 003333', '# FFCC66'), 'PROGRESS': ('# D1826B', '# CC8019'), 'BORDER': 1, 'SLIDER_DEPTH': 0, 'PROGRESS_DEPTH': 0, } # Switch to use your newly created themesg.theme('MyCreatedTheme') # Call a popup to show what the theme looks likesg.popup_get_text('This how the MyNewTheme is created') ", "e": 25740, "s": 24934, "text": null }, { "code": null, "e": 25748, "s": 25740, "text": "Output:" }, { "code": null, "e": 25759, "s": 25748, "text": "Python-gui" }, { "code": null, "e": 25766, "s": 25759, "text": "Python" }, { "code": null, "e": 25864, "s": 25766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25882, "s": 25864, "text": "Python Dictionary" }, { "code": null, "e": 25917, "s": 25882, "text": "Read a file line by line in Python" }, { "code": null, "e": 25939, "s": 25917, "text": "Enumerate() in Python" }, { "code": null, "e": 25971, "s": 25939, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26001, "s": 25971, "text": "Iterate over a list in Python" }, { "code": null, "e": 26043, "s": 26001, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26069, "s": 26043, "text": "Python String | replace()" }, { "code": null, "e": 26106, "s": 26069, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26149, "s": 26106, "text": "Python program to convert a list to string" } ]
Python - Display text to PyGame window
Pygame is a multimedia library for Python for making games and multimedia applications. In this article we will see how to use the pygame module to get customized font and text on the screen taking into consideration, its height, width, and position in the pygame window. In the below program we initialize the pygame module and then define the mode and the caption for the image. Next we add the font text and define the coordinates for the font. The screen.blit function paints the screen while the while loop keeps listening the end of the game is clicked. import pygame import sys # Initialize pygame pygame.init() #scren dimension sur_obj=pygame.display.set_mode((300,200)) # Screen caption pygame.display.set_caption("Text in Pygame") font_color=(0,150,250) font_obj=pygame.font.Font("C:\Windows\Fonts\segoeprb.ttf",25) # Render the objects text_obj=font_obj.render("Welcome to Pygame",True,font_color) while True: sur_obj.fill((255,255,255)) sur_obj.blit(text_obj,(22,0)) for eve in pygame.event.get(): if eve.type==pygame.QUIT: pygame.quit() sys.exit() pygame.display.update() Running the above code gives us the following result −
[ { "code": null, "e": 1334, "s": 1062, "text": "Pygame is a multimedia library for Python for making games and multimedia applications. In this article we will see how to use the pygame module to get customized font and text on the screen taking into consideration, its height, width, and position in the pygame window." }, { "code": null, "e": 1622, "s": 1334, "text": "In the below program we initialize the pygame module and then define the mode and the caption for the image. Next we add the font text and define the coordinates for the font. The screen.blit function paints the screen while the while loop keeps listening the end of the game is clicked." }, { "code": null, "e": 2183, "s": 1622, "text": "import pygame\nimport sys\n# Initialize pygame\npygame.init()\n#scren dimension\nsur_obj=pygame.display.set_mode((300,200))\n# Screen caption\npygame.display.set_caption(\"Text in Pygame\")\nfont_color=(0,150,250)\nfont_obj=pygame.font.Font(\"C:\\Windows\\Fonts\\segoeprb.ttf\",25)\n# Render the objects\ntext_obj=font_obj.render(\"Welcome to Pygame\",True,font_color)\nwhile True:\n sur_obj.fill((255,255,255))\n sur_obj.blit(text_obj,(22,0))\n for eve in pygame.event.get():\n if eve.type==pygame.QUIT:\n pygame.quit()\n sys.exit()\n pygame.display.update()" }, { "code": null, "e": 2238, "s": 2183, "text": "Running the above code gives us the following result −" } ]
MySQL Joins
A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Let's look at a selection from the "Orders" table: Then, look at a selection from the "Customers" table: Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column. Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that have matching values in both tables: and it will produce something like this: INNER JOIN: Returns records that have matching values in both tables LEFT JOIN: Returns all records from the left table, and the matched records from the right table RIGHT JOIN: Returns all records from the right table, and the matched records from the left table CROSS JOIN: Returns all records from both tables Insert the missing parts in the JOIN clause to join the two tables Orders and Customers, using the CustomerID field in both tables as the relationship between the two tables. SELECT * FROM Orders LEFT JOIN Customers =; 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 104, "s": 0, "text": "A JOIN clause is used to combine rows from two or more tables, based on \na related column between them." }, { "code": null, "e": 155, "s": 104, "text": "Let's look at a selection from the \"Orders\" table:" }, { "code": null, "e": 209, "s": 155, "text": "Then, look at a selection from the \"Customers\" table:" }, { "code": null, "e": 396, "s": 209, "text": "Notice that the \"CustomerID\" column in the \"Orders\" table refers to the \n\"CustomerID\" in the \"Customers\" table. The relationship between the two tables above \nis the \"CustomerID\" column." }, { "code": null, "e": 540, "s": 396, "text": "Then, we can create the following SQL statement (that contains an \nINNER JOIN), \nthat selects records that have matching values in both tables:" }, { "code": null, "e": 581, "s": 540, "text": "and it will produce something like this:" }, { "code": null, "e": 650, "s": 581, "text": "INNER JOIN: Returns records that have matching values in both tables" }, { "code": null, "e": 747, "s": 650, "text": "LEFT JOIN: Returns all records from the left table, and the matched records from the right table" }, { "code": null, "e": 845, "s": 747, "text": "RIGHT JOIN: Returns all records from the right table, and the matched records from the left table" }, { "code": null, "e": 897, "s": 845, "text": "CROSS JOIN: Returns all records from both \n tables" }, { "code": null, "e": 1081, "s": 906, "text": "Insert the missing parts in the JOIN clause to join the two tables Orders and Customers,\nusing the CustomerID field in both tables as the relationship between the two tables." }, { "code": null, "e": 1126, "s": 1081, "text": "SELECT *\nFROM Orders\nLEFT JOIN Customers\n=;\n" }, { "code": null, "e": 1145, "s": 1126, "text": "Start the Exercise" }, { "code": null, "e": 1178, "s": 1145, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1220, "s": 1178, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1327, "s": 1220, "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": 1346, "s": 1327, "text": "[email protected]" } ]
Program for N-th term of Arithmetic Progression series - GeeksforGeeks
25 Feb, 2021 Given first term (a), common difference (d) and a integer N of the Arithmetic Progression series, the task is to find Nthterm of the series.Examples : Input : a = 2 d = 1 N = 5 Output : The 5th term of the series is : 6 Input : a = 5 d = 2 N = 10 Output : The 10th term of the series is : 23 Approach: We know the Arithmetic Progression series is like = 2, 5, 8, 11, 14 .... ... In this series 2 is the stating term of the series . Common difference = 5 – 2 = 3 (Difference common in the series). so we can write the series as :t1 = a1 t2 = a1 + (2-1) * d t3 = a1 + (3-1) * d . . . tN = a1 + (N-1) * d To find the Nth term in the Arithmetic Progression series we use the simple formula . TN = a1 + (N-1) * d C++ Java Python3 C# PHP Javascript // CPP Program to find nth term of// Arithmetic progression#include <bits/stdc++.h>using namespace std; int Nth_of_AP(int a, int d, int N){ // using formula to find the // Nth term t(n) = a(1) + (n-1)*d return (a + (N - 1) * d); } // Driver codeint main(){ // starting number int a = 2; // Common difference int d = 1; // N th term to be find int N = 5; // Display the output cout << "The "<< N <<"th term of the series is : " << Nth_of_AP(a,d,N); return 0;} // Java program to find nth term// of Arithmetic progressionimport java.io.*;import java.lang.*; class GFG{ public static int Nth_of_AP(int a, int d, int N) { // using formula to find the Nth // term t(n) = a(1) + (n-1)*d return ( a + (N - 1) * d ); } // Driver code public static void main(String[] args) { // starting number int a = 2; // Common difference int d = 1; // N th term to be find int N = 5; // Display the output System.out.print("The "+ N + "th term of the series is : " + Nth_of_AP(a, d, N)); }} # Python 3 Program to# find nth term of# Arithmetic progression def Nth_of_AP(a, d, N) : # using formula to find the # Nth term t(n) = a(1) + (n-1)*d return (a + (N - 1) * d) # Driver codea = 2 # starting numberd = 1 # Common differenceN = 5 # N th term to be find # Display the outputprint( "The ", N ,"th term of the series is : ", Nth_of_AP(a, d, N)) # This code is contributed# by Nikita Tiwari. // C# program to find nth term// of Arithmetic progressionusing System; class GFG{ public static int Nth_of_AP(int a, int d, int N) { // using formula to find the Nth // term t(n) = a(1) + (n-1)*d return ( a + (N - 1) * d ); } // Driver code public static void Main() { // starting number int a = 2; // Common difference int d = 1; // N th term to be find int N = 5; // Display the output Console.WriteLine("The "+ N + "th term of the series is : " + Nth_of_AP(a, d, N)); }} // This code is contributed by vt_m. <?php// PHP Program to find nth term of// Arithmetic progression function Nth_of_AP($a, $d, $N){ // using formula to find the // Nth term t(n) = a(1) + (n-1)*d return ($a + ($N - 1) * $d); } // Driver code // starting number$a = 2; // Common difference$d = 1; // N th term to be find$N = 5; // Display the outputecho("The " . $N . "th term of the series is : " . Nth_of_AP($a, $d, $N)); // This code is contributed by Ajit.?> <script> // JavaScript Program to find nth term of // Arithmetic progression function Nth_of_AP(a, d, N) { // using formula to find the // Nth term t(n) = a(1) + (n-1)*d return (a + (N - 1) * d); } // Driver code // starting number let a = 2; // Common difference let d = 1; // N th term to be find let N = 5; // Display the output document.write("The "+ N + "th term of the series is : " + Nth_of_AP(a,d,N)); // This code is contributed by Mayank Tyagi </script> Output : The 5th term of the series is : 6 jit_t mayanktyagi1709 arithmetic progression series Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Program to find GCD or HCF of two numbers Prime Numbers Program to find sum of elements in a given array Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 25440, "s": 25412, "text": "\n25 Feb, 2021" }, { "code": null, "e": 25593, "s": 25440, "text": "Given first term (a), common difference (d) and a integer N of the Arithmetic Progression series, the task is to find Nthterm of the series.Examples : " }, { "code": null, "e": 25735, "s": 25593, "text": "Input : a = 2 d = 1 N = 5\nOutput :\nThe 5th term of the series is : 6\n\nInput : a = 5 d = 2 N = 10\nOutput :\nThe 10th term of the series is : 23" }, { "code": null, "e": 25747, "s": 25735, "text": "Approach: " }, { "code": null, "e": 26049, "s": 25747, "text": "We know the Arithmetic Progression series is like = 2, 5, 8, 11, 14 .... ... In this series 2 is the stating term of the series . Common difference = 5 – 2 = 3 (Difference common in the series). so we can write the series as :t1 = a1 t2 = a1 + (2-1) * d t3 = a1 + (3-1) * d . . . tN = a1 + (N-1) * d " }, { "code": null, "e": 26136, "s": 26049, "text": "To find the Nth term in the Arithmetic Progression series we use the simple formula . " }, { "code": null, "e": 26156, "s": 26136, "text": "TN = a1 + (N-1) * d" }, { "code": null, "e": 26164, "s": 26160, "text": "C++" }, { "code": null, "e": 26169, "s": 26164, "text": "Java" }, { "code": null, "e": 26177, "s": 26169, "text": "Python3" }, { "code": null, "e": 26180, "s": 26177, "text": "C#" }, { "code": null, "e": 26184, "s": 26180, "text": "PHP" }, { "code": null, "e": 26195, "s": 26184, "text": "Javascript" }, { "code": "// CPP Program to find nth term of// Arithmetic progression#include <bits/stdc++.h>using namespace std; int Nth_of_AP(int a, int d, int N){ // using formula to find the // Nth term t(n) = a(1) + (n-1)*d return (a + (N - 1) * d); } // Driver codeint main(){ // starting number int a = 2; // Common difference int d = 1; // N th term to be find int N = 5; // Display the output cout << \"The \"<< N <<\"th term of the series is : \" << Nth_of_AP(a,d,N); return 0;}", "e": 26726, "s": 26195, "text": null }, { "code": "// Java program to find nth term// of Arithmetic progressionimport java.io.*;import java.lang.*; class GFG{ public static int Nth_of_AP(int a, int d, int N) { // using formula to find the Nth // term t(n) = a(1) + (n-1)*d return ( a + (N - 1) * d ); } // Driver code public static void main(String[] args) { // starting number int a = 2; // Common difference int d = 1; // N th term to be find int N = 5; // Display the output System.out.print(\"The \"+ N + \"th term of the series is : \" + Nth_of_AP(a, d, N)); }}", "e": 27467, "s": 26726, "text": null }, { "code": "# Python 3 Program to# find nth term of# Arithmetic progression def Nth_of_AP(a, d, N) : # using formula to find the # Nth term t(n) = a(1) + (n-1)*d return (a + (N - 1) * d) # Driver codea = 2 # starting numberd = 1 # Common differenceN = 5 # N th term to be find # Display the outputprint( \"The \", N ,\"th term of the series is : \", Nth_of_AP(a, d, N)) # This code is contributed# by Nikita Tiwari.", "e": 27896, "s": 27467, "text": null }, { "code": "// C# program to find nth term// of Arithmetic progressionusing System; class GFG{ public static int Nth_of_AP(int a, int d, int N) { // using formula to find the Nth // term t(n) = a(1) + (n-1)*d return ( a + (N - 1) * d ); } // Driver code public static void Main() { // starting number int a = 2; // Common difference int d = 1; // N th term to be find int N = 5; // Display the output Console.WriteLine(\"The \"+ N + \"th term of the series is : \" + Nth_of_AP(a, d, N)); }} // This code is contributed by vt_m.", "e": 28648, "s": 27896, "text": null }, { "code": "<?php// PHP Program to find nth term of// Arithmetic progression function Nth_of_AP($a, $d, $N){ // using formula to find the // Nth term t(n) = a(1) + (n-1)*d return ($a + ($N - 1) * $d); } // Driver code // starting number$a = 2; // Common difference$d = 1; // N th term to be find$N = 5; // Display the outputecho(\"The \" . $N . \"th term of the series is : \" . Nth_of_AP($a, $d, $N)); // This code is contributed by Ajit.?>", "e": 29117, "s": 28648, "text": null }, { "code": "<script> // JavaScript Program to find nth term of // Arithmetic progression function Nth_of_AP(a, d, N) { // using formula to find the // Nth term t(n) = a(1) + (n-1)*d return (a + (N - 1) * d); } // Driver code // starting number let a = 2; // Common difference let d = 1; // N th term to be find let N = 5; // Display the output document.write(\"The \"+ N + \"th term of the series is : \" + Nth_of_AP(a,d,N)); // This code is contributed by Mayank Tyagi </script>", "e": 29682, "s": 29117, "text": null }, { "code": null, "e": 29693, "s": 29682, "text": "Output : " }, { "code": null, "e": 29727, "s": 29693, "text": "The 5th term of the series is : 6" }, { "code": null, "e": 29735, "s": 29729, "text": "jit_t" }, { "code": null, "e": 29751, "s": 29735, "text": "mayanktyagi1709" }, { "code": null, "e": 29774, "s": 29751, "text": "arithmetic progression" }, { "code": null, "e": 29781, "s": 29774, "text": "series" }, { "code": null, "e": 29794, "s": 29781, "text": "Mathematical" }, { "code": null, "e": 29813, "s": 29794, "text": "School Programming" }, { "code": null, "e": 29826, "s": 29813, "text": "Mathematical" }, { "code": null, "e": 29833, "s": 29826, "text": "series" }, { "code": null, "e": 29931, "s": 29833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29955, "s": 29931, "text": "Merge two sorted arrays" }, { "code": null, "e": 29998, "s": 29955, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30040, "s": 29998, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30054, "s": 30040, "text": "Prime Numbers" }, { "code": null, "e": 30103, "s": 30054, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30121, "s": 30103, "text": "Python Dictionary" }, { "code": null, "e": 30137, "s": 30121, "text": "Arrays in C/C++" }, { "code": null, "e": 30156, "s": 30137, "text": "Inheritance in C++" }, { "code": null, "e": 30181, "s": 30156, "text": "Reverse a string in Java" } ]
Solidity - Ether Units
In solidity we can use wei, finney, szabo or ether as a suffix to a literal to be used to convert various ether based denominations. Lowest unit is wei and 1e12 represents 1 x 1012. assert(1 wei == 1); assert(1 szabo == 1e12); assert(1 finney == 1e15); assert(1 ether == 1e18); assert(2 ether == 2000 fenny); Similar to currency, Solidity has time units where lowest unit is second and we can use seconds, minutes, hours, days and weeks as suffix to denote time. assert(1 seconds == 1); assert(1 minutes == 60 seconds); assert(1 hours == 60 minutes); assert(1 day == 24 hours); assert(1 week == 7 days); 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2737, "s": 2555, "text": "In solidity we can use wei, finney, szabo or ether as a suffix to a literal to be used to convert various ether based denominations. Lowest unit is wei and 1e12 represents 1 x 1012." }, { "code": null, "e": 2864, "s": 2737, "text": "assert(1 wei == 1);\nassert(1 szabo == 1e12);\nassert(1 finney == 1e15);\nassert(1 ether == 1e18);\nassert(2 ether == 2000 fenny);" }, { "code": null, "e": 3018, "s": 2864, "text": "Similar to currency, Solidity has time units where lowest unit is second and we can use seconds, minutes, hours, days and weeks as suffix to denote time." }, { "code": null, "e": 3159, "s": 3018, "text": "assert(1 seconds == 1);\nassert(1 minutes == 60 seconds);\nassert(1 hours == 60 minutes);\nassert(1 day == 24 hours);\nassert(1 week == 7 days);" }, { "code": null, "e": 3194, "s": 3159, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3211, "s": 3194, "text": " Abhilash Nelson" }, { "code": null, "e": 3246, "s": 3211, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3263, "s": 3246, "text": " Frahaan Hussain" }, { "code": null, "e": 3298, "s": 3263, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3312, "s": 3298, "text": " Swapnil Kole" }, { "code": null, "e": 3319, "s": 3312, "text": " Print" }, { "code": null, "e": 3330, "s": 3319, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML table - set column width
[]
Clothes reviews analysis with NLP — Part 1 | by Valentina Alto | Towards Data Science
Natural Language Processing (NPL) is a field of Artificial Intelligence whose purpose is finding computational methods to interpret human language as it is spoken or written. The idea of NLP goes beyond a mere classification task that could be carried on by ML algorithms or Deep Learning NNs. Indeed, NLP is about interpretation: you want to train your model not only to detect frequent words, but also to count them or to eliminate some noisy punctuations; you want it to tell you whether the mood of the conversation is positive or negative, whether the content of an e-mail is mere publicity or something important, whether the reviews about thriller books in last years have been good or bad. The good news is that, for NLP, we are provided with interesting libraries, available in Python, that offer a pre-trained model able to inquire about written text. Among those, I’m gonna be using Spacy and NLTK. In this article, I’m going to analyze the Women’s Clothing E-Commerce dataset which contains text reviews written by customers (available here). Here it is the description of the dataset: This dataset includes 23486 rows and 10 feature variables. Each row corresponds to a customer review, and includes the variables:Clothing ID: Integer Categorical variable that refers to the specific piece being reviewed.Age: Positive Integer variable of the reviewers age.Title: String variable for the title of the review.Review Text: String variable for the review body.Rating: Positive Ordinal Integer variable for the product score granted by the customer from 1 Worst, to 5 Best.Recommended IND: Binary variable stating where the customer recommends the product where 1 is recommended, 0 is not recommended.Positive Feedback Count: Positive Integer documenting the number of other customers who found this review positive.Division Name: Categorical name of the product high level division.Department Name: Categorical name of the product department name.Class Name: Categorical name of the product class name. So let’s import and inspect our dataset: import pandas as pddf = pd.read_csv('Womens Clothing E-Commerce Reviews.csv')df.head() Now let’s clean it, dropping NaN values and removing useless columns, as well as clean the text. df.dropna(inplace=True)df.reset_index(drop=True, inplace=True)import refor i in range(len(df)): #print(i) df['Review Text'][i] = df['Review Text'][i].replace("'s", " is").replace("'ll", " will").replace("'ve", " have").replace("'m", " am").replace("\'", "'") df['Review Text'][1]df = df.drop('Unnamed: 0', 1)df.head() The idea is extracting the sentiment of each review and see whether it is consistent with the recommendation indicator (1 if the review recommends the item, 0 otherwise). To do so, we will use the Vader module available in the NLTK package (you can find the official documentation here). But first, let’s preprocess our text and extract Lemmas: #importing necessary librariesimport nltkimport en_core_web_smimport spacynlp = spacy.load("en_core_web_sm")from nltk.corpus import stopwordsdef lemmatization(df): df["Lemmas"] = [" ".join([token.lemma_ if token.lemma_ != "- PRON-" else token.text.lower() for sentence in nlp(speech).sents for token in sentence if token.pos_ in {"NOUN", "VERB", "ADJ", "ADV", "X"} and token.is_stop == False]) for speech in df.text] df["Lemmas"] = [" ".join([token.lemma_ if token.lemma_ != "-PRON-" else token.text.lower() for sentence in nlp(speech).sents for token in sentence if token.pos_ in {"NOUN", "VERB", "ADJ", "ADV", "X"} and token.is_stop == False]) for speech in df['Review Text']]df.head() Now let’s perform sentiment analysis on the Lemmas column: from nltk.sentiment.vader import SentimentIntensityAnalyzersid = SentimentIntensityAnalyzer()sentiment=[]for i in range(len(df)): ss = sid.polarity_scores(df.Lemmas[i]) sentiment.append(ss) compound=[sentiment[i]['compound'] for i in range(len(sentiment))]df['compound']=compounddf.head() The compound column contains scores ranging from -1 (very negative) to 1 (very positive). As a general rule, we attribute a ‘positive’ label to a text if its score is greater than 0.05, a ‘negative’ label if it is less than -0.05, and a ‘neutral’ one if it is between -0.05 and 0.05. However, for the purpose of this research question, we will only differentiate between positive and negative, using score=0 as threshold. sent=[]for i in compound: if i<0: sent.append('negative') else: sent.append('positive')df['sentiment']=sentdf.head() Having a first glimpse of the sentiment column, it seems that most of the reviews are positive, but it is consistent with the number of recommended items: out of 19661 reviews, 16087 of them end up with a recommendation. Now let’s see how many recommended items are consistent with the sentiment of the review. Let me borrow for this task the statistical terminology of false-positive/negative and true positive/negative: I talk about false positive when the item is recommended to be purchased, yet the text review is has a negative sentiment. #initializing a 2x2 matrix populated with zerosmat = np.zeros(4).reshape(2,2)true_neg=0true_pos=0false_neg=0false_pos=0for i in range(len(df)): if df['sentiment'][i]=='negative' and df['Recommended IND'][i]==0: true_neg+=1 elif df['sentiment'][i]=='positive' and df['Recommended IND'][i]==1: true_pos+=1 elif df['sentiment'][i]=='positive' and df['Recommended IND'][i]==0: false_neg+=1 elif df['sentiment'][i]=='negative' and df['Recommended IND'][i]==1: false_pos+=1 mat[0][0]=true_negmat[0][1]=false_negmat[1][0]=false_posmat[1][1]=true_posmat Let’s make it a bit prettier: from pandas import DataFrameIndex= ['Not Recommended', 'Recommended']Cols = ['Negative', 'Positive']d = DataFrame(mat, index=Index, columns=Cols) So out of the 16087 recommended items, only 227 of them are not consistent with the sentiment of the text. On the other side, we are not recommending 3154 items that have actually received a positive review. This kind of results might suggest a different approach towards the recommendation system since more items might be purchased if we look at the sentiment of reviewers. Sentiment analysis plays a pivotal role in market research and similar fields. Indeed, keeping track of customers’ satisfaction and, most importantly, isolate those drivers which determine their sentiment towards items, could lead to winning marketing campaigns and selling strategies. In this article I limited my research to the sentiment analysis, however this dataset offers multiple research questions, which will be covered in my next articles, so stay tuned!
[ { "code": null, "e": 870, "s": 172, "text": "Natural Language Processing (NPL) is a field of Artificial Intelligence whose purpose is finding computational methods to interpret human language as it is spoken or written. The idea of NLP goes beyond a mere classification task that could be carried on by ML algorithms or Deep Learning NNs. Indeed, NLP is about interpretation: you want to train your model not only to detect frequent words, but also to count them or to eliminate some noisy punctuations; you want it to tell you whether the mood of the conversation is positive or negative, whether the content of an e-mail is mere publicity or something important, whether the reviews about thriller books in last years have been good or bad." }, { "code": null, "e": 1082, "s": 870, "text": "The good news is that, for NLP, we are provided with interesting libraries, available in Python, that offer a pre-trained model able to inquire about written text. Among those, I’m gonna be using Spacy and NLTK." }, { "code": null, "e": 1227, "s": 1082, "text": "In this article, I’m going to analyze the Women’s Clothing E-Commerce dataset which contains text reviews written by customers (available here)." }, { "code": null, "e": 1270, "s": 1227, "text": "Here it is the description of the dataset:" }, { "code": null, "e": 2185, "s": 1270, "text": "This dataset includes 23486 rows and 10 feature variables. Each row corresponds to a customer review, and includes the variables:Clothing ID: Integer Categorical variable that refers to the specific piece being reviewed.Age: Positive Integer variable of the reviewers age.Title: String variable for the title of the review.Review Text: String variable for the review body.Rating: Positive Ordinal Integer variable for the product score granted by the customer from 1 Worst, to 5 Best.Recommended IND: Binary variable stating where the customer recommends the product where 1 is recommended, 0 is not recommended.Positive Feedback Count: Positive Integer documenting the number of other customers who found this review positive.Division Name: Categorical name of the product high level division.Department Name: Categorical name of the product department name.Class Name: Categorical name of the product class name." }, { "code": null, "e": 2226, "s": 2185, "text": "So let’s import and inspect our dataset:" }, { "code": null, "e": 2313, "s": 2226, "text": "import pandas as pddf = pd.read_csv('Womens Clothing E-Commerce Reviews.csv')df.head()" }, { "code": null, "e": 2410, "s": 2313, "text": "Now let’s clean it, dropping NaN values and removing useless columns, as well as clean the text." }, { "code": null, "e": 2737, "s": 2410, "text": "df.dropna(inplace=True)df.reset_index(drop=True, inplace=True)import refor i in range(len(df)): #print(i) df['Review Text'][i] = df['Review Text'][i].replace(\"'s\", \" is\").replace(\"'ll\", \" will\").replace(\"'ve\", \" have\").replace(\"'m\", \" am\").replace(\"\\'\", \"'\") df['Review Text'][1]df = df.drop('Unnamed: 0', 1)df.head()" }, { "code": null, "e": 2908, "s": 2737, "text": "The idea is extracting the sentiment of each review and see whether it is consistent with the recommendation indicator (1 if the review recommends the item, 0 otherwise)." }, { "code": null, "e": 3082, "s": 2908, "text": "To do so, we will use the Vader module available in the NLTK package (you can find the official documentation here). But first, let’s preprocess our text and extract Lemmas:" }, { "code": null, "e": 3876, "s": 3082, "text": "#importing necessary librariesimport nltkimport en_core_web_smimport spacynlp = spacy.load(\"en_core_web_sm\")from nltk.corpus import stopwordsdef lemmatization(df): df[\"Lemmas\"] = [\" \".join([token.lemma_ if token.lemma_ != \"- PRON-\" else token.text.lower() for sentence in nlp(speech).sents for token in sentence if token.pos_ in {\"NOUN\", \"VERB\", \"ADJ\", \"ADV\", \"X\"} and token.is_stop == False]) for speech in df.text] df[\"Lemmas\"] = [\" \".join([token.lemma_ if token.lemma_ != \"-PRON-\" else token.text.lower() for sentence in nlp(speech).sents for token in sentence if token.pos_ in {\"NOUN\", \"VERB\", \"ADJ\", \"ADV\", \"X\"} and token.is_stop == False]) for speech in df['Review Text']]df.head()" }, { "code": null, "e": 3935, "s": 3876, "text": "Now let’s perform sentiment analysis on the Lemmas column:" }, { "code": null, "e": 4235, "s": 3935, "text": "from nltk.sentiment.vader import SentimentIntensityAnalyzersid = SentimentIntensityAnalyzer()sentiment=[]for i in range(len(df)): ss = sid.polarity_scores(df.Lemmas[i]) sentiment.append(ss) compound=[sentiment[i]['compound'] for i in range(len(sentiment))]df['compound']=compounddf.head()" }, { "code": null, "e": 4657, "s": 4235, "text": "The compound column contains scores ranging from -1 (very negative) to 1 (very positive). As a general rule, we attribute a ‘positive’ label to a text if its score is greater than 0.05, a ‘negative’ label if it is less than -0.05, and a ‘neutral’ one if it is between -0.05 and 0.05. However, for the purpose of this research question, we will only differentiate between positive and negative, using score=0 as threshold." }, { "code": null, "e": 4794, "s": 4657, "text": "sent=[]for i in compound: if i<0: sent.append('negative') else: sent.append('positive')df['sentiment']=sentdf.head()" }, { "code": null, "e": 5015, "s": 4794, "text": "Having a first glimpse of the sentiment column, it seems that most of the reviews are positive, but it is consistent with the number of recommended items: out of 19661 reviews, 16087 of them end up with a recommendation." }, { "code": null, "e": 5339, "s": 5015, "text": "Now let’s see how many recommended items are consistent with the sentiment of the review. Let me borrow for this task the statistical terminology of false-positive/negative and true positive/negative: I talk about false positive when the item is recommended to be purchased, yet the text review is has a negative sentiment." }, { "code": null, "e": 5928, "s": 5339, "text": "#initializing a 2x2 matrix populated with zerosmat = np.zeros(4).reshape(2,2)true_neg=0true_pos=0false_neg=0false_pos=0for i in range(len(df)): if df['sentiment'][i]=='negative' and df['Recommended IND'][i]==0: true_neg+=1 elif df['sentiment'][i]=='positive' and df['Recommended IND'][i]==1: true_pos+=1 elif df['sentiment'][i]=='positive' and df['Recommended IND'][i]==0: false_neg+=1 elif df['sentiment'][i]=='negative' and df['Recommended IND'][i]==1: false_pos+=1 mat[0][0]=true_negmat[0][1]=false_negmat[1][0]=false_posmat[1][1]=true_posmat" }, { "code": null, "e": 5958, "s": 5928, "text": "Let’s make it a bit prettier:" }, { "code": null, "e": 6104, "s": 5958, "text": "from pandas import DataFrameIndex= ['Not Recommended', 'Recommended']Cols = ['Negative', 'Positive']d = DataFrame(mat, index=Index, columns=Cols)" }, { "code": null, "e": 6480, "s": 6104, "text": "So out of the 16087 recommended items, only 227 of them are not consistent with the sentiment of the text. On the other side, we are not recommending 3154 items that have actually received a positive review. This kind of results might suggest a different approach towards the recommendation system since more items might be purchased if we look at the sentiment of reviewers." }, { "code": null, "e": 6766, "s": 6480, "text": "Sentiment analysis plays a pivotal role in market research and similar fields. Indeed, keeping track of customers’ satisfaction and, most importantly, isolate those drivers which determine their sentiment towards items, could lead to winning marketing campaigns and selling strategies." } ]
C# | Swap two Strings without using third user defined variable - GeeksforGeeks
18 Oct, 2021 Given two string variables a and b, swap these variables without using a temporary or third variable in C#. Use of library methods is allowed. Example: Input: a = "Hello" b = "World" Output: Strings before swap: a = Hello and b = World Strings after swap: a = World and b = Hello The idea is to do string concatenation and then use Substring() method to perform this operation. The Substring() method comes in two forms as listed below: String.Substring Method (startIndex): This method is used to retrieve a substring from the current instance of the string. The parameter “startIndex” will specify the starting position of substring and then substring will continue to the end of the string. String.Substring Method (int startIndex, int length): This method is used to extract a substring that begins from specified position described by parameter startIndex and has a specified length. If startIndex is equal to the length of string and parameter length is zero, then it will return nothing as substring. Algorithm: 1) Append second string to first string and store in first string: a = a + b 2) Call the Substring Method (int startIndex, int length) by passing startindex as 0 and length as, a.Length - b.Length: b = Substring(0, a.Length - b.Length); 3) Call the Substring Method(int startIndex) by passing startindex as b.Length as the argument to store the value of initial b string in a a = Substring(b.Length); // C# program to swap two strings// without using a temporary variable.using System; class GFG { // Main Method public static void Main(String[] args) { // Declare two strings String a = "Hello"; String b = "Geeks"; // Print String before swapping Console.WriteLine("Strings before swap: a =" + " " + a + " and b = " + b); // append 2nd string to 1st a = a + b; // store initial string a in string b b = a.Substring(0, a.Length - b.Length); // store initial string b in string a a = a.Substring(b.Length); // print String after swapping Console.WriteLine("Strings after swap: a =" + " " + a + " and b = " + b); }} Output: Strings before swap: a = Hello and b = Geeks Strings after swap: a = Geeks and b = Hello kashishsoda CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23937, "s": 23909, "text": "\n18 Oct, 2021" }, { "code": null, "e": 24080, "s": 23937, "text": "Given two string variables a and b, swap these variables without using a temporary or third variable in C#. Use of library methods is allowed." }, { "code": null, "e": 24089, "s": 24080, "text": "Example:" }, { "code": null, "e": 24218, "s": 24089, "text": "Input:\na = \"Hello\"\nb = \"World\"\n\nOutput:\nStrings before swap: a = Hello and b = World\nStrings after swap: a = World and b = Hello" }, { "code": null, "e": 24375, "s": 24218, "text": "The idea is to do string concatenation and then use Substring() method to perform this operation. The Substring() method comes in two forms as listed below:" }, { "code": null, "e": 24632, "s": 24375, "text": "String.Substring Method (startIndex): This method is used to retrieve a substring from the current instance of the string. The parameter “startIndex” will specify the starting position of substring and then substring will continue to the end of the string." }, { "code": null, "e": 24946, "s": 24632, "text": "String.Substring Method (int startIndex, int length): This method is used to extract a substring that begins from specified position described by parameter startIndex and has a specified length. If startIndex is equal to the length of string and parameter length is zero, then it will return nothing as substring." }, { "code": null, "e": 24957, "s": 24946, "text": "Algorithm:" }, { "code": null, "e": 25388, "s": 24957, "text": "1) Append second string to first string and \n store in first string:\n a = a + b\n\n2) Call the Substring Method (int startIndex, int length)\n by passing startindex as 0 and length as,\n a.Length - b.Length:\n b = Substring(0, a.Length - b.Length);\n\n3) Call the Substring Method(int startIndex) by passing \n startindex as b.Length as the argument to store the \n value of initial b string in a\n a = Substring(b.Length);\n" }, { "code": "// C# program to swap two strings// without using a temporary variable.using System; class GFG { // Main Method public static void Main(String[] args) { // Declare two strings String a = \"Hello\"; String b = \"Geeks\"; // Print String before swapping Console.WriteLine(\"Strings before swap: a =\" + \" \" + a + \" and b = \" + b); // append 2nd string to 1st a = a + b; // store initial string a in string b b = a.Substring(0, a.Length - b.Length); // store initial string b in string a a = a.Substring(b.Length); // print String after swapping Console.WriteLine(\"Strings after swap: a =\" + \" \" + a + \" and b = \" + b); }}", "e": 26169, "s": 25388, "text": null }, { "code": null, "e": 26177, "s": 26169, "text": "Output:" }, { "code": null, "e": 26267, "s": 26177, "text": "Strings before swap: a = Hello and b = Geeks\nStrings after swap: a = Geeks and b = Hello\n" }, { "code": null, "e": 26279, "s": 26267, "text": "kashishsoda" }, { "code": null, "e": 26293, "s": 26279, "text": "CSharp-string" }, { "code": null, "e": 26296, "s": 26293, "text": "C#" }, { "code": null, "e": 26394, "s": 26296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26403, "s": 26394, "text": "Comments" }, { "code": null, "e": 26416, "s": 26403, "text": "Old Comments" }, { "code": null, "e": 26456, "s": 26416, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26479, "s": 26456, "text": "Extension Method in C#" }, { "code": null, "e": 26507, "s": 26479, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26529, "s": 26507, "text": "Partial Classes in C#" }, { "code": null, "e": 26546, "s": 26529, "text": "C# | Inheritance" }, { "code": null, "e": 26586, "s": 26546, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 26619, "s": 26586, "text": "Linked List Implementation in C#" }, { "code": null, "e": 26662, "s": 26619, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26678, "s": 26662, "text": "C# | List Class" } ]
How to validate if JTable has an empty cell in Java?
A JTable is a subclass of JComponent class for displaying complex data structures. A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable will generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces. We can validate whether the JTable cell is empty or not by implementing the getValueAt() method of JTable class. If we click on the "Click Here" button, it will generate an action event and display a popup message like "Field is Empty" to the user. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class JTableEmptyValidateTest extends JFrame { private JPanel panel; private JTable table; private JButton button; String[] columnNames = new String[] {"Student 1", "Student 2"}; String[][] dataValues = new String[][] {{"95", "100"}, {"", "85"}, {"80", "100"}}; public JTableEmptyValidateTest() { setTitle("Empty Validation Table"); panel = new JPanel(); table = new JTable(); TableModel model = new myTableModel(); table.setModel(model); panel.add(new JScrollPane(table)); button = new JButton("Click Here"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if(validCheck()) { JOptionPane.showMessageDialog(null,"Field is filled up"); } else { JOptionPane.showMessageDialog(null, "Field is empty"); } } }); add(panel, BorderLayout.CENTER); add(button, BorderLayout.SOUTH); setSize(470, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public boolean validCheck() { if(table.getCellEditor()!= null) { table.getCellEditor().stopCellEditing(); } for(int i=0; i < table.getRowCount(); i++) { for(int j=0; j < table.getColumnCount(); j++) { String value = table.getValueAt(i,j).toString(); if(value.trim().length() == 0) { return false; } } } return true; } class myTableModel extends DefaultTableModel { myTableModel() { super(dataValues, columnNames); } public boolean isCellEditable(int row, int cols) { return true; } } public static void main(String args[]) { new JTableEmptyValidateTest(); } }
[ { "code": null, "e": 1402, "s": 1062, "text": "A JTable is a subclass of JComponent class for displaying complex data structures. A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable will generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces." }, { "code": null, "e": 1651, "s": 1402, "text": "We can validate whether the JTable cell is empty or not by implementing the getValueAt() method of JTable class. If we click on the \"Click Here\" button, it will generate an action event and display a popup message like \"Field is Empty\" to the user." }, { "code": null, "e": 3612, "s": 1651, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\npublic class JTableEmptyValidateTest extends JFrame {\n private JPanel panel;\n private JTable table;\n private JButton button;\n String[] columnNames = new String[] {\"Student 1\", \"Student 2\"};\n String[][] dataValues = new String[][] {{\"95\", \"100\"}, {\"\", \"85\"}, {\"80\", \"100\"}};\n public JTableEmptyValidateTest() {\n setTitle(\"Empty Validation Table\");\n panel = new JPanel();\n table = new JTable();\n TableModel model = new myTableModel();\n table.setModel(model);\n panel.add(new JScrollPane(table));\n button = new JButton(\"Click Here\");\n button.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent event) {\n if(validCheck()) {\n JOptionPane.showMessageDialog(null,\"Field is filled up\");\n } else {\n JOptionPane.showMessageDialog(null, \"Field is empty\");\n }\n }\n });\n add(panel, BorderLayout.CENTER);\n add(button, BorderLayout.SOUTH);\n setSize(470, 300);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public boolean validCheck() {\n if(table.getCellEditor()!= null) {\n table.getCellEditor().stopCellEditing();\n }\n for(int i=0; i < table.getRowCount(); i++) {\n for(int j=0; j < table.getColumnCount(); j++) {\n String value = table.getValueAt(i,j).toString();\n if(value.trim().length() == 0) {\n return false;\n }\n }\n }\n return true;\n }\n class myTableModel extends DefaultTableModel {\n myTableModel() {\n super(dataValues, columnNames);\n }\n public boolean isCellEditable(int row, int cols) {\n return true;\n }\n }\n public static void main(String args[]) {\n new JTableEmptyValidateTest();\n }\n}" } ]
ReactJS Reactstrap Card Component - GeeksforGeeks
01 Aug, 2021 Reactstrap: 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 Card components allow the user to display content. We can use the following approach in ReactJS to use the ReactJS Reactstrap Card Component. Properties of the ReactStarp props: Card Props: tag: Card Props tag can be a function or a string, and it is used to denote the tag for this component. inverse: The inverse props in reactStrap are used to indicate whether to inverse text color or not. color: The color props are used to change the color of the card. It should be RGB format and the name of the color. body: The body props are used to indicate whether to apply card-body class or not in the reactStrap component. className: The className props are used to denote the class name for styling the component in reactStrap. CardBody Props: tag: The CardBody props can be a function or a string, and it is used to denote the tag for this component in reactStrap. className: The className props are used to denote the class name for this component in reactStrap. CardColumns Props: tag: The tag CardColumns Props can be a function or a string, and it is used to denote the tag for this component. className: The className props are used to denote the class name for this component, which is used for styling the CSS. Card deck Props: tag: The tag props come under the Card deck Props. On the card deck, it can be a function or a string, and it is used to denote the tag for this component. className: The className props come under Card deck Props and are used to denote the class name for this component. CardFooter Props: tag: The tag Props come under the CardFooter Props. It can be a function or a string, and it is used to denote the tag for this component. className: The className props come under the CardFooter Props. It is used to denote the class name for this component. CardGroup Props: tag: The tag props in CardGroup can be a function or a string, and it is used to denote the tag for this component. className: className pops comes under the CardGroup Props .It is used to denote the class name for this component. CardHeader Props: tag: The CardHeader tag prop can be a function or a string, and it is used to denote the tag for this component. className: The className props come under CardHeader props .It is used to denote the class name for this component. CardImg Props: tag: The tag can be a function or a string, and it is used to denote the tag for this component. className: The className is used to denote the class name for this component. top: The top props are used to position images through card-img-top class. bottom: The bottom props are used to position images through card-img-bottom class. CardImgOverlay Props: tag: The tag prop can be a function or a string, and it is used to denote the tag for this component. className: The className props are used to denote the class name for this component. CardLink Props: tag: This cardLink prop can be a function or a string, and it is used to denote the tag for this component. className: This className prop is used to denote the class name for this component. innerRef: This innerRef prop is used to denote the inner reference element. CardSubtitle Props: tag: This prop can be a function or a string, and it is used to denote the tag for this component. className: These props can be used to denote the class name for this component. CardText Props: tag: This prop can be a function or a string, and it is used to denote the tag for this component. className: This prop is used to denote the class name for this component. CardTitle Props : tag: This prop can be a function or a string, and it is used to denote the tag for this component. className: These props, className props are used to denote the class name for this component. The syntax for Creating React Application And Installing Modules: Step 1: Create a React application using the following command.npx create-react-app foldername npx create-react-app foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command.cd foldername cd foldername Step 3: Install Reactstrap in your given directory. npm install --save reactstrap react react-dom Project Structure: It will look like the following : Project Structure Example 1: Now write down the following code in the App.js file. Here, the App is our default component where we have written our code. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Card, CardImg, CardBody, CardTitle, CardText, Button} from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Card Component</h4> <Card> <CardImg width="50px" height="50px" src="https://media.geeksforgeeks.org/wp-content/ uploads/20210425000233/test-300x297.png" alt="GFG Logo" /> <CardBody> <CardTitle tag="h5">Sample Card title</CardTitle> <CardText>Sample Card Text to display!</CardText> <Button>Action Button</Button> </CardBody> </Card> </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: Card Component Example 2:This is another example for ReactStrap card component. App.js import React from "react";import { Card,CardBody,CardLink,CardTitle, } from "reactstrap"; const Example = (props) => { return ( <div> <Card> <CardBody> <CardTitle tag="h5">GFG Practice Portal </CardTitle> <img width="50%" src="https://media.geeksforgeeks.org/wp-content/ uploads/20210728115525/imggggg.png" alt="Card image cap" /> <p> The Best Data Structures Course Available Online From Skilled And Experienced Faculty. Learn Data Structures In A Live Classroom With The Best Of Faculty In The Industry. Classroom Experience. </p> </CardBody> <CardBody> <CardLink href="https://www.geeksforgeeks.org/html-images/"> To knbow more about us... </CardLink> </CardBody> </Card> </div> );}; export default Example; card components Reference: https://reactstrap.github.io/components/card/ Reactstrap JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to get selected value in dropdown list using JavaScript ? 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": 24921, "s": 24893, "text": "\n01 Aug, 2021" }, { "code": null, "e": 25241, "s": 24921, "text": "Reactstrap: 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 Card components allow the user to display content. We can use the following approach in ReactJS to use the ReactJS Reactstrap Card Component." }, { "code": null, "e": 25277, "s": 25241, "text": "Properties of the ReactStarp props:" }, { "code": null, "e": 25289, "s": 25277, "text": "Card Props:" }, { "code": null, "e": 25393, "s": 25289, "text": "tag: Card Props tag can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 25493, "s": 25393, "text": "inverse: The inverse props in reactStrap are used to indicate whether to inverse text color or not." }, { "code": null, "e": 25610, "s": 25493, "text": "color: The color props are used to change the color of the card. It should be RGB format and the name of the color." }, { "code": null, "e": 25721, "s": 25610, "text": "body: The body props are used to indicate whether to apply card-body class or not in the reactStrap component." }, { "code": null, "e": 25827, "s": 25721, "text": "className: The className props are used to denote the class name for styling the component in reactStrap." }, { "code": null, "e": 25843, "s": 25827, "text": "CardBody Props:" }, { "code": null, "e": 25965, "s": 25843, "text": "tag: The CardBody props can be a function or a string, and it is used to denote the tag for this component in reactStrap." }, { "code": null, "e": 26064, "s": 25965, "text": "className: The className props are used to denote the class name for this component in reactStrap." }, { "code": null, "e": 26085, "s": 26066, "text": "CardColumns Props:" }, { "code": null, "e": 26200, "s": 26085, "text": "tag: The tag CardColumns Props can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 26320, "s": 26200, "text": "className: The className props are used to denote the class name for this component, which is used for styling the CSS." }, { "code": null, "e": 26337, "s": 26320, "text": "Card deck Props:" }, { "code": null, "e": 26493, "s": 26337, "text": "tag: The tag props come under the Card deck Props. On the card deck, it can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 26609, "s": 26493, "text": "className: The className props come under Card deck Props and are used to denote the class name for this component." }, { "code": null, "e": 26627, "s": 26609, "text": "CardFooter Props:" }, { "code": null, "e": 26766, "s": 26627, "text": "tag: The tag Props come under the CardFooter Props. It can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 26886, "s": 26766, "text": "className: The className props come under the CardFooter Props. It is used to denote the class name for this component." }, { "code": null, "e": 26903, "s": 26886, "text": "CardGroup Props:" }, { "code": null, "e": 27019, "s": 26903, "text": "tag: The tag props in CardGroup can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 27134, "s": 27019, "text": "className: className pops comes under the CardGroup Props .It is used to denote the class name for this component." }, { "code": null, "e": 27152, "s": 27134, "text": "CardHeader Props:" }, { "code": null, "e": 27265, "s": 27152, "text": "tag: The CardHeader tag prop can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 27381, "s": 27265, "text": "className: The className props come under CardHeader props .It is used to denote the class name for this component." }, { "code": null, "e": 27396, "s": 27381, "text": "CardImg Props:" }, { "code": null, "e": 27493, "s": 27396, "text": "tag: The tag can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 27571, "s": 27493, "text": "className: The className is used to denote the class name for this component." }, { "code": null, "e": 27646, "s": 27571, "text": "top: The top props are used to position images through card-img-top class." }, { "code": null, "e": 27730, "s": 27646, "text": "bottom: The bottom props are used to position images through card-img-bottom class." }, { "code": null, "e": 27752, "s": 27730, "text": "CardImgOverlay Props:" }, { "code": null, "e": 27854, "s": 27752, "text": "tag: The tag prop can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 27939, "s": 27854, "text": "className: The className props are used to denote the class name for this component." }, { "code": null, "e": 27957, "s": 27941, "text": "CardLink Props:" }, { "code": null, "e": 28065, "s": 27957, "text": "tag: This cardLink prop can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 28149, "s": 28065, "text": "className: This className prop is used to denote the class name for this component." }, { "code": null, "e": 28225, "s": 28149, "text": "innerRef: This innerRef prop is used to denote the inner reference element." }, { "code": null, "e": 28245, "s": 28225, "text": "CardSubtitle Props:" }, { "code": null, "e": 28344, "s": 28245, "text": "tag: This prop can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 28424, "s": 28344, "text": "className: These props can be used to denote the class name for this component." }, { "code": null, "e": 28440, "s": 28424, "text": "CardText Props:" }, { "code": null, "e": 28539, "s": 28440, "text": "tag: This prop can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 28613, "s": 28539, "text": "className: This prop is used to denote the class name for this component." }, { "code": null, "e": 28631, "s": 28613, "text": "CardTitle Props :" }, { "code": null, "e": 28730, "s": 28631, "text": "tag: This prop can be a function or a string, and it is used to denote the tag for this component." }, { "code": null, "e": 28824, "s": 28730, "text": "className: These props, className props are used to denote the class name for this component." }, { "code": null, "e": 28890, "s": 28824, "text": "The syntax for Creating React Application And Installing Modules:" }, { "code": null, "e": 28985, "s": 28890, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 29017, "s": 28985, "text": "npx create-react-app foldername" }, { "code": null, "e": 29131, "s": 29017, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command.cd foldername" }, { "code": null, "e": 29145, "s": 29131, "text": "cd foldername" }, { "code": null, "e": 29197, "s": 29145, "text": "Step 3: Install Reactstrap in your given directory." }, { "code": null, "e": 29244, "s": 29197, "text": " npm install --save reactstrap react react-dom" }, { "code": null, "e": 29297, "s": 29244, "text": "Project Structure: It will look like the following :" }, { "code": null, "e": 29315, "s": 29297, "text": "Project Structure" }, { "code": null, "e": 29451, "s": 29315, "text": "Example 1: Now write down the following code in the App.js file. Here, the App is our default component where we have written our code." }, { "code": null, "e": 29458, "s": 29451, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Card, CardImg, CardBody, CardTitle, CardText, Button} from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Card Component</h4> <Card> <CardImg width=\"50px\" height=\"50px\" src=\"https://media.geeksforgeeks.org/wp-content/ uploads/20210425000233/test-300x297.png\" alt=\"GFG Logo\" /> <CardBody> <CardTitle tag=\"h5\">Sample Card title</CardTitle> <CardText>Sample Card Text to display!</CardText> <Button>Action Button</Button> </CardBody> </Card> </div> );} export default App;", "e": 30361, "s": 29458, "text": null }, { "code": null, "e": 30477, "s": 30363, "text": "Step to Run Application: Run the application using the following command from the root directory of the project: " }, { "code": null, "e": 30487, "s": 30477, "text": "npm start" }, { "code": null, "e": 30586, "s": 30487, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 30601, "s": 30586, "text": "Card Component" }, { "code": null, "e": 30667, "s": 30601, "text": "Example 2:This is another example for ReactStrap card component. " }, { "code": null, "e": 30674, "s": 30667, "text": "App.js" }, { "code": "import React from \"react\";import { Card,CardBody,CardLink,CardTitle, } from \"reactstrap\"; const Example = (props) => { return ( <div> <Card> <CardBody> <CardTitle tag=\"h5\">GFG Practice Portal </CardTitle> <img width=\"50%\" src=\"https://media.geeksforgeeks.org/wp-content/ uploads/20210728115525/imggggg.png\" alt=\"Card image cap\" /> <p> The Best Data Structures Course Available Online From Skilled And Experienced Faculty. Learn Data Structures In A Live Classroom With The Best Of Faculty In The Industry. Classroom Experience. </p> </CardBody> <CardBody> <CardLink href=\"https://www.geeksforgeeks.org/html-images/\"> To knbow more about us... </CardLink> </CardBody> </Card> </div> );}; export default Example;", "e": 31647, "s": 30674, "text": null }, { "code": null, "e": 31664, "s": 31647, "text": "card components " }, { "code": null, "e": 31721, "s": 31664, "text": "Reference: https://reactstrap.github.io/components/card/" }, { "code": null, "e": 31732, "s": 31721, "text": "Reactstrap" }, { "code": null, "e": 31743, "s": 31732, "text": "JavaScript" }, { "code": null, "e": 31751, "s": 31743, "text": "ReactJS" }, { "code": null, "e": 31768, "s": 31751, "text": "Web Technologies" }, { "code": null, "e": 31866, "s": 31768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31875, "s": 31866, "text": "Comments" }, { "code": null, "e": 31888, "s": 31875, "text": "Old Comments" }, { "code": null, "e": 31949, "s": 31888, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31990, "s": 31949, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 32030, "s": 31990, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32084, "s": 32030, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 32146, "s": 32084, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 32189, "s": 32146, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 32234, "s": 32189, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 32299, "s": 32234, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 32367, "s": 32299, "text": "How to pass data from one component to other component in ReactJS ?" } ]
How to read/parse JSON array using Java?
A Json array is an ordered collection of values that are enclosed in square brackets i.e. it begins with ‘[’ and ends with ‘]’. The values in the arrays are separated by ‘,’ (comma). { "books": [ Java, JavaFX, Hbase, Cassandra, WebGL, JOGL] } The json-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using Java program. Following is the maven dependency for the JSON-simple library − <dependencies> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> </dependencies> Paste this with in the <dependencies> </dependencies> tag at the end of your pom.xml file. (before </project> tag) First of all, let us create a JSON document with name sample.json with the 6 key-value pairs and an array as shown below − { "ID": "1", "First_Name": "Krishna Kasyap", "Last_Name": "Bhagavatula", "Date_Of_Birth": "1989-09-26", "Place_Of_Birth":"Vishakhapatnam", "Salary": "25000" "contact": [ "e-mail: [email protected]", "phone: 9848022338", "city: Hyderabad", "Area: Madapur", "State: Telangana" ] } To read an array from a JSON file using a Java program − Instantiate the JSONParser class of the json-simple library. JSONParser jsonParser = new JSONParser(); Parse the contents of the obtained object using the parse() method. //Parsing the contents of the JSON file JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/players_data.json")); Retrieve the value associated with a key using the get() method. String value = (String) jsonObject.get("key_name"); Just like other element retrieve the json array using the get() method into the JSONArray object. JSONArray jsonArray = (JSONArray) jsonObject.get("contact"); The iterator() method of the JSONArray class returns an Iterator object using which you can iterate the contents of the current array. //Iterating the contents of the array Iterator<String> iterator = jsonArray.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } Following Java program parses the above created sample.json file, reads its contents and, displays them. import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ReadingArrayFromJSON { public static void main(String args[]) { //Creating a JSONParser object JSONParser jsonParser = new JSONParser(); try { //Parsing the contents of the JSON file JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/test.json")); //Forming URL System.out.println("Contents of the JSON are: "); System.out.println("ID: "+jsonObject.get("ID")); System.out.println("First name: "+jsonObject.get("First_Name")); System.out.println("Last name: "+jsonObject.get("Last_Name")); System.out.println("Date of birth: "+ jsonObject.get("Date_Of_Birth")); System.out.println("Place of birth: "+ jsonObject.get("Place_Of_Birth")); System.out.println("Salary: "+jsonObject.get("Salary")); //Retrieving the array JSONArray jsonArray = (JSONArray) jsonObject.get("contact"); System.out.println(""); System.out.println("Contact details: "); //Iterating the contents of the array Iterator<String> iterator = jsonArray.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } } Contents of the JSON are: ID: 1 First name: Krishna Kasyap Last name: Bhagavatula Date of birth: 1989-09-26 Place of birth: Vishakhapatnam Salary: 25000 Contact details: e-mail: [email protected] phone: 9848022338 city: Hyderabad Area: Madapur State: Telangana
[ { "code": null, "e": 1245, "s": 1062, "text": "A Json array is an ordered collection of values that are enclosed in square brackets i.e. it begins with ‘[’ and ends with ‘]’. The values in the arrays are separated by ‘,’ (comma)." }, { "code": null, "e": 1308, "s": 1245, "text": "{\n \"books\": [ Java, JavaFX, Hbase, Cassandra, WebGL, JOGL]\n}" }, { "code": null, "e": 1475, "s": 1308, "text": "The json-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using Java program." }, { "code": null, "e": 1539, "s": 1475, "text": "Following is the maven dependency for the JSON-simple library −" }, { "code": null, "e": 1729, "s": 1539, "text": "<dependencies>\n <dependency>\n <groupId>com.googlecode.json-simple</groupId>\n <artifactId>json-simple</artifactId>\n <version>1.1.1</version>\n </dependency>\n</dependencies>" }, { "code": null, "e": 1844, "s": 1729, "text": "Paste this with in the <dependencies> </dependencies> tag at the end of your pom.xml file. (before </project> tag)" }, { "code": null, "e": 1967, "s": 1844, "text": "First of all, let us create a JSON document with name sample.json with the 6 key-value pairs and an array as shown below −" }, { "code": null, "e": 2307, "s": 1967, "text": "{\n \"ID\": \"1\",\n \"First_Name\": \"Krishna Kasyap\",\n \"Last_Name\": \"Bhagavatula\",\n \"Date_Of_Birth\": \"1989-09-26\",\n \"Place_Of_Birth\":\"Vishakhapatnam\",\n \"Salary\": \"25000\"\n \"contact\": [\n \"e-mail: [email protected]\",\n \"phone: 9848022338\",\n \"city: Hyderabad\",\n \"Area: Madapur\",\n \"State: Telangana\"\n ]\n}" }, { "code": null, "e": 2364, "s": 2307, "text": "To read an array from a JSON file using a Java program −" }, { "code": null, "e": 2425, "s": 2364, "text": "Instantiate the JSONParser class of the json-simple library." }, { "code": null, "e": 2467, "s": 2425, "text": "JSONParser jsonParser = new JSONParser();" }, { "code": null, "e": 2535, "s": 2467, "text": "Parse the contents of the obtained object using the parse() method." }, { "code": null, "e": 2670, "s": 2535, "text": "//Parsing the contents of the JSON file\nJSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader(\"E:/players_data.json\"));" }, { "code": null, "e": 2735, "s": 2670, "text": "Retrieve the value associated with a key using the get() method." }, { "code": null, "e": 2787, "s": 2735, "text": "String value = (String) jsonObject.get(\"key_name\");" }, { "code": null, "e": 2885, "s": 2787, "text": "Just like other element retrieve the json array using the get() method into the JSONArray object." }, { "code": null, "e": 2946, "s": 2885, "text": "JSONArray jsonArray = (JSONArray) jsonObject.get(\"contact\");" }, { "code": null, "e": 3081, "s": 2946, "text": "The iterator() method of the JSONArray class returns an Iterator object using which you can iterate the contents of the current array." }, { "code": null, "e": 3239, "s": 3081, "text": "//Iterating the contents of the array\nIterator<String> iterator = jsonArray.iterator();\nwhile(iterator.hasNext()) {\n System.out.println(iterator.next());\n}" }, { "code": null, "e": 3344, "s": 3239, "text": "Following Java program parses the above created sample.json file, reads its contents and, displays them." }, { "code": null, "e": 5067, "s": 3344, "text": "import java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Iterator;\nimport org.json.simple.JSONArray;\nimport org.json.simple.JSONObject;\nimport org.json.simple.parser.JSONParser;\nimport org.json.simple.parser.ParseException;\npublic class ReadingArrayFromJSON {\n public static void main(String args[]) {\n //Creating a JSONParser object\n JSONParser jsonParser = new JSONParser();\n try {\n //Parsing the contents of the JSON file\n JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader(\"E:/test.json\"));\n //Forming URL\n System.out.println(\"Contents of the JSON are: \");\n System.out.println(\"ID: \"+jsonObject.get(\"ID\"));\n System.out.println(\"First name: \"+jsonObject.get(\"First_Name\"));\n System.out.println(\"Last name: \"+jsonObject.get(\"Last_Name\"));\n System.out.println(\"Date of birth: \"+ jsonObject.get(\"Date_Of_Birth\"));\n System.out.println(\"Place of birth: \"+ jsonObject.get(\"Place_Of_Birth\"));\n System.out.println(\"Salary: \"+jsonObject.get(\"Salary\"));\n //Retrieving the array\n JSONArray jsonArray = (JSONArray) jsonObject.get(\"contact\");\n System.out.println(\"\");\n System.out.println(\"Contact details: \");\n //Iterating the contents of the array\n Iterator<String> iterator = jsonArray.iterator();\n while(iterator.hasNext()) {\n System.out.println(iterator.next());\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 5335, "s": 5067, "text": "Contents of the JSON are:\nID: 1\nFirst name: Krishna Kasyap\nLast name: Bhagavatula\nDate of birth: 1989-09-26\nPlace of birth: Vishakhapatnam\nSalary: 25000\nContact details:\ne-mail: [email protected]\nphone: 9848022338\ncity: Hyderabad\nArea: Madapur\nState: Telangana" } ]
MATLAB - The for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. The syntax of a for loop in MATLAB is − for index = values <program statements> ... end values has one of the following forms − initval:endval increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval. initval:step:endval increments index by the value step on each iteration, or decrements when step is negative. valArray creates a column vector index from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum of n times, where n is the number of columns of valArray, given by numel(valArray, 1, :). The input valArray can be of any MATLAB data type, including a string, cell array, or struct. Create a script file and type the following code − for a = 10:20 fprintf('value of a: %d\n', a); end When you run the file, it displays the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 value of a: 20 Create a script file and type the following code − for a = 1.0: -0.1: 0.0 disp(a) end When you run the file, it displays the following result − 1 0.90000 0.80000 0.70000 0.60000 0.50000 0.40000 0.30000 0.20000 0.10000 0 Create a script file and type the following code − for a = [24,18,17,23,28] disp(a) end When you run the file, it displays the following result − 24 18 17 23 28 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2280, "s": 2141, "text": "A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times." }, { "code": null, "e": 2320, "s": 2280, "text": "The syntax of a for loop in MATLAB is −" }, { "code": null, "e": 2384, "s": 2320, "text": "for index = values\n <program statements>\n ...\nend\n" }, { "code": null, "e": 2424, "s": 2384, "text": "values has one of the following forms −" }, { "code": null, "e": 2439, "s": 2424, "text": "initval:endval" }, { "code": null, "e": 2578, "s": 2439, "text": "increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval." }, { "code": null, "e": 2598, "s": 2578, "text": "initval:step:endval" }, { "code": null, "e": 2689, "s": 2598, "text": "increments index by the value step on each iteration, or decrements when step is negative." }, { "code": null, "e": 2698, "s": 2689, "text": "valArray" }, { "code": null, "e": 3065, "s": 2698, "text": "creates a column vector index from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum of n times, where n is the number of columns of valArray, given by numel(valArray, 1, :). The input valArray can be of any MATLAB data type, including a string, cell array, or struct." }, { "code": null, "e": 3116, "s": 3065, "text": "Create a script file and type the following code −" }, { "code": null, "e": 3170, "s": 3116, "text": "for a = 10:20 \n fprintf('value of a: %d\\n', a);\nend" }, { "code": null, "e": 3228, "s": 3170, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 3394, "s": 3228, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\nvalue of a: 20\n" }, { "code": null, "e": 3445, "s": 3394, "text": "Create a script file and type the following code −" }, { "code": null, "e": 3483, "s": 3445, "text": "for a = 1.0: -0.1: 0.0\n disp(a)\nend" }, { "code": null, "e": 3541, "s": 3483, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 3618, "s": 3541, "text": "1\n0.90000\n0.80000\n0.70000\n0.60000\n0.50000\n0.40000\n0.30000\n0.20000\n0.10000\n0\n" }, { "code": null, "e": 3669, "s": 3618, "text": "Create a script file and type the following code −" }, { "code": null, "e": 3709, "s": 3669, "text": "for a = [24,18,17,23,28]\n disp(a)\nend" }, { "code": null, "e": 3767, "s": 3709, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 3787, "s": 3767, "text": "24\n\n18\n\n17\n\n23\n\n28\n" }, { "code": null, "e": 3820, "s": 3787, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 3833, "s": 3820, "text": " Nouman Azam" }, { "code": null, "e": 3868, "s": 3833, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 3881, "s": 3868, "text": " Nouman Azam" }, { "code": null, "e": 3914, "s": 3881, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 3923, "s": 3914, "text": " Sanjeev" }, { "code": null, "e": 3956, "s": 3923, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 3972, "s": 3956, "text": " TELCOMA Global" }, { "code": null, "e": 4005, "s": 3972, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 4021, "s": 4005, "text": " TELCOMA Global" }, { "code": null, "e": 4054, "s": 4021, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 4071, "s": 4054, "text": " Phinite Academy" }, { "code": null, "e": 4078, "s": 4071, "text": " Print" }, { "code": null, "e": 4089, "s": 4078, "text": " Add Notes" } ]
Git - Perform Changes
Jerry clones the repository and decides to implement basic string operations. So he creates string.c file. After adding the contents, string.c will look like as follows − #include <stdio.h> int my_strlen(char *s) { char *p = s; while (*p) ++p; return (p - s); } int main(void) { int i; char *s[] = { "Git tutorials", "Tutorials Point" }; for (i = 0; i < 2; ++i) printf("string lenght of %s = %d\n", s[i], my_strlen(s[i])); return 0; } He compiled and tested his code and everything is working fine. Now, he can safely add these changes to the repository. Git add operation adds file to the staging area. [jerry@CentOS project]$ git status -s ?? string ?? string.c [jerry@CentOS project]$ git add string.c Git is showing a question mark before file names. Obviously, these files are not a part of Git, and that is why Git does not know what to do with these files. That is why, Git is showing a question mark before file names. Jerry has added the file to the stash area, git status command will show files present in the staging area. [jerry@CentOS project]$ git status -s A string.c ?? string To commit the changes, he used the git commit command followed by –m option. If we omit –m option. Git will open a text editor where we can write multiline commit message. [jerry@CentOS project]$ git commit -m 'Implemented my_strlen function' The above command will produce the following result − [master cbe1249] Implemented my_strlen function 1 files changed, 24 insertions(+), 0 deletions(-) create mode 100644 string.c After commit to view log details, he runs the git log command. It will display the information of all the commits with their commit ID, commit author, commit date and SHA-1 hash of commit. [jerry@CentOS project]$ git log The above command will produce the following result − commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277 Author: Jerry Mouse <[email protected]> Date: Wed Sep 11 08:05:26 2013 +0530 Implemented my_strlen function commit 19ae20683fc460db7d127cf201a1429523b0e319 Author: Tom Cat <[email protected]> Date: Wed Sep 11 07:32:56 2013 +0530 Initial commit 251 Lectures 35.5 hours Gowthami Swarna 23 Lectures 2 hours Asif Hussain 15 Lectures 1.5 hours Abhilash Nelson 125 Lectures 9 hours John Shea 13 Lectures 2.5 hours Raghu Pandey 13 Lectures 3 hours Sebastian Sulinski Print Add Notes Bookmark this page
[ { "code": null, "e": 2216, "s": 2045, "text": "Jerry clones the repository and decides to implement basic string operations. So he creates string.c file. After adding the contents, string.c will look like as follows −" }, { "code": null, "e": 2542, "s": 2216, "text": "#include <stdio.h>\n\nint my_strlen(char *s)\n{\n char *p = s;\n\n while (*p)\n ++p;\n\n return (p - s);\n}\n\nint main(void)\n{\n int i;\n char *s[] = \n {\n \"Git tutorials\",\n \"Tutorials Point\"\n };\n\n for (i = 0; i < 2; ++i)\n \n printf(\"string lenght of %s = %d\\n\", s[i], my_strlen(s[i]));\n\n return 0;\n}" }, { "code": null, "e": 2662, "s": 2542, "text": "He compiled and tested his code and everything is working fine. Now, he can safely add these changes to the repository." }, { "code": null, "e": 2711, "s": 2662, "text": "Git add operation adds file to the staging area." }, { "code": null, "e": 2814, "s": 2711, "text": "[jerry@CentOS project]$ git status -s\n?? string\n?? string.c\n\n[jerry@CentOS project]$ git add string.c\n" }, { "code": null, "e": 3036, "s": 2814, "text": "Git is showing a question mark before file names. Obviously, these files are not a part of Git, and that is why Git does not know what to do with these files. That is why, Git is showing a question mark before file names." }, { "code": null, "e": 3144, "s": 3036, "text": "Jerry has added the file to the stash area, git status command will show files present in the staging area." }, { "code": null, "e": 3204, "s": 3144, "text": "[jerry@CentOS project]$ git status -s\nA string.c\n?? string\n" }, { "code": null, "e": 3376, "s": 3204, "text": "To commit the changes, he used the git commit command followed by –m option. If we omit –m option. Git will open a text editor where we can write multiline commit message." }, { "code": null, "e": 3448, "s": 3376, "text": "[jerry@CentOS project]$ git commit -m 'Implemented my_strlen function'\n" }, { "code": null, "e": 3502, "s": 3448, "text": "The above command will produce the following result −" }, { "code": null, "e": 3629, "s": 3502, "text": "[master cbe1249] Implemented my_strlen function\n1 files changed, 24 insertions(+), 0 deletions(-)\ncreate mode 100644 string.c\n" }, { "code": null, "e": 3818, "s": 3629, "text": "After commit to view log details, he runs the git log command. It will display the information of all the commits with their commit ID, commit author, commit date and SHA-1 hash of commit." }, { "code": null, "e": 3851, "s": 3818, "text": "[jerry@CentOS project]$ git log\n" }, { "code": null, "e": 3905, "s": 3851, "text": "The above command will produce the following result −" }, { "code": null, "e": 4214, "s": 3905, "text": "commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277\nAuthor: Jerry Mouse <[email protected]>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nImplemented my_strlen function\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <[email protected]>\nDate: Wed Sep 11 07:32:56 2013 +0530\n\nInitial commit\n" }, { "code": null, "e": 4251, "s": 4214, "text": "\n 251 Lectures \n 35.5 hours \n" }, { "code": null, "e": 4268, "s": 4251, "text": " Gowthami Swarna" }, { "code": null, "e": 4301, "s": 4268, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 4315, "s": 4301, "text": " Asif Hussain" }, { "code": null, "e": 4350, "s": 4315, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4367, "s": 4350, "text": " Abhilash Nelson" }, { "code": null, "e": 4401, "s": 4367, "text": "\n 125 Lectures \n 9 hours \n" }, { "code": null, "e": 4412, "s": 4401, "text": " John Shea" }, { "code": null, "e": 4447, "s": 4412, "text": "\n 13 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4461, "s": 4447, "text": " Raghu Pandey" }, { "code": null, "e": 4494, "s": 4461, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 4514, "s": 4494, "text": " Sebastian Sulinski" }, { "code": null, "e": 4521, "s": 4514, "text": " Print" }, { "code": null, "e": 4532, "s": 4521, "text": " Add Notes" } ]
ExpressJS - Middleware
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc. Here is a simple example of a middleware function in action − var express = require('express'); var app = express(); //Simple request time logger app.use(function(req, res, next){ console.log("A new request received at " + Date.now()); //This function call is very important. It tells that more processing is //required for the current request and is in the next middleware function route handler. next(); }); app.listen(3000); The above middleware is called for every request on the server. So after every request, we will get the following message in the console − A new request received at 1467267512545 To restrict it to a specific route (and all its subroutes), provide that route as the first argument of app.use(). For Example, var express = require('express'); var app = express(); //Middleware function to log request protocol app.use('/things', function(req, res, next){ console.log("A request for things received at " + Date.now()); next(); }); // Route handler that sends the response app.get('/things', function(req, res){ res.send('Things'); }); app.listen(3000); Now whenever you request any subroute of '/things', only then it will log the time. One of the most important things about middleware in Express is the order in which they are written/included in your file; the order in which they are executed, given that the route matches also needs to be considered. For example, in the following code snippet, the first function executes first, then the route handler and then the end function. This example summarizes how to use middleware before and after route handler; also how a route handler can be used as a middleware itself. var express = require('express'); var app = express(); //First middleware before response is sent app.use(function(req, res, next){ console.log("Start"); next(); }); //Route handler app.get('/', function(req, res, next){ res.send("Middle"); next(); }); app.use('/', function(req, res){ console.log('End'); }); app.listen(3000); When we visit '/' after running this code, we receive the response as Middle and on our console − Start End The following diagram summarizes what we have learnt about middleware − Now that we have covered how to create our own middleware, let us discuss some of the most commonly used community created middleware. A list of Third party middleware for Express is available here. Following are some of the most commonly used middleware; we will also learn how to use/mount these − This is used to parse the body of requests which have payloads attached to them. To mount body parser, we need to install it using npm install --save body-parser and to mount it, include the following lines in your index.js − var bodyParser = require('body-parser'); //To parse URL encoded data app.use(bodyParser.urlencoded({ extended: false })) //To parse json data app.use(bodyParser.json()) To view all available options for body-parser, visit its github page. It parses Cookie header and populate req.cookies with an object keyed by cookie names. To mount cookie parser, we need to install it using npm install --save cookie-parser and to mount it, include the following lines in your index.js − var cookieParser = require('cookie-parser'); app.use(cookieParser()) It creates a session middleware with the given options. We will discuss its usage in the Sessions section. We have many other third party middleware in ExpressJS. However, we have discussed only a few important ones here. 16 Lectures 1 hours Anadi Sharma Print Add Notes Bookmark this page
[ { "code": null, "e": 2371, "s": 2061, "text": "Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc." }, { "code": null, "e": 2433, "s": 2371, "text": "Here is a simple example of a middleware function in action −" }, { "code": null, "e": 2820, "s": 2433, "text": "var express = require('express');\nvar app = express();\n\n//Simple request time logger\napp.use(function(req, res, next){\n console.log(\"A new request received at \" + Date.now());\n \n //This function call is very important. It tells that more processing is\n //required for the current request and is in the next middleware\n function route handler.\n next();\n});\n\napp.listen(3000);" }, { "code": null, "e": 2959, "s": 2820, "text": "The above middleware is called for every request on the server. So after every request, we will get the following message in the console −" }, { "code": null, "e": 3000, "s": 2959, "text": "A new request received at 1467267512545\n" }, { "code": null, "e": 3128, "s": 3000, "text": "To restrict it to a specific route (and all its subroutes), provide that route as the first argument of app.use(). For Example," }, { "code": null, "e": 3483, "s": 3128, "text": "var express = require('express');\nvar app = express();\n\n//Middleware function to log request protocol\napp.use('/things', function(req, res, next){\n console.log(\"A request for things received at \" + Date.now());\n next();\n});\n\n// Route handler that sends the response\napp.get('/things', function(req, res){\n res.send('Things');\n});\n\napp.listen(3000);" }, { "code": null, "e": 3567, "s": 3483, "text": "Now whenever you request any subroute of '/things', only then it will log the time." }, { "code": null, "e": 3786, "s": 3567, "text": "One of the most important things about middleware in Express is the order in which they are written/included in your file; the order in which they are executed, given that the route matches also needs to be considered." }, { "code": null, "e": 4054, "s": 3786, "text": "For example, in the following code snippet, the first function executes first, then the route handler and then the end function. This example summarizes how to use middleware before and after route handler; also how a route handler can be used as a middleware itself." }, { "code": null, "e": 4401, "s": 4054, "text": "var express = require('express');\nvar app = express();\n\n//First middleware before response is sent\napp.use(function(req, res, next){\n console.log(\"Start\");\n next();\n});\n\n//Route handler\napp.get('/', function(req, res, next){\n res.send(\"Middle\");\n next();\n});\n\napp.use('/', function(req, res){\n console.log('End');\n});\n\napp.listen(3000);" }, { "code": null, "e": 4499, "s": 4401, "text": "When we visit '/' after running this code, we receive the response as Middle and on our console −" }, { "code": null, "e": 4510, "s": 4499, "text": "Start\nEnd\n" }, { "code": null, "e": 4582, "s": 4510, "text": "The following diagram summarizes what we have learnt about middleware −" }, { "code": null, "e": 4717, "s": 4582, "text": "Now that we have covered how to create our own middleware, let us discuss some of the most commonly used community created middleware." }, { "code": null, "e": 4882, "s": 4717, "text": "A list of Third party middleware for Express is available here. Following are some of the most commonly used middleware; we will also learn how to use/mount these −" }, { "code": null, "e": 5108, "s": 4882, "text": "This is used to parse the body of requests which have payloads attached to them. To mount body parser, we need to install it using npm install --save body-parser and to mount it, include the following lines in your index.js −" }, { "code": null, "e": 5279, "s": 5108, "text": "var bodyParser = require('body-parser');\n\n//To parse URL encoded data\napp.use(bodyParser.urlencoded({ extended: false }))\n\n//To parse json data\napp.use(bodyParser.json())" }, { "code": null, "e": 5349, "s": 5279, "text": "To view all available options for body-parser, visit its github page." }, { "code": null, "e": 5585, "s": 5349, "text": "It parses Cookie header and populate req.cookies with an object keyed by cookie names. To mount cookie parser, we need to install it using npm install --save cookie-parser and to mount it, include the following lines in your index.js −" }, { "code": null, "e": 5654, "s": 5585, "text": "var cookieParser = require('cookie-parser');\napp.use(cookieParser())" }, { "code": null, "e": 5761, "s": 5654, "text": "It creates a session middleware with the given options. We will discuss its usage in the Sessions section." }, { "code": null, "e": 5876, "s": 5761, "text": "We have many other third party middleware in ExpressJS. However, we have discussed only a few important ones here." }, { "code": null, "e": 5909, "s": 5876, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5923, "s": 5909, "text": " Anadi Sharma" }, { "code": null, "e": 5930, "s": 5923, "text": " Print" }, { "code": null, "e": 5941, "s": 5930, "text": " Add Notes" } ]
How to add line breaks to an HTML textarea? - GeeksforGeeks
28 Jan, 2020 Way of implementing line breaks differ from one platform to another. The following approach takes input text from HTML Textarea and adds line breaks using JavaScript. Approach:This task can be achieved by using some predefined array and string functions provided by JavaScript. In the following code, the input from the textarea is processed by JavaScript on the click of the submit button to produce a required output with line breaks. Functions Used:split(): is a predefined JavaScript function that splits a string into an array using a parameter.join(): is a predefined JavaScript function that joins an array to convert it into a string using provided parameters. Example: <!DOCTYPE html><html> <head> <script type="text/javascript"> function divide() { var txt; txt = document.getElementById('a').value; var text = txt.split("."); var str = text.join('.</br>'); document.write(str); } </script> <title></title></head> <body> <form> ENTER TEXT: <br> <textarea rows="20" cols="50" name="txt" id="a"> </textarea> <br> <br> <input type="submit" name="submit" value="submit" onclick="divide()" /> </form></body> </html> Output:Code without line break: Geeks for geeks. Geeks for geeks. Geeks for geeks. Geeks for geeks. Code with line break: Geeks for geeks. Geeks for geeks. Geeks for geeks. Geeks for geeks. JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React Difference between var, let and const keywords in JavaScript How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux 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": 24992, "s": 24964, "text": "\n28 Jan, 2020" }, { "code": null, "e": 25159, "s": 24992, "text": "Way of implementing line breaks differ from one platform to another. The following approach takes input text from HTML Textarea and adds line breaks using JavaScript." }, { "code": null, "e": 25429, "s": 25159, "text": "Approach:This task can be achieved by using some predefined array and string functions provided by JavaScript. In the following code, the input from the textarea is processed by JavaScript on the click of the submit button to produce a required output with line breaks." }, { "code": null, "e": 25661, "s": 25429, "text": "Functions Used:split(): is a predefined JavaScript function that splits a string into an array using a parameter.join(): is a predefined JavaScript function that joins an array to convert it into a string using provided parameters." }, { "code": null, "e": 25670, "s": 25661, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\"> function divide() { var txt; txt = document.getElementById('a').value; var text = txt.split(\".\"); var str = text.join('.</br>'); document.write(str); } </script> <title></title></head> <body> <form> ENTER TEXT: <br> <textarea rows=\"20\" cols=\"50\" name=\"txt\" id=\"a\"> </textarea> <br> <br> <input type=\"submit\" name=\"submit\" value=\"submit\" onclick=\"divide()\" /> </form></body> </html>", "e": 26347, "s": 25670, "text": null }, { "code": null, "e": 26379, "s": 26347, "text": "Output:Code without line break:" }, { "code": null, "e": 26447, "s": 26379, "text": "Geeks for geeks. Geeks for geeks. Geeks for geeks. Geeks for geeks." }, { "code": null, "e": 26469, "s": 26447, "text": "Code with line break:" }, { "code": null, "e": 26540, "s": 26469, "text": "Geeks for geeks. \nGeeks for geeks. \nGeeks for geeks. \nGeeks for geeks." }, { "code": null, "e": 26556, "s": 26540, "text": "JavaScript-Misc" }, { "code": null, "e": 26563, "s": 26556, "text": "Picked" }, { "code": null, "e": 26574, "s": 26563, "text": "JavaScript" }, { "code": null, "e": 26591, "s": 26574, "text": "Web Technologies" }, { "code": null, "e": 26689, "s": 26591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26698, "s": 26689, "text": "Comments" }, { "code": null, "e": 26711, "s": 26698, "text": "Old Comments" }, { "code": null, "e": 26756, "s": 26711, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26828, "s": 26756, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26889, "s": 26828, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26941, "s": 26889, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 26987, "s": 26941, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27029, "s": 26987, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27062, "s": 27029, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27124, "s": 27062, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27167, "s": 27124, "text": "How to fetch data from an API in ReactJS ?" } ]
A Gentle Introduction To Understand Airflow Executor | by Chengzhi Zhao | Towards Data Science
Apache Airflow is a prominent open-source python framework for scheduling tasks. There are many new concepts in the Airflow ecosystem; one of those concepts you cannot skip is Airflow Executor, which are the “working stations” for all the scheduled tasks. Airflow is generally user-friendly to the end-users, and getting a good understanding of the Airflow Executor is critical to personal use, as well as the production Airflow environment. In this article, we are going to discuss details about what’s Airflow executor, compare different types of executors to help you make a decision. There are many Airflow executors to choose, let’s put those choices aside, and first focus on what do the Airflow executors do in Airflow ecosystem. The discipline “Executor,” fittingly, is a mechanism that gets tasks executed. The worker is the node or processor which runs the actual tasks. The Airflow scheduler won’t run any tasks but handle tasks over to the Executor. The Executor acts as a middle man to handle resource utilization and how to distribute work best. Although an Airflow job is organized at the DAG level, the execution phase of a job is more granular, and the Executor runs at the task level. As the images are shown below, if a DAG ends up with six tasks, the Airflow scheduler will assign each task separately to the Executor. Whether those tasks finished in parallel or sequentially, it is determined by the executor type. As for now, Airflow (version 1.10.10) is a single scheduler system. In this case, all of the tasks are scheduled by only one scheduler. The scheduler controls when tasks will be sent to the Executor and monitor the state of tasks from executors. The life cycle of a task from the scheduler to Executor includes the following steps: Before the scheduler sends the command on which task the Executor is going to run, depending on the types of executors, the resource of executors themself keeps idle or unavailable.Once the scheduled time arrives, the Airflow scheduler sends the command to the Executor.After received signals from the scheduler, the Executor starts allocating resources and put tasks into the queue. When work is available, it will pick up the tasks from the queue to execute it. Meanwhile, the scheduler is poking the tasks every once a while (called heartbeat) to get the current state of the task, then update its state in backend DB.Once the tasks finished, and the scheduler received the Completed state from the Executor, the resource allocated for running the task got clean up. Before the scheduler sends the command on which task the Executor is going to run, depending on the types of executors, the resource of executors themself keeps idle or unavailable. Once the scheduled time arrives, the Airflow scheduler sends the command to the Executor. After received signals from the scheduler, the Executor starts allocating resources and put tasks into the queue. When work is available, it will pick up the tasks from the queue to execute it. Meanwhile, the scheduler is poking the tasks every once a while (called heartbeat) to get the current state of the task, then update its state in backend DB. Once the tasks finished, and the scheduler received the Completed state from the Executor, the resource allocated for running the task got clean up. Majority types of the Airflow executor instrument tasks to run in a distributed manner, those tasks are running on either multi-processing or multiple worker nodes. An Airflow production environment usually has hundreds of DAGs, which include thousands of tasks to run. With the capability to run various tasks in parallel at such a large scale, the Airflow executor shines on the intensive workload. One of the reasons you have various types of executors is you have the option to choose based on your requirement and infrastructure. Airflow provides executors “toolkit,” different kinds of executors give the flexibility to have Airflow integrate smoothly with your environment. Airflow is extensible, which supports various executors. Initially, Airflow only has SequentialExecutor, LocalExecutor, CeleryExecutor, and MesosExecutor available. In the last two years, since Airflow 1.9.0, Airflow gets more attention, and more executors have been contributed to the community, those executors include DaskExecutor, KubernetesExecutor, DebugExecutor. The difference between the Executors is the mechanism on where the executors are running the tasks. In my opinion, not all executors are equally to be considered, some you may even want to skip unless you have specific reasons you have to use them. Below is the description of each Executor and what should be the consideration when you tend to choose one of them. SequentialExecutor is the default executor out of the box. As the name suggested, tasks will get executed sequentially. Even you have a branch operator, and the tasks are still going to be executed one by one in order of ’branch_a’, ‘branch_b’, ‘branch_c’, ‘branch_d’ LocalExecutor is excellent for testing Airflow multiple jobs in parallel, performing tasks for a small scale production environment. LocalExecutor runs the task on the same node as the Airflow scheduler but different processors. There are other executors which use this type while distributing the actual work; for example, KubernetesExecutor would use LocalExecutor within each pod to run the task. CeleryExecutor is the most mature option for Airflow as most of the early Airflow adoption is using CeleryExecutor. It requires infrastructure support — Celery and Celery’s backend (Redis or RabbitMQ) additionally. However, you’d have much better help with this option from the Airflow community since a lot of companies are running under this option. MesosExecutor is one of the early community contributions. However, Since Kubernetes is adopted widely than Mesos, the Airflow Community is also discussing retiring MesosExecutor. Unless your company is running Mesos, and you don’t see migration to Kubernetes in the next few years, and you want to use Mesos to manage your Airflow executor resource, you might want to choose this option. Otherwise, you might want to avoid choosing MesosExecutor. Dask.org inspires DaskExecutor. There is some discussion about removing DaskExecutor as well due to lack of usage, which DaskExecutor failed on Airflow master for months, but no one noticed. I personally like Dask; it’s unfortunate for less usage with Airflow and Dask. Due to less usage and support, you might want to avoid choosing DaskExecutor, unfortunately. KubernetesExecutor was introduced in version 1.10.0 and contributed by Bloomberg. This contribution sets a milestone for Airflow to integrate with the Kubernetes ecosystem. Although the first few minor version is buggy, the recent ones are more stable. If your company has Kubernetes widely adopted, KubernetesExecutor might be the best choice for the Airflow executor. Another beautiful thing about KubernetesExecutor is you can prepare different docker images for your tasks, and it gives you more flexibility here. DebugExecutor was introduced in 1.10.8. It might not be classified as an executor; the purpose of this DebugExecutor is to run with IDE. It is similar to SequentialExecutor to run one task at a time, and it supports to work with sensors. To summary, CeleryExecutor and KubernetesExecutor would be an excellent selection for your production environment. LocalExecutor is also a preference to be considered for the production environment. If you have a light workload or majority of the tasks are running in cloud services like AWS or Azure service, Airflow Executor acts as the middle man to talk to different services without actually running them, LocalExecutor is also viable choice to consider. SequentialExecutor and DebugExecutor are for local testing purposes. You probably would skip them on production. MesosExecutor and DaskExecutor you might want to avoid them due to ambivalence about their future road map in the Airflow ecosystem. Most of the configurations on the Airflow Executor are controlled by airflow.cfg file. Different functional sections organize the file in brackets. For executor selection, you’d see under the core section, SequentialExecutor is chosen as the default. It allows you to run Airflow without setting up too many dependencies. SequentialExecutor can work directly with SQLite, which should be installed with the Python installation. As we discussed above, you can choose different types of executors, but each requires additional setup in the AirflowAirflow.cfg file. [core]executor = SequentialExecutor The LocalExecutor is also easy to set up, and it does require the metadata database to be MySQL or PostgreSQL instead of SQLite. Once the LocalExecutor is set up, 90% of the functionality of the Airflow executor is unveiled. The other 10% of functionality the Executor is to run Airflow in a distributed manner. CeleryExecutor has its configuration section — [celery] . There are two main components: Celery and Celery backend. Celery is an asynchronous task queue. With Celery, Airflow can scale its tasks to multiple workers to finish the jobs faster. More setup can be found at Airflow Celery Page KubernetesExecutor is the beloved child in Airflow due to the popularity of Kubernetes. If you have Kubernetes in your environment, setting up KubernetesExecutor in Airflow won’t be too much work, I have covered the basic set up in my previous article: Explore Airflow KubernetesExecutor on AWS and kops It is a critical step for Airflow infrastructure to set up proper Executor. If you want Airflow to handle not only the scheduling part but also run tasks on your worker node, Airflow executor provides more extra potential here with its distributed capability. I hope this article can give you some basic ideas on Airflow Executor. Cheers!
[ { "code": null, "e": 760, "s": 172, "text": "Apache Airflow is a prominent open-source python framework for scheduling tasks. There are many new concepts in the Airflow ecosystem; one of those concepts you cannot skip is Airflow Executor, which are the “working stations” for all the scheduled tasks. Airflow is generally user-friendly to the end-users, and getting a good understanding of the Airflow Executor is critical to personal use, as well as the production Airflow environment. In this article, we are going to discuss details about what’s Airflow executor, compare different types of executors to help you make a decision." }, { "code": null, "e": 1232, "s": 760, "text": "There are many Airflow executors to choose, let’s put those choices aside, and first focus on what do the Airflow executors do in Airflow ecosystem. The discipline “Executor,” fittingly, is a mechanism that gets tasks executed. The worker is the node or processor which runs the actual tasks. The Airflow scheduler won’t run any tasks but handle tasks over to the Executor. The Executor acts as a middle man to handle resource utilization and how to distribute work best." }, { "code": null, "e": 1608, "s": 1232, "text": "Although an Airflow job is organized at the DAG level, the execution phase of a job is more granular, and the Executor runs at the task level. As the images are shown below, if a DAG ends up with six tasks, the Airflow scheduler will assign each task separately to the Executor. Whether those tasks finished in parallel or sequentially, it is determined by the executor type." }, { "code": null, "e": 1854, "s": 1608, "text": "As for now, Airflow (version 1.10.10) is a single scheduler system. In this case, all of the tasks are scheduled by only one scheduler. The scheduler controls when tasks will be sent to the Executor and monitor the state of tasks from executors." }, { "code": null, "e": 1940, "s": 1854, "text": "The life cycle of a task from the scheduler to Executor includes the following steps:" }, { "code": null, "e": 2710, "s": 1940, "text": "Before the scheduler sends the command on which task the Executor is going to run, depending on the types of executors, the resource of executors themself keeps idle or unavailable.Once the scheduled time arrives, the Airflow scheduler sends the command to the Executor.After received signals from the scheduler, the Executor starts allocating resources and put tasks into the queue. When work is available, it will pick up the tasks from the queue to execute it. Meanwhile, the scheduler is poking the tasks every once a while (called heartbeat) to get the current state of the task, then update its state in backend DB.Once the tasks finished, and the scheduler received the Completed state from the Executor, the resource allocated for running the task got clean up." }, { "code": null, "e": 2892, "s": 2710, "text": "Before the scheduler sends the command on which task the Executor is going to run, depending on the types of executors, the resource of executors themself keeps idle or unavailable." }, { "code": null, "e": 2982, "s": 2892, "text": "Once the scheduled time arrives, the Airflow scheduler sends the command to the Executor." }, { "code": null, "e": 3334, "s": 2982, "text": "After received signals from the scheduler, the Executor starts allocating resources and put tasks into the queue. When work is available, it will pick up the tasks from the queue to execute it. Meanwhile, the scheduler is poking the tasks every once a while (called heartbeat) to get the current state of the task, then update its state in backend DB." }, { "code": null, "e": 3483, "s": 3334, "text": "Once the tasks finished, and the scheduler received the Completed state from the Executor, the resource allocated for running the task got clean up." }, { "code": null, "e": 3884, "s": 3483, "text": "Majority types of the Airflow executor instrument tasks to run in a distributed manner, those tasks are running on either multi-processing or multiple worker nodes. An Airflow production environment usually has hundreds of DAGs, which include thousands of tasks to run. With the capability to run various tasks in parallel at such a large scale, the Airflow executor shines on the intensive workload." }, { "code": null, "e": 4164, "s": 3884, "text": "One of the reasons you have various types of executors is you have the option to choose based on your requirement and infrastructure. Airflow provides executors “toolkit,” different kinds of executors give the flexibility to have Airflow integrate smoothly with your environment." }, { "code": null, "e": 4534, "s": 4164, "text": "Airflow is extensible, which supports various executors. Initially, Airflow only has SequentialExecutor, LocalExecutor, CeleryExecutor, and MesosExecutor available. In the last two years, since Airflow 1.9.0, Airflow gets more attention, and more executors have been contributed to the community, those executors include DaskExecutor, KubernetesExecutor, DebugExecutor." }, { "code": null, "e": 4899, "s": 4534, "text": "The difference between the Executors is the mechanism on where the executors are running the tasks. In my opinion, not all executors are equally to be considered, some you may even want to skip unless you have specific reasons you have to use them. Below is the description of each Executor and what should be the consideration when you tend to choose one of them." }, { "code": null, "e": 5167, "s": 4899, "text": "SequentialExecutor is the default executor out of the box. As the name suggested, tasks will get executed sequentially. Even you have a branch operator, and the tasks are still going to be executed one by one in order of ’branch_a’, ‘branch_b’, ‘branch_c’, ‘branch_d’" }, { "code": null, "e": 5567, "s": 5167, "text": "LocalExecutor is excellent for testing Airflow multiple jobs in parallel, performing tasks for a small scale production environment. LocalExecutor runs the task on the same node as the Airflow scheduler but different processors. There are other executors which use this type while distributing the actual work; for example, KubernetesExecutor would use LocalExecutor within each pod to run the task." }, { "code": null, "e": 5919, "s": 5567, "text": "CeleryExecutor is the most mature option for Airflow as most of the early Airflow adoption is using CeleryExecutor. It requires infrastructure support — Celery and Celery’s backend (Redis or RabbitMQ) additionally. However, you’d have much better help with this option from the Airflow community since a lot of companies are running under this option." }, { "code": null, "e": 6367, "s": 5919, "text": "MesosExecutor is one of the early community contributions. However, Since Kubernetes is adopted widely than Mesos, the Airflow Community is also discussing retiring MesosExecutor. Unless your company is running Mesos, and you don’t see migration to Kubernetes in the next few years, and you want to use Mesos to manage your Airflow executor resource, you might want to choose this option. Otherwise, you might want to avoid choosing MesosExecutor." }, { "code": null, "e": 6730, "s": 6367, "text": "Dask.org inspires DaskExecutor. There is some discussion about removing DaskExecutor as well due to lack of usage, which DaskExecutor failed on Airflow master for months, but no one noticed. I personally like Dask; it’s unfortunate for less usage with Airflow and Dask. Due to less usage and support, you might want to avoid choosing DaskExecutor, unfortunately." }, { "code": null, "e": 7248, "s": 6730, "text": "KubernetesExecutor was introduced in version 1.10.0 and contributed by Bloomberg. This contribution sets a milestone for Airflow to integrate with the Kubernetes ecosystem. Although the first few minor version is buggy, the recent ones are more stable. If your company has Kubernetes widely adopted, KubernetesExecutor might be the best choice for the Airflow executor. Another beautiful thing about KubernetesExecutor is you can prepare different docker images for your tasks, and it gives you more flexibility here." }, { "code": null, "e": 7486, "s": 7248, "text": "DebugExecutor was introduced in 1.10.8. It might not be classified as an executor; the purpose of this DebugExecutor is to run with IDE. It is similar to SequentialExecutor to run one task at a time, and it supports to work with sensors." }, { "code": null, "e": 8192, "s": 7486, "text": "To summary, CeleryExecutor and KubernetesExecutor would be an excellent selection for your production environment. LocalExecutor is also a preference to be considered for the production environment. If you have a light workload or majority of the tasks are running in cloud services like AWS or Azure service, Airflow Executor acts as the middle man to talk to different services without actually running them, LocalExecutor is also viable choice to consider. SequentialExecutor and DebugExecutor are for local testing purposes. You probably would skip them on production. MesosExecutor and DaskExecutor you might want to avoid them due to ambivalence about their future road map in the Airflow ecosystem." }, { "code": null, "e": 8755, "s": 8192, "text": "Most of the configurations on the Airflow Executor are controlled by airflow.cfg file. Different functional sections organize the file in brackets. For executor selection, you’d see under the core section, SequentialExecutor is chosen as the default. It allows you to run Airflow without setting up too many dependencies. SequentialExecutor can work directly with SQLite, which should be installed with the Python installation. As we discussed above, you can choose different types of executors, but each requires additional setup in the AirflowAirflow.cfg file." }, { "code": null, "e": 8791, "s": 8755, "text": "[core]executor = SequentialExecutor" }, { "code": null, "e": 9103, "s": 8791, "text": "The LocalExecutor is also easy to set up, and it does require the metadata database to be MySQL or PostgreSQL instead of SQLite. Once the LocalExecutor is set up, 90% of the functionality of the Airflow executor is unveiled. The other 10% of functionality the Executor is to run Airflow in a distributed manner." }, { "code": null, "e": 9392, "s": 9103, "text": "CeleryExecutor has its configuration section — [celery] . There are two main components: Celery and Celery backend. Celery is an asynchronous task queue. With Celery, Airflow can scale its tasks to multiple workers to finish the jobs faster. More setup can be found at Airflow Celery Page" }, { "code": null, "e": 9696, "s": 9392, "text": "KubernetesExecutor is the beloved child in Airflow due to the popularity of Kubernetes. If you have Kubernetes in your environment, setting up KubernetesExecutor in Airflow won’t be too much work, I have covered the basic set up in my previous article: Explore Airflow KubernetesExecutor on AWS and kops" } ]
How to get formatted date and time in Python?
You can get formatted date and time using strftime function. It accepts a format string that you can use to get your desired output. Following are the directives supported by it. You can use these directives in the strftime function as follows − import datetime now = datetime.datetime.now() print("Current date and time: ") print(now.strftime('%Y-%m-%d %H:%M:%S')) print(now.strftime('%H:%M:%S on %A, %B the %dth, %Y')) This will give the output − 2017-12-29 12:19:13 12:19:13 on Friday, December the 29th, 2017
[ { "code": null, "e": 1241, "s": 1062, "text": "You can get formatted date and time using strftime function. It accepts a format string that you can use to get your desired output. Following are the directives supported by it." }, { "code": null, "e": 1308, "s": 1241, "text": "You can use these directives in the strftime function as follows −" }, { "code": null, "e": 1483, "s": 1308, "text": "import datetime\nnow = datetime.datetime.now()\nprint(\"Current date and time: \")\nprint(now.strftime('%Y-%m-%d %H:%M:%S'))\nprint(now.strftime('%H:%M:%S on %A, %B the %dth, %Y'))" }, { "code": null, "e": 1511, "s": 1483, "text": "This will give the output −" }, { "code": null, "e": 1575, "s": 1511, "text": "2017-12-29 12:19:13\n12:19:13 on Friday, December the 29th, 2017" } ]
How can we add/insert a JButton to JTable cell in Java?
A JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface. We can add or insert a JButton to JTable cell by customizing the code either in DefaultTableModel or AbstractTableModel and we can also customize the code by implementing TableCellRenderer interface and need to override getTableCellRendererComponent() method. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class JTableButtonTest extends JFrame { private JTable table; private JScrollPane scrollPane; public JTableButtonTest() { setTitle("JTableButton Test"); TableCellRenderer tableRenderer; table = new JTable(new JTableButtonModel()); tableRenderer = table.getDefaultRenderer(JButton.class); table.setDefaultRenderer(JButton.class, new JTableButtonRenderer(tableRenderer)); scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setSize(400, 300); setVisible(true); } public static void main(String[] args) { new JTableButtonTest(); } } class JTableButtonRenderer implements TableCellRenderer { private TableCellRenderer defaultRenderer; public JTableButtonRenderer(TableCellRenderer renderer) { defaultRenderer = renderer; } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if(value instanceof Component) return (Component)value; return defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } } class JTableButtonModel extends AbstractTableModel { private Object[][] rows = {{"Button1", new JButton("Button1")},{"Button2", new JButton("Button2")},{"Button3", new JButton("Button3")}, {"Button4", new JButton("Button4")}}; private String[] columns = {"Count", "Buttons"}; public String getColumnName(int column) { return columns[column]; } public int getRowCount() { return rows.length; } public int getColumnCount() { return columns.length; } public Object getValueAt(int row, int column) { return rows[row][column]; } public boolean isCellEditable(int row, int column) { return false; } public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } }
[ { "code": null, "e": 1596, "s": 1062, "text": "A JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface. We can add or insert a JButton to JTable cell by customizing the code either in DefaultTableModel or AbstractTableModel and we can also customize the code by implementing TableCellRenderer interface and need to override getTableCellRendererComponent() method." }, { "code": null, "e": 3708, "s": 1596, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\npublic class JTableButtonTest extends JFrame {\n private JTable table;\n private JScrollPane scrollPane;\n public JTableButtonTest() {\n setTitle(\"JTableButton Test\");\n TableCellRenderer tableRenderer;\n table = new JTable(new JTableButtonModel());\n tableRenderer = table.getDefaultRenderer(JButton.class);\n table.setDefaultRenderer(JButton.class, new JTableButtonRenderer(tableRenderer));\n scrollPane = new JScrollPane(table);\n add(scrollPane, BorderLayout.CENTER);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setSize(400, 300);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JTableButtonTest();\n }\n}\nclass JTableButtonRenderer implements TableCellRenderer {\n private TableCellRenderer defaultRenderer;\n public JTableButtonRenderer(TableCellRenderer renderer) {\n defaultRenderer = renderer;\n }\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if(value instanceof Component)\n return (Component)value;\n return defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n }\n}\nclass JTableButtonModel extends AbstractTableModel {\n private Object[][] rows = {{\"Button1\", new JButton(\"Button1\")},{\"Button2\", new JButton(\"Button2\")},{\"Button3\", new JButton(\"Button3\")}, {\"Button4\", new JButton(\"Button4\")}};\n private String[] columns = {\"Count\", \"Buttons\"};\n public String getColumnName(int column) {\n return columns[column];\n }\n public int getRowCount() {\n return rows.length;\n }\n public int getColumnCount() {\n return columns.length;\n }\n public Object getValueAt(int row, int column) {\n return rows[row][column];\n }\n public boolean isCellEditable(int row, int column) {\n return false;\n }\n public Class getColumnClass(int column) {\n return getValueAt(0, column).getClass();\n }\n}" } ]
HTML Iframes - GeeksforGeeks
17 Mar, 2022 In this article, we will know HTML Iframes, their implementation through the examples. The iframe in HTML stands for Inline Frame. The ” iframe ” tag defines a rectangular region within the document in which the browser can display a separate document, including scrollbars and borders. An inline frame is used to embed another document within the current HTML document. The HTML iframe name attribute is used to specify a reference for an <Iframe> element. The name attribute is also used as a reference to the elements in JavaScript. The iframe is basically used to show a webpage inside the current web page. The ‘ src ‘ attribute is used to specify the URL of the document that occupies the iframe. Syntax: <iframe src="URL" title="description"></iframe> Attributes value: It contains a single value URL that specifies the URL of the document that is embedded in the iframe. There are two types of URL links which are listed below: Absolute URL: It points to another webpage. Relative URL: It points to other files of the same web page. Example: This example illustrates the use of an iframe tag which is used to display a webpage inside the current web page. HTML <!DOCTYPE html><html> <head> <title>HTML iframe Tag</title></head> <body style="text-align: center"> <h1>GeeksforGeeks</h1> <h2>HTML iframe Tag</h2> <iframe src="https://ide.geeksforgeeks.org/index.php" height="200" width="400"> </iframe></body> </html> Output: HTML iframe tag Accepted Attribute: The following attributes can be used with the <iframe> tag in HTML. HTML <iframe> allow Attribute HTML <iframe> allowfullscreen attribute HTML <iframe> allowpaymentrequest attribute HTML <iframe> height attribute HTML <iframe> width attribute HTML <iframe> loading attribute HTML <iframe> scrolling attribute HTML <iframe> name attribute HTML <iframe> referrerpolicy attribute HTML <iframe> sandbox attribute HTML <iframe> src attribute HTML <iframe> srcdoc attribute Below few of the attributes examples are given: Height and Width: The height and width attributes are used to specify the size of the iframe. The attribute values are specified in pixels by default, but they can also be specified in percentages like ” 80% “. Example: This example describes the HTML iframe Tag by setting the width & height of the iframe. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML iframe Tag</h2> <p>Content goes here</p> <iframe src="https://ide.geeksforgeeks.org/tryit.php" height="300" width="400"> </iframe></body> </html> Output: Setting the width & height of HTML iframe Removing Border: By default, iframe has a border around it. To remove the border, we must use the style attribute and use the CSS border property. Example: This example describes the HTML iframe Tag where the border property is set as none. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML iframe Tag</h2> <p>Content goes here</p> <iframe src="https://ide.geeksforgeeks.org/tryit.php" height="300" width="400" style="border: none"> </iframe></body> </html> Output: HTML iframe with no border Border Style: Changing the size, style, and color of the Iframe’s border: Example: This example describes the HTML iframe Tag by specifying the border style. HTML <!DOCTYPE html><html> <body> <p>Content goes here</p> <iframe src="https://ide.geeksforgeeks.org/tryit.php" height="300" width="400" style="border: 4px solid orange"> </iframe></body> </html> Output: HTML iframe with border style Link: An iframe can be used as the target frame for a link. The target attribute of the link must refer to the name attribute of the iframe. Example: This example describes the HTML iframe Tag by using the target frame for a link. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML iframe Tag</h2> <p>Click the link text</p> <iframe height="300" width="350" src="https://media.geeksforgeeks.org/wp-content/uploads/20210910170539/gfg-221x300.png" name="iframe_a"> </iframe> <p><a href="https://ide.geeksforgeeks.org/tryit.php" target="iframe_a"> GeeksforGeeks IDE </a> </p> </body> </html> Output: HTML iframe with a link tag Supported Browsers: Google Chrome 93.0 Internet Explorer 11.0 Firefox 92.0 Microsoft Edge 93.0 Opera 78.0 Safari 14.1 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ghoshsuman0129 bhaskargeeksforgeeks HTML-Tags HTML Technical Scripter HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? Hide or show elements in HTML using display property REST API (Introduction) Types of CSS (Cascading Style Sheet) CSS to put icon inside an input element in a form
[ { "code": null, "e": 30322, "s": 30294, "text": "\n17 Mar, 2022" }, { "code": null, "e": 31025, "s": 30322, "text": "In this article, we will know HTML Iframes, their implementation through the examples. The iframe in HTML stands for Inline Frame. The ” iframe ” tag defines a rectangular region within the document in which the browser can display a separate document, including scrollbars and borders. An inline frame is used to embed another document within the current HTML document. The HTML iframe name attribute is used to specify a reference for an <Iframe> element. The name attribute is also used as a reference to the elements in JavaScript. The iframe is basically used to show a webpage inside the current web page. The ‘ src ‘ attribute is used to specify the URL of the document that occupies the iframe." }, { "code": null, "e": 31033, "s": 31025, "text": "Syntax:" }, { "code": null, "e": 31081, "s": 31033, "text": "<iframe src=\"URL\" title=\"description\"></iframe>" }, { "code": null, "e": 31258, "s": 31081, "text": "Attributes value: It contains a single value URL that specifies the URL of the document that is embedded in the iframe. There are two types of URL links which are listed below:" }, { "code": null, "e": 31302, "s": 31258, "text": "Absolute URL: It points to another webpage." }, { "code": null, "e": 31363, "s": 31302, "text": "Relative URL: It points to other files of the same web page." }, { "code": null, "e": 31486, "s": 31363, "text": "Example: This example illustrates the use of an iframe tag which is used to display a webpage inside the current web page." }, { "code": null, "e": 31491, "s": 31486, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML iframe Tag</title></head> <body style=\"text-align: center\"> <h1>GeeksforGeeks</h1> <h2>HTML iframe Tag</h2> <iframe src=\"https://ide.geeksforgeeks.org/index.php\" height=\"200\" width=\"400\"> </iframe></body> </html>", "e": 31797, "s": 31491, "text": null }, { "code": null, "e": 31805, "s": 31797, "text": "Output:" }, { "code": null, "e": 31821, "s": 31805, "text": "HTML iframe tag" }, { "code": null, "e": 31909, "s": 31821, "text": "Accepted Attribute: The following attributes can be used with the <iframe> tag in HTML." }, { "code": null, "e": 31939, "s": 31909, "text": "HTML <iframe> allow Attribute" }, { "code": null, "e": 31979, "s": 31939, "text": "HTML <iframe> allowfullscreen attribute" }, { "code": null, "e": 32023, "s": 31979, "text": "HTML <iframe> allowpaymentrequest attribute" }, { "code": null, "e": 32054, "s": 32023, "text": "HTML <iframe> height attribute" }, { "code": null, "e": 32084, "s": 32054, "text": "HTML <iframe> width attribute" }, { "code": null, "e": 32116, "s": 32084, "text": "HTML <iframe> loading attribute" }, { "code": null, "e": 32150, "s": 32116, "text": "HTML <iframe> scrolling attribute" }, { "code": null, "e": 32179, "s": 32150, "text": "HTML <iframe> name attribute" }, { "code": null, "e": 32218, "s": 32179, "text": "HTML <iframe> referrerpolicy attribute" }, { "code": null, "e": 32250, "s": 32218, "text": "HTML <iframe> sandbox attribute" }, { "code": null, "e": 32278, "s": 32250, "text": "HTML <iframe> src attribute" }, { "code": null, "e": 32309, "s": 32278, "text": "HTML <iframe> srcdoc attribute" }, { "code": null, "e": 32357, "s": 32309, "text": "Below few of the attributes examples are given:" }, { "code": null, "e": 32568, "s": 32357, "text": "Height and Width: The height and width attributes are used to specify the size of the iframe. The attribute values are specified in pixels by default, but they can also be specified in percentages like ” 80% “." }, { "code": null, "e": 32665, "s": 32568, "text": "Example: This example describes the HTML iframe Tag by setting the width & height of the iframe." }, { "code": null, "e": 32670, "s": 32665, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML iframe Tag</h2> <p>Content goes here</p> <iframe src=\"https://ide.geeksforgeeks.org/tryit.php\" height=\"300\" width=\"400\"> </iframe></body> </html>", "e": 32921, "s": 32670, "text": null }, { "code": null, "e": 32929, "s": 32921, "text": "Output:" }, { "code": null, "e": 32971, "s": 32929, "text": "Setting the width & height of HTML iframe" }, { "code": null, "e": 33118, "s": 32971, "text": "Removing Border: By default, iframe has a border around it. To remove the border, we must use the style attribute and use the CSS border property." }, { "code": null, "e": 33212, "s": 33118, "text": "Example: This example describes the HTML iframe Tag where the border property is set as none." }, { "code": null, "e": 33217, "s": 33212, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML iframe Tag</h2> <p>Content goes here</p> <iframe src=\"https://ide.geeksforgeeks.org/tryit.php\" height=\"300\" width=\"400\" style=\"border: none\"> </iframe></body> </html>", "e": 33501, "s": 33217, "text": null }, { "code": null, "e": 33509, "s": 33501, "text": "Output:" }, { "code": null, "e": 33536, "s": 33509, "text": "HTML iframe with no border" }, { "code": null, "e": 33610, "s": 33536, "text": "Border Style: Changing the size, style, and color of the Iframe’s border:" }, { "code": null, "e": 33694, "s": 33610, "text": "Example: This example describes the HTML iframe Tag by specifying the border style." }, { "code": null, "e": 33699, "s": 33694, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p>Content goes here</p> <iframe src=\"https://ide.geeksforgeeks.org/tryit.php\" height=\"300\" width=\"400\" style=\"border: 4px solid orange\"> </iframe></body> </html>", "e": 33939, "s": 33699, "text": null }, { "code": null, "e": 33947, "s": 33939, "text": "Output:" }, { "code": null, "e": 33977, "s": 33947, "text": "HTML iframe with border style" }, { "code": null, "e": 34118, "s": 33977, "text": "Link: An iframe can be used as the target frame for a link. The target attribute of the link must refer to the name attribute of the iframe." }, { "code": null, "e": 34208, "s": 34118, "text": "Example: This example describes the HTML iframe Tag by using the target frame for a link." }, { "code": null, "e": 34213, "s": 34208, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML iframe Tag</h2> <p>Click the link text</p> <iframe height=\"300\" width=\"350\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210910170539/gfg-221x300.png\" name=\"iframe_a\"> </iframe> <p><a href=\"https://ide.geeksforgeeks.org/tryit.php\" target=\"iframe_a\"> GeeksforGeeks IDE </a> </p> </body> </html>", "e": 34669, "s": 34213, "text": null }, { "code": null, "e": 34677, "s": 34669, "text": "Output:" }, { "code": null, "e": 34705, "s": 34677, "text": "HTML iframe with a link tag" }, { "code": null, "e": 34726, "s": 34705, "text": "Supported Browsers: " }, { "code": null, "e": 34745, "s": 34726, "text": "Google Chrome 93.0" }, { "code": null, "e": 34768, "s": 34745, "text": "Internet Explorer 11.0" }, { "code": null, "e": 34781, "s": 34768, "text": "Firefox 92.0" }, { "code": null, "e": 34801, "s": 34781, "text": "Microsoft Edge 93.0" }, { "code": null, "e": 34812, "s": 34801, "text": "Opera 78.0" }, { "code": null, "e": 34824, "s": 34812, "text": "Safari 14.1" }, { "code": null, "e": 34961, "s": 34824, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 34976, "s": 34961, "text": "ghoshsuman0129" }, { "code": null, "e": 34997, "s": 34976, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 35007, "s": 34997, "text": "HTML-Tags" }, { "code": null, "e": 35012, "s": 35007, "text": "HTML" }, { "code": null, "e": 35031, "s": 35012, "text": "Technical Scripter" }, { "code": null, "e": 35036, "s": 35031, "text": "HTML" }, { "code": null, "e": 35134, "s": 35036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35143, "s": 35134, "text": "Comments" }, { "code": null, "e": 35156, "s": 35143, "text": "Old Comments" }, { "code": null, "e": 35218, "s": 35156, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 35268, "s": 35218, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 35328, "s": 35268, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 35376, "s": 35328, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 35437, "s": 35376, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 35487, "s": 35437, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 35540, "s": 35487, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 35564, "s": 35540, "text": "REST API (Introduction)" }, { "code": null, "e": 35601, "s": 35564, "text": "Types of CSS (Cascading Style Sheet)" } ]
AtomicBoolean getAndSet() method in Java with Examples - GeeksforGeeks
27 Feb, 2019 The Java.util.concurrent.atomic.AtomicBoolean.getAndSet() is an inbuilt method in java that sets the given value to the value passed in the parameter and returns the value before updation which is of data-type boolean. Syntax: public final boolean getAndSet(boolean val) Parameters: The function accepts a single mandatory parameter val which specifies the value to be updated. Return Value: The function returns the value before update operation is performed to the previous value. Below programs illustrate the above method: Program 1: // Java program that demonstrates// the getAndSet() function import java.util.concurrent.atomic.AtomicBoolean; public class GFG { public static void main(String args[]) { // Initially value as false AtomicBoolean val = new AtomicBoolean(false); // Updates and sets boolean res = val.getAndSet(true); System.out.println("Previous value: " + res); // Prints the updated value System.out.println("Current value: " + val); }} Previous value: false Current value: true Program 2: // Java program that demonstrates// the getAndSet() function import java.util.concurrent.atomic.AtomicBoolean; public class GFG { public static void main(String args[]) { // Initially value as true AtomicBoolean val = new AtomicBoolean(true); // Gets and updates boolean res = val.getAndSet(false); System.out.println("Previous value: " + res); // Prints the updated value System.out.println("Current value: " + val); }} Previous value: true Current value: false Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html#getAndSet-boolean- Java-AtomicBoolean Java-concurrent-package Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25939, "s": 25911, "text": "\n27 Feb, 2019" }, { "code": null, "e": 26158, "s": 25939, "text": "The Java.util.concurrent.atomic.AtomicBoolean.getAndSet() is an inbuilt method in java that sets the given value to the value passed in the parameter and returns the value before updation which is of data-type boolean." }, { "code": null, "e": 26166, "s": 26158, "text": "Syntax:" }, { "code": null, "e": 26211, "s": 26166, "text": "public final boolean getAndSet(boolean val)\n" }, { "code": null, "e": 26318, "s": 26211, "text": "Parameters: The function accepts a single mandatory parameter val which specifies the value to be updated." }, { "code": null, "e": 26423, "s": 26318, "text": "Return Value: The function returns the value before update operation is performed to the previous value." }, { "code": null, "e": 26467, "s": 26423, "text": "Below programs illustrate the above method:" }, { "code": null, "e": 26478, "s": 26467, "text": "Program 1:" }, { "code": "// Java program that demonstrates// the getAndSet() function import java.util.concurrent.atomic.AtomicBoolean; public class GFG { public static void main(String args[]) { // Initially value as false AtomicBoolean val = new AtomicBoolean(false); // Updates and sets boolean res = val.getAndSet(true); System.out.println(\"Previous value: \" + res); // Prints the updated value System.out.println(\"Current value: \" + val); }}", "e": 27031, "s": 26478, "text": null }, { "code": null, "e": 27074, "s": 27031, "text": "Previous value: false\nCurrent value: true\n" }, { "code": null, "e": 27085, "s": 27074, "text": "Program 2:" }, { "code": "// Java program that demonstrates// the getAndSet() function import java.util.concurrent.atomic.AtomicBoolean; public class GFG { public static void main(String args[]) { // Initially value as true AtomicBoolean val = new AtomicBoolean(true); // Gets and updates boolean res = val.getAndSet(false); System.out.println(\"Previous value: \" + res); // Prints the updated value System.out.println(\"Current value: \" + val); }}", "e": 27624, "s": 27085, "text": null }, { "code": null, "e": 27667, "s": 27624, "text": "Previous value: true\nCurrent value: false\n" }, { "code": null, "e": 27786, "s": 27667, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html#getAndSet-boolean-" }, { "code": null, "e": 27805, "s": 27786, "text": "Java-AtomicBoolean" }, { "code": null, "e": 27829, "s": 27805, "text": "Java-concurrent-package" }, { "code": null, "e": 27844, "s": 27829, "text": "Java-Functions" }, { "code": null, "e": 27849, "s": 27844, "text": "Java" }, { "code": null, "e": 27854, "s": 27849, "text": "Java" }, { "code": null, "e": 27952, "s": 27854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28003, "s": 27952, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28033, "s": 28003, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28052, "s": 28033, "text": "Interfaces in Java" }, { "code": null, "e": 28067, "s": 28052, "text": "Stream In Java" }, { "code": null, "e": 28098, "s": 28067, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28116, "s": 28098, "text": "ArrayList in Java" }, { "code": null, "e": 28148, "s": 28116, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28168, "s": 28148, "text": "Stack Class in Java" }, { "code": null, "e": 28200, "s": 28168, "text": "Multidimensional Arrays in Java" } ]
C# Stack with Examples - GeeksforGeeks
22 Oct, 2021 A Stack represents a last-in, first-out collection of objects. It is used when you need last-in, first-out access to items. It is both a generic and non-generic type of collection. The generic stack is defined in System.Collections.Generic namespace whereas non-generic stack is defined under System.Collections namespace, here we will discuss non-generic type stack. A stack is used to create a dynamic collection that grows, according to the need of your program. In a stack, you can store elements of the same type or different types. The below diagram illustrates the Stack class hierarchy: Important Points: The Stack class implements the IEnumerable, ICollection, and ICloneable interfaces. When you add an item in the list, it is called pushing the element. When you remove it, it is called popping the element. The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. In Stack, you are allowed to store duplicate elements. A Stack accepts null as a valid value for reference types. Stack class has three constructors which are used to create a stack which is as follows: Stack(): This constructor is used to create an instance of the Stack class which is empty and having the default initial capacity. Stack(ICollection): This constructor is used to create an instance of the Stack class which contains elements copied from the specified collection, and has the same initial capacity as the number of elements copied. Stack(Int32): This constructor is used to create an instance of the Stack class which is empty and having specified initial capacity or the default initial capacity, whichever is greater. Let’s see how to create a stack using Stack() constructor:Step 1: Include System.Collections namespace in your program with the help of using keyword. using System.Collections; Step 2: Create a stack using Stack class as shown below: Stack stack_name = new Stack(); Step 3: If you want to add elements in your stack, then use Push() method to add elements in your stack. As shown in the below example. Example: C# // C# program to illustrate how to// create a stackusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a stack // Using Stack class Stack my_stack = new Stack(); // Adding elements in the Stack // Using Push method my_stack.Push("Geeks"); my_stack.Push("geeksforgeeks"); my_stack.Push('G'); my_stack.Push(null); my_stack.Push(1234); my_stack.Push(490.98); // Accessing the elements // of my_stack Stack // Using foreach loop foreach(var elem in my_stack) { Console.WriteLine(elem); } }} 490.98 1234 G geeksforgeeks Geeks In Stack, you are allowed to remove elements from the stack. The Stack class provides two different methods to remove elements and the methods are: Clear: This method is used to remove all the objects from the stack. Pop: This method removes the beginning element of the stack. Example: C# // C# program to illustrate how to// remove elements from the stackusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a stack // Using Stack class Stack my_stack = new Stack(); // Adding elements in the Stack // Using Push method my_stack.Push("Geeks"); my_stack.Push("geeksforgeeks"); my_stack.Push("geeks23"); my_stack.Push("GeeksforGeeks"); Console.WriteLine("Total elements present in"+ " my_stack: {0}", my_stack.Count); my_stack.Pop(); // After Pop method Console.WriteLine("Total elements present in "+ "my_stack: {0}", my_stack.Count); // Remove all the elements // from the stack my_stack.Clear(); // After Pop method Console.WriteLine("Total elements present in "+ "my_stack: {0}", my_stack.Count); }} Total elements present in my_stack: 4 Total elements present in my_stack: 3 Total elements present in my_stack: 0 In Stack, you can easily find the topmost element of the stack by using the following methods provided by the Stack class: Pop: This method returns the object at the beginning of the stack with modification means this method removes the topmost element of the stack. Peek: This method returns the object at the beginning of the stack without removing it. Example: C# // C# program to illustrate how to// get topmost elements of the stackusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a stack // Using Stack class Stack my_stack = new Stack(); // Adding elements in the Stack // Using Push method my_stack.Push("Geeks"); my_stack.Push("geeksforgeeks"); my_stack.Push("geeks23"); my_stack.Push("GeeksforGeeks"); Console.WriteLine("Total elements present in"+ " my_stack: {0}",my_stack.Count); // Obtain the topmost element // of my_stack Using Pop method Console.WriteLine("Topmost element of my_stack" + " is: {0}",my_stack.Pop()); Console.WriteLine("Total elements present in"+ " my_stack: {0}", my_stack.Count); // Obtain the topmost element // of my_stack Using Peek method Console.WriteLine("Topmost element of my_stack "+ "is: {0}",my_stack.Peek()); Console.WriteLine("Total elements present "+ "in my_stack: {0}",my_stack.Count); }} Total elements present in my_stack: 4 Topmost element of my_stack is: GeeksforGeeks Total elements present in my_stack: 3 Topmost element of my_stack is: geeks23 Total elements present in my_stack: 3 In a stack, you can check whether the given element is present or not using Contains() method. Or in other words, if you want to search an element in the given stack use Contains() method. This method returns true if the element present in the stack. Otherwise, return false. Note: The Contains() method takes O(n) time to check if the element exists in the stack. This should be taken into consideration while using this method. Example: C# // C# program to illustrate how// to check element present in// the stack or notusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a stack // Using Stack class Stack my_stack = new Stack(); // Adding elements in the Stack // Using Push method my_stack.Push("Geeks"); my_stack.Push("geeksforgeeks"); my_stack.Push("geeks23"); my_stack.Push("GeeksforGeeks"); // Checking if the element is // present in the Stack or not if (my_stack.Contains("GeeksforGeeks") == true) { Console.WriteLine("Element is found...!!"); } else { Console.WriteLine("Element is not found...!!"); } }} Element is found...!! Generic Stack Non-Generic Stack wadekarpraddyumn1 adventuremonki9 CSharp-Collections-Namespace CSharp-Collections-Stack CSharp-Stack-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# | IsNullOrEmpty() Method C# Dictionary with examples C# | Delegates C# | Arrays of Strings C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C#
[ { "code": null, "e": 38925, "s": 38897, "text": "\n22 Oct, 2021" }, { "code": null, "e": 39464, "s": 38925, "text": "A Stack represents a last-in, first-out collection of objects. It is used when you need last-in, first-out access to items. It is both a generic and non-generic type of collection. The generic stack is defined in System.Collections.Generic namespace whereas non-generic stack is defined under System.Collections namespace, here we will discuss non-generic type stack. A stack is used to create a dynamic collection that grows, according to the need of your program. In a stack, you can store elements of the same type or different types. " }, { "code": null, "e": 39522, "s": 39464, "text": "The below diagram illustrates the Stack class hierarchy: " }, { "code": null, "e": 39540, "s": 39522, "text": "Important Points:" }, { "code": null, "e": 39624, "s": 39540, "text": "The Stack class implements the IEnumerable, ICollection, and ICloneable interfaces." }, { "code": null, "e": 39692, "s": 39624, "text": "When you add an item in the list, it is called pushing the element." }, { "code": null, "e": 39746, "s": 39692, "text": "When you remove it, it is called popping the element." }, { "code": null, "e": 39924, "s": 39746, "text": "The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation." }, { "code": null, "e": 39979, "s": 39924, "text": "In Stack, you are allowed to store duplicate elements." }, { "code": null, "e": 40038, "s": 39979, "text": "A Stack accepts null as a valid value for reference types." }, { "code": null, "e": 40127, "s": 40038, "text": "Stack class has three constructors which are used to create a stack which is as follows:" }, { "code": null, "e": 40258, "s": 40127, "text": "Stack(): This constructor is used to create an instance of the Stack class which is empty and having the default initial capacity." }, { "code": null, "e": 40474, "s": 40258, "text": "Stack(ICollection): This constructor is used to create an instance of the Stack class which contains elements copied from the specified collection, and has the same initial capacity as the number of elements copied." }, { "code": null, "e": 40662, "s": 40474, "text": "Stack(Int32): This constructor is used to create an instance of the Stack class which is empty and having specified initial capacity or the default initial capacity, whichever is greater." }, { "code": null, "e": 40813, "s": 40662, "text": "Let’s see how to create a stack using Stack() constructor:Step 1: Include System.Collections namespace in your program with the help of using keyword." }, { "code": null, "e": 40839, "s": 40813, "text": "using System.Collections;" }, { "code": null, "e": 40896, "s": 40839, "text": "Step 2: Create a stack using Stack class as shown below:" }, { "code": null, "e": 40928, "s": 40896, "text": "Stack stack_name = new Stack();" }, { "code": null, "e": 41064, "s": 40928, "text": "Step 3: If you want to add elements in your stack, then use Push() method to add elements in your stack. As shown in the below example." }, { "code": null, "e": 41073, "s": 41064, "text": "Example:" }, { "code": null, "e": 41076, "s": 41073, "text": "C#" }, { "code": "// C# program to illustrate how to// create a stackusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a stack // Using Stack class Stack my_stack = new Stack(); // Adding elements in the Stack // Using Push method my_stack.Push(\"Geeks\"); my_stack.Push(\"geeksforgeeks\"); my_stack.Push('G'); my_stack.Push(null); my_stack.Push(1234); my_stack.Push(490.98); // Accessing the elements // of my_stack Stack // Using foreach loop foreach(var elem in my_stack) { Console.WriteLine(elem); } }}", "e": 41761, "s": 41076, "text": null }, { "code": null, "e": 41796, "s": 41761, "text": "490.98\n1234\n\nG\ngeeksforgeeks\nGeeks" }, { "code": null, "e": 41946, "s": 41798, "text": "In Stack, you are allowed to remove elements from the stack. The Stack class provides two different methods to remove elements and the methods are:" }, { "code": null, "e": 42015, "s": 41946, "text": "Clear: This method is used to remove all the objects from the stack." }, { "code": null, "e": 42076, "s": 42015, "text": "Pop: This method removes the beginning element of the stack." }, { "code": null, "e": 42085, "s": 42076, "text": "Example:" }, { "code": null, "e": 42088, "s": 42085, "text": "C#" }, { "code": "// C# program to illustrate how to// remove elements from the stackusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a stack // Using Stack class Stack my_stack = new Stack(); // Adding elements in the Stack // Using Push method my_stack.Push(\"Geeks\"); my_stack.Push(\"geeksforgeeks\"); my_stack.Push(\"geeks23\"); my_stack.Push(\"GeeksforGeeks\"); Console.WriteLine(\"Total elements present in\"+ \" my_stack: {0}\", my_stack.Count); my_stack.Pop(); // After Pop method Console.WriteLine(\"Total elements present in \"+ \"my_stack: {0}\", my_stack.Count); // Remove all the elements // from the stack my_stack.Clear(); // After Pop method Console.WriteLine(\"Total elements present in \"+ \"my_stack: {0}\", my_stack.Count); }}", "e": 43216, "s": 42088, "text": null }, { "code": null, "e": 43330, "s": 43216, "text": "Total elements present in my_stack: 4\nTotal elements present in my_stack: 3\nTotal elements present in my_stack: 0" }, { "code": null, "e": 43455, "s": 43332, "text": "In Stack, you can easily find the topmost element of the stack by using the following methods provided by the Stack class:" }, { "code": null, "e": 43599, "s": 43455, "text": "Pop: This method returns the object at the beginning of the stack with modification means this method removes the topmost element of the stack." }, { "code": null, "e": 43687, "s": 43599, "text": "Peek: This method returns the object at the beginning of the stack without removing it." }, { "code": null, "e": 43696, "s": 43687, "text": "Example:" }, { "code": null, "e": 43699, "s": 43696, "text": "C#" }, { "code": "// C# program to illustrate how to// get topmost elements of the stackusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a stack // Using Stack class Stack my_stack = new Stack(); // Adding elements in the Stack // Using Push method my_stack.Push(\"Geeks\"); my_stack.Push(\"geeksforgeeks\"); my_stack.Push(\"geeks23\"); my_stack.Push(\"GeeksforGeeks\"); Console.WriteLine(\"Total elements present in\"+ \" my_stack: {0}\",my_stack.Count); // Obtain the topmost element // of my_stack Using Pop method Console.WriteLine(\"Topmost element of my_stack\" + \" is: {0}\",my_stack.Pop()); Console.WriteLine(\"Total elements present in\"+ \" my_stack: {0}\", my_stack.Count); // Obtain the topmost element // of my_stack Using Peek method Console.WriteLine(\"Topmost element of my_stack \"+ \"is: {0}\",my_stack.Peek()); Console.WriteLine(\"Total elements present \"+ \"in my_stack: {0}\",my_stack.Count); }}", "e": 45038, "s": 43699, "text": null }, { "code": null, "e": 45238, "s": 45038, "text": "Total elements present in my_stack: 4\nTopmost element of my_stack is: GeeksforGeeks\nTotal elements present in my_stack: 3\nTopmost element of my_stack is: geeks23\nTotal elements present in my_stack: 3" }, { "code": null, "e": 45516, "s": 45240, "text": "In a stack, you can check whether the given element is present or not using Contains() method. Or in other words, if you want to search an element in the given stack use Contains() method. This method returns true if the element present in the stack. Otherwise, return false." }, { "code": null, "e": 45670, "s": 45516, "text": "Note: The Contains() method takes O(n) time to check if the element exists in the stack. This should be taken into consideration while using this method." }, { "code": null, "e": 45679, "s": 45670, "text": "Example:" }, { "code": null, "e": 45682, "s": 45679, "text": "C#" }, { "code": "// C# program to illustrate how// to check element present in// the stack or notusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a stack // Using Stack class Stack my_stack = new Stack(); // Adding elements in the Stack // Using Push method my_stack.Push(\"Geeks\"); my_stack.Push(\"geeksforgeeks\"); my_stack.Push(\"geeks23\"); my_stack.Push(\"GeeksforGeeks\"); // Checking if the element is // present in the Stack or not if (my_stack.Contains(\"GeeksforGeeks\") == true) { Console.WriteLine(\"Element is found...!!\"); } else { Console.WriteLine(\"Element is not found...!!\"); } }}", "e": 46468, "s": 45682, "text": null }, { "code": null, "e": 46490, "s": 46468, "text": "Element is found...!!" }, { "code": null, "e": 46506, "s": 46492, "text": "Generic Stack" }, { "code": null, "e": 46524, "s": 46506, "text": "Non-Generic Stack" }, { "code": null, "e": 46542, "s": 46524, "text": "wadekarpraddyumn1" }, { "code": null, "e": 46558, "s": 46542, "text": "adventuremonki9" }, { "code": null, "e": 46587, "s": 46558, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 46612, "s": 46587, "text": "CSharp-Collections-Stack" }, { "code": null, "e": 46631, "s": 46612, "text": "CSharp-Stack-Class" }, { "code": null, "e": 46634, "s": 46631, "text": "C#" }, { "code": null, "e": 46732, "s": 46634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46786, "s": 46732, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 46828, "s": 46786, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 46890, "s": 46828, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 46918, "s": 46890, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 46946, "s": 46918, "text": "C# Dictionary with examples" }, { "code": null, "e": 46961, "s": 46946, "text": "C# | Delegates" }, { "code": null, "e": 46984, "s": 46961, "text": "C# | Arrays of Strings" }, { "code": null, "e": 47007, "s": 46984, "text": "C# | Method Overriding" }, { "code": null, "e": 47029, "s": 47007, "text": "C# | Abstract Classes" } ]
How to set the Height of the Drop-Down List in the ComboBox in C#? - GeeksforGeeks
30 Jun, 2019 In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the height in pixels of the drop-down list in your ComboBox by using the DropDownHeight Property. You can set this property using two different methods: 1. Design-Time: It is the easiest method to set the DropDownHeight property of the ComboBox control using the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the ComboBox control to set the DropDownHeight property of the ComboBox.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the height of the drop-down list in the ComboBox programmatically with the help of given syntax: public int DropDownHeight { get; set; } Here, the value of this property is of System.Int32 type. It will throw an ArgumentException if the value of this property is less than one. Following steps are used to set the DropDownHeight Property of the ComboBox elements: Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class ComboBox mybox = new ComboBox(); // Creating ComboBox using ComboBox class ComboBox mybox = new ComboBox(); Step 2: After creating ComboBox, set the DropDownHeight property of the ComboBox provided by the ComboBox class.// Set DropDownHeight property of the combobox mybox.DropDownHeight = 26; // Set DropDownHeight property of the combobox mybox.DropDownHeight = 26; Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form this.Controls.Add(mybox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp14 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select Id"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.MaxLength = 3; mybox.DropDownStyle = ComboBoxStyle.DropDown; mybox.DropDownHeight = 26; mybox.Items.Add(240); mybox.Items.Add(241); mybox.Items.Add(242); mybox.Items.Add(243); mybox.Items.Add(244); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:Before setting drop-down height:After setting drop-down height: // Add this ComboBox to form this.Controls.Add(mybox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp14 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select Id"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.MaxLength = 3; mybox.DropDownStyle = ComboBoxStyle.DropDown; mybox.DropDownHeight = 26; mybox.Items.Add(240); mybox.Items.Add(241); mybox.Items.Add(242); mybox.Items.Add(243); mybox.Items.Add(244); // Adding this ComboBox to the form this.Controls.Add(mybox); }}} Output: Before setting drop-down height: After setting drop-down height: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | Replace() Method C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 25429, "s": 25401, "text": "\n30 Jun, 2019" }, { "code": null, "e": 25849, "s": 25429, "text": "In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the height in pixels of the drop-down list in your ComboBox by using the DropDownHeight Property. You can set this property using two different methods:" }, { "code": null, "e": 25976, "s": 25849, "text": "1. Design-Time: It is the easiest method to set the DropDownHeight property of the ComboBox control using the following steps:" }, { "code": null, "e": 26092, "s": 25976, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 26273, "s": 26092, "text": "Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need." }, { "code": null, "e": 26414, "s": 26273, "text": "Step 3: After drag and drop you will go to the properties of the ComboBox control to set the DropDownHeight property of the ComboBox.Output:" }, { "code": null, "e": 26422, "s": 26414, "text": "Output:" }, { "code": null, "e": 26611, "s": 26422, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the height of the drop-down list in the ComboBox programmatically with the help of given syntax:" }, { "code": null, "e": 26651, "s": 26611, "text": "public int DropDownHeight { get; set; }" }, { "code": null, "e": 26878, "s": 26651, "text": "Here, the value of this property is of System.Int32 type. It will throw an ArgumentException if the value of this property is less than one. Following steps are used to set the DropDownHeight Property of the ComboBox elements:" }, { "code": null, "e": 27047, "s": 26878, "text": "Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n" }, { "code": null, "e": 27123, "s": 27047, "text": "// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n" }, { "code": null, "e": 27310, "s": 27123, "text": "Step 2: After creating ComboBox, set the DropDownHeight property of the ComboBox provided by the ComboBox class.// Set DropDownHeight property of the combobox\nmybox.DropDownHeight = 26;\n" }, { "code": null, "e": 27385, "s": 27310, "text": "// Set DropDownHeight property of the combobox\nmybox.DropDownHeight = 26;\n" }, { "code": null, "e": 28771, "s": 27385, "text": "Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form\nthis.Controls.Add(mybox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp14 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select Id\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.MaxLength = 3; mybox.DropDownStyle = ComboBoxStyle.DropDown; mybox.DropDownHeight = 26; mybox.Items.Add(240); mybox.Items.Add(241); mybox.Items.Add(242); mybox.Items.Add(243); mybox.Items.Add(244); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:Before setting drop-down height:After setting drop-down height:" }, { "code": null, "e": 28827, "s": 28771, "text": "// Add this ComboBox to form\nthis.Controls.Add(mybox);\n" }, { "code": null, "e": 28836, "s": 28827, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp14 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select Id\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.MaxLength = 3; mybox.DropDownStyle = ComboBoxStyle.DropDown; mybox.DropDownHeight = 26; mybox.Items.Add(240); mybox.Items.Add(241); mybox.Items.Add(242); mybox.Items.Add(243); mybox.Items.Add(244); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}", "e": 30019, "s": 28836, "text": null }, { "code": null, "e": 30027, "s": 30019, "text": "Output:" }, { "code": null, "e": 30060, "s": 30027, "text": "Before setting drop-down height:" }, { "code": null, "e": 30092, "s": 30060, "text": "After setting drop-down height:" }, { "code": null, "e": 30095, "s": 30092, "text": "C#" }, { "code": null, "e": 30193, "s": 30095, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30221, "s": 30193, "text": "C# Dictionary with examples" }, { "code": null, "e": 30236, "s": 30221, "text": "C# | Delegates" }, { "code": null, "e": 30259, "s": 30236, "text": "C# | Method Overriding" }, { "code": null, "e": 30281, "s": 30259, "text": "C# | Abstract Classes" }, { "code": null, "e": 30327, "s": 30281, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30350, "s": 30327, "text": "Extension Method in C#" }, { "code": null, "e": 30372, "s": 30350, "text": "C# | Class and Object" }, { "code": null, "e": 30390, "s": 30372, "text": "C# | Constructors" }, { "code": null, "e": 30412, "s": 30390, "text": "C# | Replace() Method" } ]
Create Lagged Variable by Group in R DataFrame - GeeksforGeeks
30 May, 2021 Lagged variable is the type of variable that contains the previous value of the variable for which we want to create the lagged variable and the first value is neglected. Data can be segregated based on different groups in R programming language and then these categories can be processed differently. The “dplyr” package in R language is used to perform data enhancements and manipulations and can be loaded into the working space. group_by() method in R can be used to categorize data into groups based on either a single column or a group of multiple columns. All the plausible unique combinations of the input columns are stacked together as a single group. Syntax: group_by(args .. ), where the args contain a sequence of column to group data upon This is followed by the application of the mutate() method over the data frame which is used to simulate creation, deletion and modification of data frame columns. mutate() method adds new variables as well as preserves the existing ones. The mutate method takes as an argument the lag() method to perform transmutations on the data. The lag() method is used to induce lagged values for the specified variable. Syntax: lag(col, n = 1L, default = NA) Parameters : col – The column of the data frame to introduce lagged values in. n – (Default : 1) The number of positions to lead or lag by default – (Default : NA) Value used for non-existent rows. The first instance of the occurrence of the variable in the lag() input column’s attribute is replaced by NA. All the successive instances as replaced by the previous value that was assigned to the same group. The result of these methods is in the form of a tibble which is a table-like structure and proper information about the number of groups and column class is returned. Example 1: R library("dplyr") # creating a data framedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3] ) print ("Original DataFrame")print (data_frame) data_mod <- data_frame %>% group_by(col1) %>% dplyr::mutate(laggedval = lag(col2, n = 1, default = NA)) print ("Modified Data")print (data_mod) Output [1] "Original DataFrame" col1 col2 1 1 a 2 1 b 3 1 c 4 2 a 5 2 b 6 2 c 7 3 a 8 3 b 9 3 c [1] "Modified Data" # A tibble: 9 x 3 # Groups: col1 [3] col1 col2 laggedval <int> <fct> <fct> 1 1 a NA 2 1 b a 3 1 c b 4 2 a NA 5 2 b a 6 2 c b 7 3 a NA 8 3 b a 9 3 c b Grouping can be done based on multiple columns, where the groups created are dependent on the different possible unique sets that can be created out of all the combinations of the involved columns. Example 2: R library("tidyverse") # creating a data framedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,2,1,2,2)) print ("Original DataFrame")print (data_frame) print ("Modified DataFrame")data_mod <- data_frame %>% group_by(col1,col3) %>% dplyr::mutate(laggedval = lag(col2, n = 1, default = NA)) print ("Modified Data")print (data_mod) Output [1] "Original DataFrame" col1 col2 col3 1 1 a 1 2 1 b 4 3 1 c 1 4 2 a 2 5 2 b 2 6 2 c 2 7 3 a 1 8 3 b 2 9 3 c 2 [1] "Modified DataFrame" [1] "Modified Data" # A tibble: 9 x 4 # Groups: col1, col3 [5] col1 col2 col3 laggedval <int> <fct> <dbl> <fct> 1 1 a 1 NA 2 1 b 4 NA 3 1 c 1 a 4 2 a 2 NA 5 2 b 2 a 6 2 c 2 b 7 3 a 1 NA 8 3 b 2 NA 9 3 c 2 b Initially, the number of rows of the data frame are fetched using the nrow() method in R language. This is followed by the extraction of values from the column to introduce lagged values in excluding the last row value. This will return a vector of one missing value (induced for the last row) followed by the row values in order of the desired column. The first instance of every group occurrence is then identified by the duplicated() method and replaced by NA using the which() method. These values’ modification is stored in the new column name assigned to the data frame. Example: R # creating a data framedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3] ) print ("Original DataFrame")print (data_frame) # getting the last row col indexlast_row <- -nrow(data_frame)excl_last_row <- as.character(data_frame$col2[last_row]) # create a vector of values of NA and col2 data_frame$lag_value <- c( NA, excl_last_row) # replace first occurence by NAdata_frame$lag_value[which(!duplicated(data_frame$col1))] <- NAprint ("Modified Data")print (data_frame) Output [1] "Original DataFrame" col1 col2 1 1 a 2 1 b 3 1 c 4 2 a 5 2 b 6 2 c 7 3 a 8 3 b 9 3 c [1] "Modified Data" col1 col2 lag_value 1 1 a <NA> 2 1 b a 3 1 c b 4 2 a <NA> 5 2 b a 6 2 c b 7 3 a <NA> 8 3 b a 9 3 c b Picked R DataFrame-Programs R-DataFrame 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": "\n30 May, 2021" }, { "code": null, "e": 26790, "s": 26487, "text": "Lagged variable is the type of variable that contains the previous value of the variable for which we want to create the lagged variable and the first value is neglected. Data can be segregated based on different groups in R programming language and then these categories can be processed differently. " }, { "code": null, "e": 26921, "s": 26790, "text": "The “dplyr” package in R language is used to perform data enhancements and manipulations and can be loaded into the working space." }, { "code": null, "e": 27150, "s": 26921, "text": "group_by() method in R can be used to categorize data into groups based on either a single column or a group of multiple columns. All the plausible unique combinations of the input columns are stacked together as a single group." }, { "code": null, "e": 27158, "s": 27150, "text": "Syntax:" }, { "code": null, "e": 27178, "s": 27158, "text": "group_by(args .. )," }, { "code": null, "e": 27241, "s": 27178, "text": "where the args contain a sequence of column to group data upon" }, { "code": null, "e": 27652, "s": 27241, "text": "This is followed by the application of the mutate() method over the data frame which is used to simulate creation, deletion and modification of data frame columns. mutate() method adds new variables as well as preserves the existing ones. The mutate method takes as an argument the lag() method to perform transmutations on the data. The lag() method is used to induce lagged values for the specified variable." }, { "code": null, "e": 27660, "s": 27652, "text": "Syntax:" }, { "code": null, "e": 27691, "s": 27660, "text": "lag(col, n = 1L, default = NA)" }, { "code": null, "e": 27704, "s": 27691, "text": "Parameters :" }, { "code": null, "e": 27771, "s": 27704, "text": "col – The column of the data frame to introduce lagged values in. " }, { "code": null, "e": 27831, "s": 27771, "text": "n – (Default : 1) The number of positions to lead or lag by" }, { "code": null, "e": 27893, "s": 27831, "text": "default – (Default : NA) Value used for non-existent rows. " }, { "code": null, "e": 28104, "s": 27893, "text": "The first instance of the occurrence of the variable in the lag() input column’s attribute is replaced by NA. All the successive instances as replaced by the previous value that was assigned to the same group. " }, { "code": null, "e": 28272, "s": 28104, "text": "The result of these methods is in the form of a tibble which is a table-like structure and proper information about the number of groups and column class is returned. " }, { "code": null, "e": 28283, "s": 28272, "text": "Example 1:" }, { "code": null, "e": 28285, "s": 28283, "text": "R" }, { "code": "library(\"dplyr\") # creating a data framedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3] ) print (\"Original DataFrame\")print (data_frame) data_mod <- data_frame %>% group_by(col1) %>% dplyr::mutate(laggedval = lag(col2, n = 1, default = NA)) print (\"Modified Data\")print (data_mod)", "e": 28676, "s": 28285, "text": null }, { "code": null, "e": 28683, "s": 28676, "text": "Output" }, { "code": null, "e": 29167, "s": 28683, "text": "[1] \"Original DataFrame\" \ncol1 col2 \n1 1 a \n2 1 b\n3 1 c \n4 2 a \n5 2 b \n6 2 c \n7 3 a \n8 3 b \n9 3 c \n[1] \"Modified Data\" \n# A tibble: 9 x 3 \n# Groups: col1 [3] \ncol1 col2 laggedval \n<int> <fct> <fct> \n1 1 a NA \n2 1 b a \n3 1 c b \n4 2 a NA \n5 2 b a \n6 2 c b \n7 3 a NA \n8 3 b a \n9 3 c b " }, { "code": null, "e": 29366, "s": 29167, "text": "Grouping can be done based on multiple columns, where the groups created are dependent on the different possible unique sets that can be created out of all the combinations of the involved columns. " }, { "code": null, "e": 29377, "s": 29366, "text": "Example 2:" }, { "code": null, "e": 29379, "s": 29377, "text": "R" }, { "code": "library(\"tidyverse\") # creating a data framedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,2,1,2,2)) print (\"Original DataFrame\")print (data_frame) print (\"Modified DataFrame\")data_mod <- data_frame %>% group_by(col1,col3) %>% dplyr::mutate(laggedval = lag(col2, n = 1, default = NA)) print (\"Modified Data\")print (data_mod) ", "e": 29836, "s": 29379, "text": null }, { "code": null, "e": 29843, "s": 29836, "text": "Output" }, { "code": null, "e": 30480, "s": 29843, "text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 1 a 1 \n2 1 b 4 \n3 1 c 1 \n4 2 a 2 \n5 2 b 2 \n6 2 c 2 \n7 3 a 1 \n8 3 b 2 \n9 3 c 2 \n[1] \"Modified DataFrame\" \n[1] \"Modified Data\" \n# A tibble: 9 x 4 \n# Groups: col1, col3 [5] \ncol1 col2 col3 laggedval \n <int> <fct> <dbl> <fct> \n1 1 a 1 NA \n2 1 b 4 NA \n3 1 c 1 a \n4 2 a 2 NA \n5 2 b 2 a \n6 2 c 2 b \n7 3 a 1 NA \n8 3 b 2 NA \n9 3 c 2 b " }, { "code": null, "e": 30834, "s": 30480, "text": "Initially, the number of rows of the data frame are fetched using the nrow() method in R language. This is followed by the extraction of values from the column to introduce lagged values in excluding the last row value. This will return a vector of one missing value (induced for the last row) followed by the row values in order of the desired column. " }, { "code": null, "e": 31059, "s": 30834, "text": "The first instance of every group occurrence is then identified by the duplicated() method and replaced by NA using the which() method. These values’ modification is stored in the new column name assigned to the data frame. " }, { "code": null, "e": 31068, "s": 31059, "text": "Example:" }, { "code": null, "e": 31070, "s": 31068, "text": "R" }, { "code": "# creating a data framedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3] ) print (\"Original DataFrame\")print (data_frame) # getting the last row col indexlast_row <- -nrow(data_frame)excl_last_row <- as.character(data_frame$col2[last_row]) # create a vector of values of NA and col2 data_frame$lag_value <- c( NA, excl_last_row) # replace first occurence by NAdata_frame$lag_value[which(!duplicated(data_frame$col1))] <- NAprint (\"Modified Data\")print (data_frame) ", "e": 31616, "s": 31070, "text": null }, { "code": null, "e": 31623, "s": 31616, "text": "Output" }, { "code": null, "e": 32030, "s": 31623, "text": "[1] \"Original DataFrame\" \n col1 col2 \n1 1 a \n2 1 b \n3 1 c \n4 2 a \n5 2 b \n6 2 c \n7 3 a \n8 3 b \n9 3 c \n[1] \"Modified Data\" \n col1 col2 lag_value \n1 1 a <NA> \n2 1 b a \n3 1 c b \n4 2 a <NA> \n5 2 b a \n6 2 c b \n7 3 a <NA> \n8 3 b a \n9 3 c b" }, { "code": null, "e": 32037, "s": 32030, "text": "Picked" }, { "code": null, "e": 32058, "s": 32037, "text": "R DataFrame-Programs" }, { "code": null, "e": 32070, "s": 32058, "text": "R-DataFrame" }, { "code": null, "e": 32081, "s": 32070, "text": "R Language" }, { "code": null, "e": 32092, "s": 32081, "text": "R Programs" }, { "code": null, "e": 32190, "s": 32092, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32242, "s": 32190, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 32277, "s": 32242, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 32315, "s": 32277, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 32373, "s": 32315, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32416, "s": 32373, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 32474, "s": 32416, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32517, "s": 32474, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 32566, "s": 32517, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 32616, "s": 32566, "text": "How to filter R dataframe by multiple conditions?" } ]
MySQL WHILE Loop - GeeksforGeeks
21 Jan, 2022 In this, we will cover the overview of MySQL WHILE Loop and then will cover the algorithm of each example and then will see the analysis of each example. Let’s discuss it one by one. Introduction :MySQL WHILE loop statement is used to execute one or more statements again and again, as long as a condition is true. We can use the loop when we need to execute the task with repetition while condition is true.Note – Use a WHILE LOOP statement in case you are unsure of what number of times you would like the loop body to execute. Since the WHILE condition is evaluated before entering the loop, it’s possible that the loop body might not execute even once. Syntax : [label_name:] WHILE condition DO statements_list END WHILE [label_name] Syntax label meaning – Label_name – label_name is optional, it’s a name related to the WHILE loop. Condition – condition is tested each undergoes through the WHILE loop. If the condition results in TRUE, the statements_list is executed, or if the condition results in FALSE, the WHILE loop is terminated. Statements_list – Statements_list is that the list of statements to be executed withstand the WHILE loop. Block diagram of While loop : Block diagram of WHILE loop Examples of MySQL WHILE Loop : Example-1 : Lets us create a function using a while loop. DELIMITER $$ CREATE FUNCTION GeekInc ( value INT ) RETURNS INT BEGIN DECLARE inc INT; SET inc = 0; label: WHILE inc <= 30000 DO SET inc = inc + value; END WHILE label; RETURN inc; END; $$ DELIMITER ; Analysis – Value is the input for the GeekInc function. inc is declared and set to 0. While inc is less than and equal to 3000, it will set inc to inc + value. To check output used the following command given below. CALL GeekInc(10000); Output – 0, 10000, 20000, 30000 Example-2 :Let us create a procedure using a while loop. DELIMITER $$ CREATE procedure while_ex() block: BEGIN declare value VARCHAR(20) default ' ' ; declare num INT default 0; SET num = 1; WHILE num <= 5 DO SET value = CONCAT(value, num ,',' ); SET num = num + 1; END WHILE block; select value ; END $$ DELIMITER ; Analysis – create procedure while_ex and declare value and num. set num at 1, while num is equal to or less than 5 do set value equal to concatenation of value and num. To check output used the following command given below. call while_ex(); Output – Example-3 : Let us create a table “Test_Cal” which has dates as follows. CREATE TABLE Test_Cal( t_in INT AUTO_INCREMENT, fulldate DATE UNIQUE, day TINYINT NOT NULL, month TINYINT NOT NULL, PRIMARY KEY(id) ); Now, create a stored procedure to insert data into the table as follows. DELIMITER $$ CREATE PROCEDURE InsertCal(dt DATE) BEGIN INSERT INTO Test_Cal( fulldate, day, month ) VALUES(dt, EXTRACT(DAY FROM dt), EXTRACT(MONTH FROM dt) ); END$$ DELIMITER ; Now create stored procedure LoadCal() that updates the number of days starting from a start date into the table. DELIMITER $$ CREATE PROCEDURE LoadCal( startDate DATE, day INT ) BEGIN DECLARE counter INT DEFAULT 1; DECLARE dt DATE DEFAULT startDate; WHILE counter <= day DO CALL InsertCal(dt); SET counter = counter + 1; SET dt = DATE_ADD(dt,INTERVAL 1 day); END WHILE; END$$ DELIMITER ; Analysis – The stored procedure LoadCal() has two parameters: startDate and day. First, declare a counter and dt variables for saving values. Then, check if the counter is less than or equal day, if yes: Run stored procedure Inertial() to insert a row into the Test_Cal table. An increase in counter by 1 increases the dt by 1 day using the DATE_ADD(). The WHILE loop inserts date into the table till the counter is the same as the day. To check output used the following command given below. CALL LoadCal('2021-01-01',31); select * from Test_Cal where tid < 10 ; Output – clintra DBMS-SQL loop mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n21 Jan, 2022" }, { "code": null, "e": 25696, "s": 25513, "text": "In this, we will cover the overview of MySQL WHILE Loop and then will cover the algorithm of each example and then will see the analysis of each example. Let’s discuss it one by one." }, { "code": null, "e": 26170, "s": 25696, "text": "Introduction :MySQL WHILE loop statement is used to execute one or more statements again and again, as long as a condition is true. We can use the loop when we need to execute the task with repetition while condition is true.Note – Use a WHILE LOOP statement in case you are unsure of what number of times you would like the loop body to execute. Since the WHILE condition is evaluated before entering the loop, it’s possible that the loop body might not execute even once." }, { "code": null, "e": 26179, "s": 26170, "text": "Syntax :" }, { "code": null, "e": 26255, "s": 26179, "text": "[label_name:] WHILE \ncondition DO \n statements_list\nEND WHILE [label_name]" }, { "code": null, "e": 26278, "s": 26255, "text": "Syntax label meaning –" }, { "code": null, "e": 26354, "s": 26278, "text": "Label_name – label_name is optional, it’s a name related to the WHILE loop." }, { "code": null, "e": 26560, "s": 26354, "text": "Condition – condition is tested each undergoes through the WHILE loop. If the condition results in TRUE, the statements_list is executed, or if the condition results in FALSE, the WHILE loop is terminated." }, { "code": null, "e": 26666, "s": 26560, "text": "Statements_list – Statements_list is that the list of statements to be executed withstand the WHILE loop." }, { "code": null, "e": 26696, "s": 26666, "text": "Block diagram of While loop :" }, { "code": null, "e": 26725, "s": 26696, "text": "Block diagram of WHILE loop " }, { "code": null, "e": 26758, "s": 26727, "text": "Examples of MySQL WHILE Loop :" }, { "code": null, "e": 26816, "s": 26758, "text": "Example-1 : Lets us create a function using a while loop." }, { "code": null, "e": 27032, "s": 26816, "text": "DELIMITER $$\nCREATE FUNCTION GeekInc ( value INT )\nRETURNS INT\nBEGIN\n DECLARE inc INT;\n SET inc = 0;\n label: \nWHILE inc <= 30000 DO\n SET inc = inc + value;\n END \nWHILE label;\n RETURN inc;\nEND; $$\nDELIMITER ;" }, { "code": null, "e": 27043, "s": 27032, "text": "Analysis –" }, { "code": null, "e": 27088, "s": 27043, "text": "Value is the input for the GeekInc function." }, { "code": null, "e": 27118, "s": 27088, "text": "inc is declared and set to 0." }, { "code": null, "e": 27192, "s": 27118, "text": "While inc is less than and equal to 3000, it will set inc to inc + value." }, { "code": null, "e": 27248, "s": 27192, "text": "To check output used the following command given below." }, { "code": null, "e": 27269, "s": 27248, "text": "CALL GeekInc(10000);" }, { "code": null, "e": 27278, "s": 27269, "text": "Output –" }, { "code": null, "e": 27301, "s": 27278, "text": "0, 10000, 20000, 30000" }, { "code": null, "e": 27358, "s": 27301, "text": "Example-2 :Let us create a procedure using a while loop." }, { "code": null, "e": 27631, "s": 27358, "text": "DELIMITER $$\nCREATE procedure while_ex()\nblock: BEGIN\n declare value VARCHAR(20) default ' ' ;\n declare num INT default 0;\n SET num = 1;\n WHILE num <= 5 DO\n SET value = CONCAT(value, num ,',' );\n SET num = num + 1;\n END\n WHILE block;\n select value ;\nEND $$\nDELIMITER ;" }, { "code": null, "e": 27642, "s": 27631, "text": "Analysis –" }, { "code": null, "e": 27695, "s": 27642, "text": "create procedure while_ex and declare value and num." }, { "code": null, "e": 27749, "s": 27695, "text": "set num at 1, while num is equal to or less than 5 do" }, { "code": null, "e": 27800, "s": 27749, "text": "set value equal to concatenation of value and num." }, { "code": null, "e": 27856, "s": 27800, "text": "To check output used the following command given below." }, { "code": null, "e": 27873, "s": 27856, "text": "call while_ex();" }, { "code": null, "e": 27882, "s": 27873, "text": "Output –" }, { "code": null, "e": 27955, "s": 27882, "text": "Example-3 : Let us create a table “Test_Cal” which has dates as follows." }, { "code": null, "e": 28105, "s": 27955, "text": "CREATE TABLE Test_Cal(\n t_in INT AUTO_INCREMENT,\n fulldate DATE UNIQUE,\n day TINYINT NOT NULL,\n month TINYINT NOT NULL,\n PRIMARY KEY(id)\n);" }, { "code": null, "e": 28178, "s": 28105, "text": "Now, create a stored procedure to insert data into the table as follows." }, { "code": null, "e": 28403, "s": 28178, "text": "DELIMITER $$\nCREATE PROCEDURE InsertCal(dt DATE)\nBEGIN\n INSERT INTO Test_Cal(\n fulldate,\n day,\n month )\n VALUES(dt, \n EXTRACT(DAY FROM dt),\n EXTRACT(MONTH FROM dt)\n );\nEND$$\nDELIMITER ;" }, { "code": null, "e": 28516, "s": 28403, "text": "Now create stored procedure LoadCal() that updates the number of days starting from a start date into the table." }, { "code": null, "e": 28835, "s": 28516, "text": "DELIMITER $$\nCREATE PROCEDURE LoadCal(\n startDate DATE, \n day INT\n)\nBEGIN\n DECLARE counter INT DEFAULT 1;\n DECLARE dt DATE DEFAULT startDate;\n WHILE counter <= day DO\n CALL InsertCal(dt);\n SET counter = counter + 1;\n SET dt = DATE_ADD(dt,INTERVAL 1 day);\n END WHILE;\nEND$$\nDELIMITER ;" }, { "code": null, "e": 28846, "s": 28835, "text": "Analysis –" }, { "code": null, "e": 28916, "s": 28846, "text": "The stored procedure LoadCal() has two parameters: startDate and day." }, { "code": null, "e": 28977, "s": 28916, "text": "First, declare a counter and dt variables for saving values." }, { "code": null, "e": 29039, "s": 28977, "text": "Then, check if the counter is less than or equal day, if yes:" }, { "code": null, "e": 29112, "s": 29039, "text": "Run stored procedure Inertial() to insert a row into the Test_Cal table." }, { "code": null, "e": 29188, "s": 29112, "text": "An increase in counter by 1 increases the dt by 1 day using the DATE_ADD()." }, { "code": null, "e": 29272, "s": 29188, "text": "The WHILE loop inserts date into the table till the counter is the same as the day." }, { "code": null, "e": 29328, "s": 29272, "text": "To check output used the following command given below." }, { "code": null, "e": 29399, "s": 29328, "text": "CALL LoadCal('2021-01-01',31);\nselect * from Test_Cal where tid < 10 ;" }, { "code": null, "e": 29408, "s": 29399, "text": "Output –" }, { "code": null, "e": 29416, "s": 29408, "text": "clintra" }, { "code": null, "e": 29425, "s": 29416, "text": "DBMS-SQL" }, { "code": null, "e": 29430, "s": 29425, "text": "loop" }, { "code": null, "e": 29436, "s": 29430, "text": "mysql" }, { "code": null, "e": 29440, "s": 29436, "text": "SQL" }, { "code": null, "e": 29444, "s": 29440, "text": "SQL" }, { "code": null, "e": 29542, "s": 29444, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29608, "s": 29542, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 29623, "s": 29608, "text": "SQL | Subquery" }, { "code": null, "e": 29680, "s": 29623, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 29712, "s": 29680, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 29790, "s": 29712, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 29807, "s": 29790, "text": "SQL using Python" }, { "code": null, "e": 29843, "s": 29807, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 29909, "s": 29843, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 29971, "s": 29909, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Python program to find the type of IP Address using Regex - GeeksforGeeks
02 Sep, 2021 Prerequisite: Python Regex Given an IP address as input, write a Python program to find the type of IP address i.e. either IPv4 or IPv6. If the given is neither of them then print neither. Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. IPv4 and IPv6 are internet protocol version 4 and internet protocol version 6, IP version 6 is the new version of Internet Protocol, which is way better than IP version 4 in terms of complexity and efficiency. IPv4 was the primary version brought into action for production within the ARPANET in 1983. IP version four addresses are 32-bit integers which will be expressed in hexadecimal notation. IPv6 was developed by the Internet Engineering Task Force (IETF) to deal with the problem of IP v4 exhaustion. IP v6 is 128-bits address having an address space of 2128, which is way bigger than IPv4. In IPv6 we use Colon-Hexa representation. There are 8 groups and each group represents 2 Bytes. Examples: Input: 192.0.2.126 Output: IPv4 Input: 3001:0da8:75a3:0000:0000:8a2e:0370:7334 Output: IPv6 Input: 36.12.08.20.52 Output: Neither Take the IP address as input. Now, check if this IP address resembles IPv4 type addresses using regex. If yes, then print “IPv4” else check if this IP address resembles IPv6 type addresses using regex. If yes, then print “IPv6”. If the address doesn’t resemble any of the above types then we will print “Neither”. Below is the implementation of the above approach: Python3 # Python program to find the type of Ip address # re module provides support# for regular expressionsimport re # Make a regular expression# for validating an Ipv4ipv4 = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$''' # Make a regular expression# for validating an Ipv6ipv6 = '''(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| ([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:) {1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1 ,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4} :){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{ 1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA -F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a -fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0 -9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0, 4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1} :){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9 ])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0 -9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4] |1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4] |1{0,1}[0-9]){0,1}[0-9]))''' # Define a function for finding# the type of Ip addressdef find(Ip): # pass the regular expression # and the string in search() method if re.search(ipv4, Ip): print("IPv4") elif re.search(ipv6, Ip): print("IPv6") else: print("Neither") # Driver Code if __name__ == '__main__' : # Enter the Ip address Ip = "192.0.2.126" # calling run function find(Ip) Ip = "3001:0da8:75a3:0000:0000:8a2e:0370:7334" find(Ip) Ip = "36.12.08.20.52" find(Ip) Output: IPv4 IPv6 Neither simmytarika5 Python Regex-programs python-regex Technical Scripter 2020 Python Python Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Sep, 2021" }, { "code": null, "e": 25564, "s": 25537, "text": "Prerequisite: Python Regex" }, { "code": null, "e": 25726, "s": 25564, "text": "Given an IP address as input, write a Python program to find the type of IP address i.e. either IPv4 or IPv6. If the given is neither of them then print neither." }, { "code": null, "e": 26066, "s": 25726, "text": "Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. IPv4 and IPv6 are internet protocol version 4 and internet protocol version 6, IP version 6 is the new version of Internet Protocol, which is way better than IP version 4 in terms of complexity and efficiency." }, { "code": null, "e": 26253, "s": 26066, "text": "IPv4 was the primary version brought into action for production within the ARPANET in 1983. IP version four addresses are 32-bit integers which will be expressed in hexadecimal notation." }, { "code": null, "e": 26550, "s": 26253, "text": "IPv6 was developed by the Internet Engineering Task Force (IETF) to deal with the problem of IP v4 exhaustion. IP v6 is 128-bits address having an address space of 2128, which is way bigger than IPv4. In IPv6 we use Colon-Hexa representation. There are 8 groups and each group represents 2 Bytes." }, { "code": null, "e": 26560, "s": 26550, "text": "Examples:" }, { "code": null, "e": 26692, "s": 26560, "text": "Input: 192.0.2.126\nOutput: IPv4\n\nInput: 3001:0da8:75a3:0000:0000:8a2e:0370:7334\nOutput: IPv6\n\nInput: 36.12.08.20.52\nOutput: Neither" }, { "code": null, "e": 26722, "s": 26692, "text": "Take the IP address as input." }, { "code": null, "e": 26795, "s": 26722, "text": "Now, check if this IP address resembles IPv4 type addresses using regex." }, { "code": null, "e": 26894, "s": 26795, "text": "If yes, then print “IPv4” else check if this IP address resembles IPv6 type addresses using regex." }, { "code": null, "e": 26921, "s": 26894, "text": "If yes, then print “IPv6”." }, { "code": null, "e": 27006, "s": 26921, "text": "If the address doesn’t resemble any of the above types then we will print “Neither”." }, { "code": null, "e": 27057, "s": 27006, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27065, "s": 27057, "text": "Python3" }, { "code": "# Python program to find the type of Ip address # re module provides support# for regular expressionsimport re # Make a regular expression# for validating an Ipv4ipv4 = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$''' # Make a regular expression# for validating an Ipv6ipv6 = '''(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| ([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:) {1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1 ,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4} :){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{ 1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA -F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a -fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0 -9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0, 4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1} :){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9 ])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0 -9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4] |1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4] |1{0,1}[0-9]){0,1}[0-9]))''' # Define a function for finding# the type of Ip addressdef find(Ip): # pass the regular expression # and the string in search() method if re.search(ipv4, Ip): print(\"IPv4\") elif re.search(ipv6, Ip): print(\"IPv6\") else: print(\"Neither\") # Driver Code if __name__ == '__main__' : # Enter the Ip address Ip = \"192.0.2.126\" # calling run function find(Ip) Ip = \"3001:0da8:75a3:0000:0000:8a2e:0370:7334\" find(Ip) Ip = \"36.12.08.20.52\" find(Ip)", "e": 28802, "s": 27065, "text": null }, { "code": null, "e": 28810, "s": 28802, "text": "Output:" }, { "code": null, "e": 28828, "s": 28810, "text": "IPv4\nIPv6\nNeither" }, { "code": null, "e": 28841, "s": 28828, "text": "simmytarika5" }, { "code": null, "e": 28863, "s": 28841, "text": "Python Regex-programs" }, { "code": null, "e": 28876, "s": 28863, "text": "python-regex" }, { "code": null, "e": 28900, "s": 28876, "text": "Technical Scripter 2020" }, { "code": null, "e": 28907, "s": 28900, "text": "Python" }, { "code": null, "e": 28923, "s": 28907, "text": "Python Programs" }, { "code": null, "e": 28942, "s": 28923, "text": "Technical Scripter" }, { "code": null, "e": 29040, "s": 28942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29072, "s": 29040, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29114, "s": 29072, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29156, "s": 29114, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29183, "s": 29156, "text": "Python Classes and Objects" }, { "code": null, "e": 29239, "s": 29183, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29261, "s": 29239, "text": "Defaultdict in Python" }, { "code": null, "e": 29300, "s": 29261, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29346, "s": 29300, "text": "Python | Split string into list of characters" }, { "code": null, "e": 29384, "s": 29346, "text": "Python | Convert a list to dictionary" } ]
Bootstrapping in R Programming - GeeksforGeeks
16 Dec, 2021 Bootstrapping is a technique used in inferential statistics that work on building random samples of single datasets again and again. Bootstrapping allows calculating measures such as mean, median, mode, confidence intervals, etc. of the sampling. Select the number of bootstrap samples. Select the size of each sample. For each sample, if the size of the sample is less than the chosen sample, then select a random observation from the dataset and add it to the sample. Measure the statistic on the sample. Measure the mean of all calculated sample values. There are 2 methods of bootstrapping: Residual Resampling: This method is also called as model-based resampling. This method assumes that model is correct and errors are independent and distributed identically. After each resampling, variables are redefined and new variables are used to measure the new dependent variables. Bootstrap Pairs: In this method, dependent and independent variables are used together as pairs for sampling. Confidence Interval (CI) is a type of computational value calculated on sample data in statistics. It produces a range of values or an interval where the true value lies for sure. There are 5 types of confidence intervals in bootstrapping as follows: Basic: It is also known as Reverse Percentile Interval and is generated using quantiles of bootstrap data distribution. Mathematically, where,represents confidence interval, mostly represents bootstrapped coefficients represents percentile of bootstrapped coefficients Normal: Normal CI is mathematically given as, where, represents a value from dataset t b is the bias of bootstrap estimate i.e., represents quantile of bootstrap distribution represents standard error of Stud: In studentized CI, data is normalized with center at 0 and standard deviation 1 correcting the skew of distribution. Perc – Percentile CI is similar to basic CI but with different formula, BCa: This method adjusts for both bias and skewness but can be unstable when outliers are extreme. Mathematically, The syntax to perform bootstrapping in R programming is as follows: Syntax: boot(data, statistic, R) Parameters: data represents dataset statistic represents statistic functions to be performed on dataset R represents number of samples To learn about more optional arguments of boot() function, use below command: help("boot") Example: R # Library required for boot() functioninstall.packages("boot") # Load the librarylibrary(boot) # Creating a function to pass into boot() functionbootFunc <- function(data, i){df <- data[i, ]c(cor(df[, 2], df[, 3]), median(df[, 2]), mean(df[, 1]))} b <- boot(mtcars, bootFunc, R = 100) print(b) # Show all CI valuesboot.ci(b, index = 1) Output: ORDINARY NONPARAMETRIC BOOTSTRAP Call: boot(data = mtcars, statistic = bootFunc, R = 100) Bootstrap Statistics : original bias std. error t1* 0.9020329 -0.002195625 0.02104139 t2* 6.0000000 0.340000000 0.85540468 t3* 20.0906250 -0.110812500 0.96052824 BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS Based on 100 bootstrap replicates CALL : boot.ci(boot.out = b, index = 1) Intervals : Level Normal Basic 95% ( 0.8592, 0.9375 ) ( 0.8612, 0.9507 ) Level Percentile BCa 95% ( 0.8534, 0.9429 ) ( 0.8279, 0.9280 ) Calculations and Intervals on Original Scale Some basic intervals may be unstable Some percentile intervals may be unstable Warning : BCa Intervals used Extreme Quantiles Some BCa intervals may be unstable Warning messages: 1: In boot.ci(b, index = 1) : bootstrap variances needed for studentized intervals 2: In norm.inter(t, adj.alpha) : extreme order statistics used as endpoints kumar_satyam R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Convert Factor to Numeric and Numeric to Factor in R Programming Group by function in R using Dplyr How to Change Axis Scales in R Plots?
[ { "code": null, "e": 30289, "s": 30261, "text": "\n16 Dec, 2021" }, { "code": null, "e": 30537, "s": 30289, "text": "Bootstrapping is a technique used in inferential statistics that work on building random samples of single datasets again and again. Bootstrapping allows calculating measures such as mean, median, mode, confidence intervals, etc. of the sampling. " }, { "code": null, "e": 30577, "s": 30537, "text": "Select the number of bootstrap samples." }, { "code": null, "e": 30609, "s": 30577, "text": "Select the size of each sample." }, { "code": null, "e": 30760, "s": 30609, "text": "For each sample, if the size of the sample is less than the chosen sample, then select a random observation from the dataset and add it to the sample." }, { "code": null, "e": 30797, "s": 30760, "text": "Measure the statistic on the sample." }, { "code": null, "e": 30847, "s": 30797, "text": "Measure the mean of all calculated sample values." }, { "code": null, "e": 30886, "s": 30847, "text": "There are 2 methods of bootstrapping: " }, { "code": null, "e": 31173, "s": 30886, "text": "Residual Resampling: This method is also called as model-based resampling. This method assumes that model is correct and errors are independent and distributed identically. After each resampling, variables are redefined and new variables are used to measure the new dependent variables." }, { "code": null, "e": 31283, "s": 31173, "text": "Bootstrap Pairs: In this method, dependent and independent variables are used together as pairs for sampling." }, { "code": null, "e": 31535, "s": 31283, "text": "Confidence Interval (CI) is a type of computational value calculated on sample data in statistics. It produces a range of values or an interval where the true value lies for sure. There are 5 types of confidence intervals in bootstrapping as follows: " }, { "code": null, "e": 31671, "s": 31535, "text": "Basic: It is also known as Reverse Percentile Interval and is generated using quantiles of bootstrap data distribution. Mathematically," }, { "code": null, "e": 31805, "s": 31671, "text": "where,represents confidence interval, mostly represents bootstrapped coefficients represents percentile of bootstrapped coefficients " }, { "code": null, "e": 31851, "s": 31805, "text": "Normal: Normal CI is mathematically given as," }, { "code": null, "e": 31858, "s": 31851, "text": "where," }, { "code": null, "e": 31936, "s": 31858, "text": "represents a value from dataset t b is the bias of bootstrap estimate i.e., " }, { "code": null, "e": 32011, "s": 31936, "text": "represents quantile of bootstrap distribution represents standard error of" }, { "code": null, "e": 32134, "s": 32011, "text": "Stud: In studentized CI, data is normalized with center at 0 and standard deviation 1 correcting the skew of distribution." }, { "code": null, "e": 32206, "s": 32134, "text": "Perc – Percentile CI is similar to basic CI but with different formula," }, { "code": null, "e": 32321, "s": 32206, "text": "BCa: This method adjusts for both bias and skewness but can be unstable when outliers are extreme. Mathematically," }, { "code": null, "e": 32389, "s": 32321, "text": "The syntax to perform bootstrapping in R programming is as follows:" }, { "code": null, "e": 32422, "s": 32389, "text": "Syntax: boot(data, statistic, R)" }, { "code": null, "e": 32435, "s": 32422, "text": "Parameters: " }, { "code": null, "e": 32459, "s": 32435, "text": "data represents dataset" }, { "code": null, "e": 32527, "s": 32459, "text": "statistic represents statistic functions to be performed on dataset" }, { "code": null, "e": 32558, "s": 32527, "text": "R represents number of samples" }, { "code": null, "e": 32636, "s": 32558, "text": "To learn about more optional arguments of boot() function, use below command:" }, { "code": null, "e": 32649, "s": 32636, "text": "help(\"boot\")" }, { "code": null, "e": 32659, "s": 32649, "text": "Example: " }, { "code": null, "e": 32661, "s": 32659, "text": "R" }, { "code": "# Library required for boot() functioninstall.packages(\"boot\") # Load the librarylibrary(boot) # Creating a function to pass into boot() functionbootFunc <- function(data, i){df <- data[i, ]c(cor(df[, 2], df[, 3]), median(df[, 2]), mean(df[, 1]))} b <- boot(mtcars, bootFunc, R = 100) print(b) # Show all CI valuesboot.ci(b, index = 1)", "e": 33003, "s": 32661, "text": null }, { "code": null, "e": 33012, "s": 33003, "text": "Output: " }, { "code": null, "e": 34002, "s": 33012, "text": "ORDINARY NONPARAMETRIC BOOTSTRAP\nCall:\nboot(data = mtcars, statistic = bootFunc, R = 100)\n\n\nBootstrap Statistics :\n original bias std. error\nt1* 0.9020329 -0.002195625 0.02104139\nt2* 6.0000000 0.340000000 0.85540468\nt3* 20.0906250 -0.110812500 0.96052824\n\n\nBOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS\nBased on 100 bootstrap replicates\n\nCALL : \nboot.ci(boot.out = b, index = 1)\n\nIntervals : \nLevel Normal Basic \n95% ( 0.8592, 0.9375 ) ( 0.8612, 0.9507 ) \n\nLevel Percentile BCa \n95% ( 0.8534, 0.9429 ) ( 0.8279, 0.9280 ) \nCalculations and Intervals on Original Scale\nSome basic intervals may be unstable\nSome percentile intervals may be unstable\nWarning : BCa Intervals used Extreme Quantiles\nSome BCa intervals may be unstable\nWarning messages:\n1: In boot.ci(b, index = 1) :\n bootstrap variances needed for studentized intervals\n2: In norm.inter(t, adj.alpha) :\n extreme order statistics used as endpoints" }, { "code": null, "e": 34015, "s": 34002, "text": "kumar_satyam" }, { "code": null, "e": 34026, "s": 34015, "text": "R Language" }, { "code": null, "e": 34124, "s": 34026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34169, "s": 34124, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 34227, "s": 34169, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 34279, "s": 34227, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 34311, "s": 34279, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 34374, "s": 34311, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 34418, "s": 34374, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 34470, "s": 34418, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 34535, "s": 34470, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 34570, "s": 34535, "text": "Group by function in R using Dplyr" } ]
Python PIL | ImageChops.subtract() method - GeeksforGeeks
29 Jun, 2019 PIL.ImageChops.subtract() method subtracts two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. At least one of the images must have mode “1”. Syntax: PIL.ImageChops.subtract(image1, image2, scale=1.0, offset=0) Parameters: image1: first image image2: second image scale: numeric value offset: numeric value Return Type: Image Image1: Image2: # Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 object im1 = Image.open(r"C:\Users\sadow984\Desktop\a2.PNG") # creating a image2 object im2 = Image.open(r"C:\Users\sadow984\Desktop\x5.PNG") # applying subtract method im3 = ImageChops.add(im1, im2, scale = 1.0, offset = 2) im3.show() Output: # Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 object im1 = Image.open(r"C:\Users\sadow984\Desktop\a2.PNG") # creating a image2 object im2 = Image.open(r"C:\Users\sadow984\Desktop\x5.PNG") # applying subtract method im3 = ImageChops.add(im1, im2, scale = 1.0, offset = 2) im3.show() Output: Image-Processing Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25685, "s": 25657, "text": "\n29 Jun, 2019" }, { "code": null, "e": 25893, "s": 25685, "text": "PIL.ImageChops.subtract() method subtracts two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0. At least one of the images must have mode “1”." }, { "code": null, "e": 26080, "s": 25893, "text": "Syntax: PIL.ImageChops.subtract(image1, image2, scale=1.0, offset=0)\n\nParameters:\nimage1: first image\nimage2: second image\nscale: numeric value\noffset: numeric value\n\nReturn Type: Image\n" }, { "code": null, "e": 26088, "s": 26080, "text": "Image1:" }, { "code": null, "e": 26096, "s": 26088, "text": "Image2:" }, { "code": "# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 object im1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\a2.PNG\") # creating a image2 object im2 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\x5.PNG\") # applying subtract method im3 = ImageChops.add(im1, im2, scale = 1.0, offset = 2) im3.show() ", "e": 26461, "s": 26096, "text": null }, { "code": null, "e": 26469, "s": 26461, "text": "Output:" }, { "code": "# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 object im1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\a2.PNG\") # creating a image2 object im2 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\x5.PNG\") # applying subtract method im3 = ImageChops.add(im1, im2, scale = 1.0, offset = 2) im3.show() ", "e": 26834, "s": 26469, "text": null }, { "code": null, "e": 26842, "s": 26834, "text": "Output:" }, { "code": null, "e": 26859, "s": 26842, "text": "Image-Processing" }, { "code": null, "e": 26870, "s": 26859, "text": "Python-pil" }, { "code": null, "e": 26877, "s": 26870, "text": "Python" }, { "code": null, "e": 26975, "s": 26877, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26993, "s": 26975, "text": "Python Dictionary" }, { "code": null, "e": 27028, "s": 26993, "text": "Read a file line by line in Python" }, { "code": null, "e": 27060, "s": 27028, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27082, "s": 27060, "text": "Enumerate() in Python" }, { "code": null, "e": 27124, "s": 27082, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27154, "s": 27124, "text": "Iterate over a list in Python" }, { "code": null, "e": 27180, "s": 27154, "text": "Python String | replace()" }, { "code": null, "e": 27209, "s": 27180, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27253, "s": 27209, "text": "Reading and Writing to text files in Python" } ]
zlib.adler32() in Python - GeeksforGeeks
23 Mar, 2020 With the help of zlib.adler32() method, we can compute the checksum for adler32 to a particular data. It will give 32-bit integer value as a result by using zlib.adler32() method. Syntax : zlib.adler32(s)Return : Return the unsigned 32-bit checksum integer. Example #1 :In this example we can see that by using zlib.adler32() method, we are able to compute the unsigned 32-bit checksum for given data by using this method. # import zlib and adler32import zlib s = b'I love python, Hello world' # using zlib.adler32() methodt = zlib.adler32(s) print(t) Output : 2073102698 Example #2 : # import zlib and adler32import zlib s = b'Hello GeeksForGeeks' # using zlib.adler32() methodt = zlib.adler32(s) print(t) Output : 1156384538 python-zlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n23 Mar, 2020" }, { "code": null, "e": 25717, "s": 25537, "text": "With the help of zlib.adler32() method, we can compute the checksum for adler32 to a particular data. It will give 32-bit integer value as a result by using zlib.adler32() method." }, { "code": null, "e": 25795, "s": 25717, "text": "Syntax : zlib.adler32(s)Return : Return the unsigned 32-bit checksum integer." }, { "code": null, "e": 25960, "s": 25795, "text": "Example #1 :In this example we can see that by using zlib.adler32() method, we are able to compute the unsigned 32-bit checksum for given data by using this method." }, { "code": "# import zlib and adler32import zlib s = b'I love python, Hello world' # using zlib.adler32() methodt = zlib.adler32(s) print(t)", "e": 26092, "s": 25960, "text": null }, { "code": null, "e": 26101, "s": 26092, "text": "Output :" }, { "code": null, "e": 26112, "s": 26101, "text": "2073102698" }, { "code": null, "e": 26125, "s": 26112, "text": "Example #2 :" }, { "code": "# import zlib and adler32import zlib s = b'Hello GeeksForGeeks' # using zlib.adler32() methodt = zlib.adler32(s) print(t)", "e": 26250, "s": 26125, "text": null }, { "code": null, "e": 26259, "s": 26250, "text": "Output :" }, { "code": null, "e": 26270, "s": 26259, "text": "1156384538" }, { "code": null, "e": 26282, "s": 26270, "text": "python-zlib" }, { "code": null, "e": 26289, "s": 26282, "text": "Python" }, { "code": null, "e": 26387, "s": 26289, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26419, "s": 26387, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26461, "s": 26419, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26503, "s": 26461, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26530, "s": 26503, "text": "Python Classes and Objects" }, { "code": null, "e": 26586, "s": 26530, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26625, "s": 26586, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26647, "s": 26625, "text": "Defaultdict in Python" }, { "code": null, "e": 26678, "s": 26647, "text": "Python | os.path.join() method" }, { "code": null, "e": 26707, "s": 26678, "text": "Create a directory in Python" } ]
PyQt5 QSpinBox - Setting Special Value Text - GeeksforGeeks
28 May, 2020 In this article we will see how we can set the special value text to the spin box. Setting special value text to spin box will display this special text instead of a numeric value whenever the current value is equal to minimum value. Typical use of this is to indicate that this choice has a special (default) meaning. In order to do this we use setSpecialValueText method with the spin box object. Syntax : spin_box.setSpecialValueText(text) Argument : It takes string as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 999999) # setting prefix to spin self.spin.setPrefix("PREFIX ") # setting suffix to spin self.spin.setSuffix(" SUFFIX") # setting special value text self.spin.setSpecialValueText("Geeks for Geeks") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-SpinBox Python-gui Python-PyQt 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 Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 May, 2020" }, { "code": null, "e": 25856, "s": 25537, "text": "In this article we will see how we can set the special value text to the spin box. Setting special value text to spin box will display this special text instead of a numeric value whenever the current value is equal to minimum value. Typical use of this is to indicate that this choice has a special (default) meaning." }, { "code": null, "e": 25936, "s": 25856, "text": "In order to do this we use setSpecialValueText method with the spin box object." }, { "code": null, "e": 25980, "s": 25936, "text": "Syntax : spin_box.setSpecialValueText(text)" }, { "code": null, "e": 26019, "s": 25980, "text": "Argument : It takes string as argument" }, { "code": null, "e": 26044, "s": 26019, "text": "Return : It returns None" }, { "code": null, "e": 26072, "s": 26044, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 999999) # setting prefix to spin self.spin.setPrefix(\"PREFIX \") # setting suffix to spin self.spin.setSuffix(\" SUFFIX\") # setting special value text self.spin.setSpecialValueText(\"Geeks for Geeks\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27204, "s": 26072, "text": null }, { "code": null, "e": 27213, "s": 27204, "text": "Output :" }, { "code": null, "e": 27233, "s": 27213, "text": "Python PyQt-SpinBox" }, { "code": null, "e": 27244, "s": 27233, "text": "Python-gui" }, { "code": null, "e": 27256, "s": 27244, "text": "Python-PyQt" }, { "code": null, "e": 27263, "s": 27256, "text": "Python" }, { "code": null, "e": 27361, "s": 27263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27393, "s": 27361, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27435, "s": 27393, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27477, "s": 27435, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27533, "s": 27477, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27560, "s": 27533, "text": "Python Classes and Objects" }, { "code": null, "e": 27599, "s": 27560, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27630, "s": 27599, "text": "Python | os.path.join() method" }, { "code": null, "e": 27659, "s": 27630, "text": "Create a directory in Python" }, { "code": null, "e": 27681, "s": 27659, "text": "Defaultdict in Python" } ]
ReactJS UI Ant Design Slider Component - GeeksforGeeks
21 May, 2021 Ant Design Library has this component pre-built, and it is very easy to integrate as well. Slider Component to used when the users want to make selections from a range of values. We can use the following approach in ReactJS to use the Ant Design Slider Component. Slider Methods: blur(): This method is used to remove the focus from the element. focus(): This method is used to get the focus on the element. Slider Props: autoFocus: It is used to get the focus when the component is mounted. defaultValue: It is used as the default value of the slider. disabled: It is used to disable the slider. dots: It is used to indicate whether the thumb can drag over tick only or not. getTooltipPopupContainer: It is used for the DOM container of the Tooltip. included: It is used to make an effect when marks not null. marks: It is used to define the tick mark of the slider. max: It is used to denote the maximum value the slider can slide. min: It is used to denote the minimum value the slider can slide. range: It is used for the dual thumb mode. reverse: It is used to reverse the component. step: It is used to indicate the granularity the slider can step through values. tipFormatter: It is used for the slider so that it will pass its value to tipFormatter. tooltipPlacement: It is used to set Tooltip display position. tooltipVisible: It is used to indicate whether to show Tooltip or not. value: It is used to denote the value of the slider. vertical: It is used to indicate whether to set the slider vertical or not. onAfterChange: It is a callback function that is triggered when onmouseup event is fired. onChange: It is a callback function that is triggered when the user changes the slider’s value. Range Props: draggableTrack: It is used to indicate whether the range track can be drag or not. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd Step 3: After creating the ReactJS application, Install the required module using the following command: npm install antd Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React, { useState } from 'react'import "antd/dist/antd.css";import { Slider } from 'antd'; export default function App() { // State to hold our current value const [currentValue, setCurrentValue] = useState(0) return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Slider Component</h4> <Slider defaultValue={0} disabled={false} max={100} onChange={(value)=> { setCurrentValue(value) }}/> Slider Value: {currentValue} </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://ant.design/components/slider/ ReactJS-Ant Design ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 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": 35483, "s": 35455, "text": "\n21 May, 2021" }, { "code": null, "e": 35747, "s": 35483, "text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. Slider Component to used when the users want to make selections from a range of values. We can use the following approach in ReactJS to use the Ant Design Slider Component." }, { "code": null, "e": 35763, "s": 35747, "text": "Slider Methods:" }, { "code": null, "e": 35829, "s": 35763, "text": "blur(): This method is used to remove the focus from the element." }, { "code": null, "e": 35891, "s": 35829, "text": "focus(): This method is used to get the focus on the element." }, { "code": null, "e": 35905, "s": 35891, "text": "Slider Props:" }, { "code": null, "e": 35975, "s": 35905, "text": "autoFocus: It is used to get the focus when the component is mounted." }, { "code": null, "e": 36036, "s": 35975, "text": "defaultValue: It is used as the default value of the slider." }, { "code": null, "e": 36080, "s": 36036, "text": "disabled: It is used to disable the slider." }, { "code": null, "e": 36159, "s": 36080, "text": "dots: It is used to indicate whether the thumb can drag over tick only or not." }, { "code": null, "e": 36234, "s": 36159, "text": "getTooltipPopupContainer: It is used for the DOM container of the Tooltip." }, { "code": null, "e": 36294, "s": 36234, "text": "included: It is used to make an effect when marks not null." }, { "code": null, "e": 36351, "s": 36294, "text": "marks: It is used to define the tick mark of the slider." }, { "code": null, "e": 36417, "s": 36351, "text": "max: It is used to denote the maximum value the slider can slide." }, { "code": null, "e": 36483, "s": 36417, "text": "min: It is used to denote the minimum value the slider can slide." }, { "code": null, "e": 36526, "s": 36483, "text": "range: It is used for the dual thumb mode." }, { "code": null, "e": 36572, "s": 36526, "text": "reverse: It is used to reverse the component." }, { "code": null, "e": 36653, "s": 36572, "text": "step: It is used to indicate the granularity the slider can step through values." }, { "code": null, "e": 36741, "s": 36653, "text": "tipFormatter: It is used for the slider so that it will pass its value to tipFormatter." }, { "code": null, "e": 36803, "s": 36741, "text": "tooltipPlacement: It is used to set Tooltip display position." }, { "code": null, "e": 36874, "s": 36803, "text": "tooltipVisible: It is used to indicate whether to show Tooltip or not." }, { "code": null, "e": 36927, "s": 36874, "text": "value: It is used to denote the value of the slider." }, { "code": null, "e": 37003, "s": 36927, "text": "vertical: It is used to indicate whether to set the slider vertical or not." }, { "code": null, "e": 37093, "s": 37003, "text": "onAfterChange: It is a callback function that is triggered when onmouseup event is fired." }, { "code": null, "e": 37189, "s": 37093, "text": "onChange: It is a callback function that is triggered when the user changes the slider’s value." }, { "code": null, "e": 37202, "s": 37189, "text": "Range Props:" }, { "code": null, "e": 37285, "s": 37202, "text": "draggableTrack: It is used to indicate whether the range track can be drag or not." }, { "code": null, "e": 37335, "s": 37285, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 37430, "s": 37335, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 37494, "s": 37430, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 37526, "s": 37494, "text": "npx create-react-app foldername" }, { "code": null, "e": 37639, "s": 37526, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 37739, "s": 37639, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 37753, "s": 37739, "text": "cd foldername" }, { "code": null, "e": 37874, "s": 37753, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd" }, { "code": null, "e": 37979, "s": 37874, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 37996, "s": 37979, "text": "npm install antd" }, { "code": null, "e": 38048, "s": 37996, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 38066, "s": 38048, "text": "Project Structure" }, { "code": null, "e": 38196, "s": 38066, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 38207, "s": 38196, "text": "Javascript" }, { "code": "import React, { useState } from 'react'import \"antd/dist/antd.css\";import { Slider } from 'antd'; export default function App() { // State to hold our current value const [currentValue, setCurrentValue] = useState(0) return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Slider Component</h4> <Slider defaultValue={0} disabled={false} max={100} onChange={(value)=> { setCurrentValue(value) }}/> Slider Value: {currentValue} </div> );}", "e": 38730, "s": 38207, "text": null }, { "code": null, "e": 38843, "s": 38730, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 38853, "s": 38843, "text": "npm start" }, { "code": null, "e": 38952, "s": 38853, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 39001, "s": 38952, "text": "Reference: https://ant.design/components/slider/" }, { "code": null, "e": 39020, "s": 39001, "text": "ReactJS-Ant Design" }, { "code": null, "e": 39028, "s": 39020, "text": "ReactJS" }, { "code": null, "e": 39045, "s": 39028, "text": "Web Technologies" }, { "code": null, "e": 39143, "s": 39045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39186, "s": 39143, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 39231, "s": 39186, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 39296, "s": 39231, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 39364, "s": 39296, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 39394, "s": 39364, "text": "ReactJS Functional Components" }, { "code": null, "e": 39434, "s": 39394, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 39467, "s": 39434, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39512, "s": 39467, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39555, "s": 39512, "text": "How to fetch data from an API in ReactJS ?" } ]
Construct a Binary Search Tree from given postorder - GeeksforGeeks
02 Mar, 2022 Given postorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned. 10 / \ 5 40 / \ \ 1 7 50 Method 1 ( O(n^2) time complexity ) The last element of postorder traversal is always root. We first construct the root. Then we find the index of last element which is smaller than root. Let the index be ‘i’. The values between 0 and ‘i’ are part of left subtree, and the values between ‘i+1’ and ‘n-2’ are part of right subtree. Divide given post[] at index “i” and recur for left and right sub-trees. For example in {1, 7, 5, 50, 40, 10}, 10 is the last element, so we make it root. Now we look for the last element smaller than 10, we find 5. So we know the structure of BST is as following. 10 / \ / \ {1, 7, 5} {50, 40} We recursively follow above steps for subarrays {1, 7, 5} and {40, 50}, and get the complete tree.Method 2 ( O(n) time complexity ) The trick is to set a range {min .. max} for every node. Initialize the range as {INT_MIN .. INT_MAX}. The last node will definitely be in range, so create root node. To construct the left subtree, set the range as {INT_MIN ...root->data}. If a values is in the range {INT_MIN .. root->data}, the values is part part of left subtree. To construct the right subtree, set the range as {root->data .. INT_MAX}.Following code is used to generate the exact Binary Search Tree of a given post order traversal. C++ C Java Python3 C# Javascript /* A O(n) program for construction ofBST from postorder traversal */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child and apointer to right child */struct node{ int data; struct node *left, *right;}; // A utility function to create a nodestruct node* newNode (int data){ struct node* temp =(struct node *) malloc(sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct// BST from post[]. postIndex is used// to keep track of index in post[].struct node* constructTreeUtil(int post[], int* postIndex, int key, int min, int max, int size){ // Base case if (*postIndex < 0) return NULL; struct node* root = NULL; // If current element of post[] is // in range, then only it is part // of current subtree if (key > min && key < max) { // Allocate memory for root of this // subtree and decrement *postIndex root = newNode(key); *postIndex = *postIndex - 1; if (*postIndex >= 0) { // All nodes which are in range {key..max} // will go in right subtree, and first such // node will be root of right subtree. root->right = constructTreeUtil(post, postIndex, post[*postIndex], key, max, size ); // Construct the subtree under root // All nodes which are in range {min .. key} // will go in left subtree, and first such // node will be root of left subtree. root->left = constructTreeUtil(post, postIndex, post[*postIndex], min, key, size ); } } return root;} // The main function to construct BST// from given postorder traversal.// This function mainly uses constructTreeUtil()struct node *constructTree (int post[], int size){ int postIndex = size-1; return constructTreeUtil(post, &postIndex, post[postIndex], INT_MIN, INT_MAX, size);} // A utility function to print// inorder traversal of a Binary Treevoid printInorder (struct node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << " "; printInorder(node->right);} // Driver Codeint main (){ int post[] = {1, 7, 5, 50, 40, 10}; int size = sizeof(post) / sizeof(post[0]); struct node *root = constructTree(post, size); cout << "Inorder traversal of " << "the constructed tree: \n"; printInorder(root); return 0;} // This code is contributed// by Akanksha Rai /* A O(n) program for construction of BST from postorder traversal */#include <stdio.h>#include <stdlib.h>#include <limits.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // A utility function to create a nodestruct node* newNode (int data){ struct node* temp = (struct node *) malloc( sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct BST from post[].// postIndex is used to keep track of index in post[].struct node* constructTreeUtil(int post[], int* postIndex, int key, int min, int max, int size){ // Base case if (*postIndex < 0) return NULL; struct node* root = NULL; // If current element of post[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this subtree and decrement // *postIndex root = newNode(key); *postIndex = *postIndex - 1; if (*postIndex >= 0) { // All nodes which are in range {key..max} will go in right // subtree, and first such node will be root of right subtree. root->right = constructTreeUtil(post, postIndex, post[*postIndex], key, max, size ); // Construct the subtree under root // All nodes which are in range {min .. key} will go in left // subtree, and first such node will be root of left subtree. root->left = constructTreeUtil(post, postIndex, post[*postIndex], min, key, size ); } } return root;} // The main function to construct BST from given postorder// traversal. This function mainly uses constructTreeUtil()struct node *constructTree (int post[], int size){ int postIndex = size-1; return constructTreeUtil(post, &postIndex, post[postIndex], INT_MIN, INT_MAX, size);} // A utility function to print inorder traversal of a Binary Treevoid printInorder (struct node* node){ if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right);} // Driver program to test above functionsint main (){ int post[] = {1, 7, 5, 50, 40, 10}; int size = sizeof(post) / sizeof(post[0]); struct node *root = constructTree(post, size); printf("Inorder traversal of the constructed tree: \n"); printInorder(root); return 0;} /* A O(n) program for construction of BST from postorder traversal */ /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int data) { this.data = data; left = right = null; }} // Class containing variable that keeps a track of overall// calculated postindexclass Index{ int postindex = 0;} class BinaryTree{ // A recursive function to construct BST from post[]. // postIndex is used to keep track of index in post[]. Node constructTreeUtil(int post[], Index postIndex, int key, int min, int max, int size) { // Base case if (postIndex.postindex < 0) return null; Node root = null; // If current element of post[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this subtree and decrement // *postIndex root = new Node(key); postIndex.postindex = postIndex.postindex - 1; if (postIndex.postindex >= 0) { // All nodes which are in range {key..max} will go in // right subtree, and first such node will be root of right // subtree root.right = constructTreeUtil(post, postIndex, post[postIndex.postindex],key, max, size); // Construct the subtree under root // All nodes which are in range {min .. key} will go in left // subtree, and first such node will be root of left subtree. root.left = constructTreeUtil(post, postIndex, post[postIndex.postindex],min, key, size); } } return root; } // The main function to construct BST from given postorder // traversal. This function mainly uses constructTreeUtil() Node constructTree(int post[], int size) { Index index = new Index(); index.postindex = size - 1; return constructTreeUtil(post, index, post[index.postindex], Integer.MIN_VALUE, Integer.MAX_VALUE, size); } // A utility function to print inorder traversal of a Binary Tree void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(node.data + " "); printInorder(node.right); } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int post[] = new int[]{1, 7, 5, 50, 40, 10}; int size = post.length; Node root = tree.constructTree(post, size); System.out.println("Inorder traversal of the constructed tree:"); tree.printInorder(root); }} // This code has been contributed by Mayank Jaiswal # A O(n) program for construction of BST# from postorder traversalINT_MIN = -2**31INT_MAX = 2**31 # A binary tree node has data, pointer to# left child and a pointer to right child# A utility function to create a nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # A recursive function to construct# BST from post[]. postIndex is used# to keep track of index in post[].def constructTreeUtil(post, postIndex, key, min, max, size): # Base case if (postIndex[0] < 0): return None root = None # If current element of post[] is # in range, then only it is part # of current subtree if (key > min and key < max) : # Allocate memory for root of this # subtree and decrement *postIndex root = newNode(key) postIndex[0] = postIndex[0] - 1 if (postIndex[0] >= 0) : # All nodes which are in range key.. # max will go in right subtree, and # first such node will be root of # right subtree. root.right = constructTreeUtil(post, postIndex, post[postIndex[0]], key, max, size ) # Construct the subtree under root # All nodes which are in range min .. # key will go in left subtree, and # first such node will be root of # left subtree. root.left = constructTreeUtil(post, postIndex, post[postIndex[0]], min, key, size ) return root # The main function to construct BST# from given postorder traversal. This# function mainly uses constructTreeUtil()def constructTree (post, size) : postIndex = [size-1] return constructTreeUtil(post, postIndex, post[postIndex[0]], INT_MIN, INT_MAX, size) # A utility function to printInorder# traversal of a Binary Treedef printInorder (node) : if (node == None) : return printInorder(node.left) print(node.data, end = " ") printInorder(node.right) # Driver Codeif __name__ == '__main__': post = [1, 7, 5, 50, 40, 10] size = len(post) root = constructTree(post, size) print("Inorder traversal of the", "constructed tree: ") printInorder(root) # This code is contributed# by SHUBHAMSINGH10 using System;/* A O(n) program forconstruction of BST frompostorder traversal */ /* A binary tree node has data,pointer to left child and a pointer to right child */class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} // Class containing variable// that keeps a track of overall// calculated postindexclass Index{ public int postindex = 0;} public class BinaryTree{ // A recursive function to // construct BST from post[]. // postIndex is used to // keep track of index in post[]. Node constructTreeUtil(int []post, Index postIndex, int key, int min, int max, int size) { // Base case if (postIndex.postindex < 0) return null; Node root = null; // If current element of post[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of // this subtree and decrement *postIndex root = new Node(key); postIndex.postindex = postIndex.postindex - 1; if (postIndex.postindex >= 0) { // All nodes which are in range // {key..max} will go in right subtree, // and first such node will be root of // right subtree root.right = constructTreeUtil(post, postIndex, post[postIndex.postindex], key, max, size); // Construct the subtree under root // All nodes which are in range // {min .. key} will go in left // subtree, and first such node // will be root of left subtree. root.left = constructTreeUtil(post, postIndex, post[postIndex.postindex],min, key, size); } } return root; } // The main function to construct // BST from given postorder traversal. // This function mainly uses constructTreeUtil() Node constructTree(int []post, int size) { Index index = new Index(); index.postindex = size - 1; return constructTreeUtil(post, index, post[index.postindex], int.MinValue, int.MaxValue, size); } // A utility function to print // inorder traversal of a Binary Tree void printInorder(Node node) { if (node == null) return; printInorder(node.left); Console.Write(node.data + " "); printInorder(node.right); } // Driver code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); int []post = new int[]{1, 7, 5, 50, 40, 10}; int size = post.Length; Node root = tree.constructTree(post, size); Console.WriteLine("Inorder traversal of" + "the constructed tree:"); tree.printInorder(root); }} // This code has been contributed by PrinciRaj1992 <script> /* A O(n) program forconstruction of BST frompostorder traversal */ /* A binary tree node has data,pointer to left child and a pointer to right child */ class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } // Class containing variable // that keeps a track of overall // calculated postindex class Index { constructor() { this.postindex = 0; } } class BinaryTree { // A recursive function to // construct BST from post[]. // postIndex is used to // keep track of index in post[]. constructTreeUtil(post, postIndex, key, min, max, size) { // Base case if (postIndex.postindex < 0) return null; var root = null; // If current element of post[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of // this subtree and decrement *postIndex root = new Node(key); postIndex.postindex = postIndex.postindex - 1; if (postIndex.postindex >= 0) { // All nodes which are in range // {key..max} will go in right subtree, // and first such node will be root of // right subtree root.right = this.constructTreeUtil( post, postIndex, post[postIndex.postindex], key, max, size ); // Construct the subtree under root // All nodes which are in range // {min .. key} will go in left // subtree, and first such node // will be root of left subtree. root.left = this.constructTreeUtil( post, postIndex, post[postIndex.postindex], min, key, size ); } } return root; } // The main function to construct // BST from given postorder traversal. // This function mainly uses constructTreeUtil() constructTree(post, size) { var index = new Index(); index.postindex = size - 1; return this.constructTreeUtil( post, index, post[index.postindex], -2147483648, 2147483647, size ); } // A utility function to print // inorder traversal of a Binary Tree printInorder(node) { if (node == null) return; this.printInorder(node.left); document.write(node.data + " "); this.printInorder(node.right); } } // Driver code var tree = new BinaryTree(); var post = [1, 7, 5, 50, 40, 10]; var size = post.length; var root = tree.constructTree(post, size); document.write("Inorder traversal of " + "the constructed tree: <br>"); tree.printInorder(root); </script> Output: Inorder traversal of the constructed tree: 1 5 7 10 40 50 Note that the output to the program will always be a sorted sequence as we are printing the inorder traversal of a Binary Search Tree. This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above princiraj1992 SHUBHAMSINGH10 Akanksha_Rai rdtank himanshuaswalgfg simmytarika5 SAP Labs Binary Search Tree Tree SAP Labs Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Binary Search Tree | DP-24 Red-Black Tree | Set 2 (Insert) Find the node with minimum value in a Binary Search Tree Advantages of BST over Hash Table Difference between Binary Tree and Binary Search Tree Binary Tree | Set 1 (Introduction) Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Write a Program to Find the Maximum Depth or Height of a Tree
[ { "code": null, "e": 26557, "s": 26529, "text": "\n02 Mar, 2022" }, { "code": null, "e": 26773, "s": 26557, "text": "Given postorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned. " }, { "code": null, "e": 26829, "s": 26773, "text": " 10\n / \\\n 5 40\n / \\ \\\n1 7 50" }, { "code": null, "e": 27429, "s": 26831, "text": "Method 1 ( O(n^2) time complexity ) The last element of postorder traversal is always root. We first construct the root. Then we find the index of last element which is smaller than root. Let the index be ‘i’. The values between 0 and ‘i’ are part of left subtree, and the values between ‘i+1’ and ‘n-2’ are part of right subtree. Divide given post[] at index “i” and recur for left and right sub-trees. For example in {1, 7, 5, 50, 40, 10}, 10 is the last element, so we make it root. Now we look for the last element smaller than 10, we find 5. So we know the structure of BST is as following. " }, { "code": null, "e": 27509, "s": 27429, "text": " 10\n / \\\n / \\\n {1, 7, 5} {50, 40}" }, { "code": null, "e": 28147, "s": 27509, "text": "We recursively follow above steps for subarrays {1, 7, 5} and {40, 50}, and get the complete tree.Method 2 ( O(n) time complexity ) The trick is to set a range {min .. max} for every node. Initialize the range as {INT_MIN .. INT_MAX}. The last node will definitely be in range, so create root node. To construct the left subtree, set the range as {INT_MIN ...root->data}. If a values is in the range {INT_MIN .. root->data}, the values is part part of left subtree. To construct the right subtree, set the range as {root->data .. INT_MAX}.Following code is used to generate the exact Binary Search Tree of a given post order traversal. " }, { "code": null, "e": 28151, "s": 28147, "text": "C++" }, { "code": null, "e": 28153, "s": 28151, "text": "C" }, { "code": null, "e": 28158, "s": 28153, "text": "Java" }, { "code": null, "e": 28166, "s": 28158, "text": "Python3" }, { "code": null, "e": 28169, "s": 28166, "text": "C#" }, { "code": null, "e": 28180, "s": 28169, "text": "Javascript" }, { "code": "/* A O(n) program for construction ofBST from postorder traversal */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child and apointer to right child */struct node{ int data; struct node *left, *right;}; // A utility function to create a nodestruct node* newNode (int data){ struct node* temp =(struct node *) malloc(sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct// BST from post[]. postIndex is used// to keep track of index in post[].struct node* constructTreeUtil(int post[], int* postIndex, int key, int min, int max, int size){ // Base case if (*postIndex < 0) return NULL; struct node* root = NULL; // If current element of post[] is // in range, then only it is part // of current subtree if (key > min && key < max) { // Allocate memory for root of this // subtree and decrement *postIndex root = newNode(key); *postIndex = *postIndex - 1; if (*postIndex >= 0) { // All nodes which are in range {key..max} // will go in right subtree, and first such // node will be root of right subtree. root->right = constructTreeUtil(post, postIndex, post[*postIndex], key, max, size ); // Construct the subtree under root // All nodes which are in range {min .. key} // will go in left subtree, and first such // node will be root of left subtree. root->left = constructTreeUtil(post, postIndex, post[*postIndex], min, key, size ); } } return root;} // The main function to construct BST// from given postorder traversal.// This function mainly uses constructTreeUtil()struct node *constructTree (int post[], int size){ int postIndex = size-1; return constructTreeUtil(post, &postIndex, post[postIndex], INT_MIN, INT_MAX, size);} // A utility function to print// inorder traversal of a Binary Treevoid printInorder (struct node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << \" \"; printInorder(node->right);} // Driver Codeint main (){ int post[] = {1, 7, 5, 50, 40, 10}; int size = sizeof(post) / sizeof(post[0]); struct node *root = constructTree(post, size); cout << \"Inorder traversal of \" << \"the constructed tree: \\n\"; printInorder(root); return 0;} // This code is contributed// by Akanksha Rai", "e": 30958, "s": 28180, "text": null }, { "code": "/* A O(n) program for construction of BST from postorder traversal */#include <stdio.h>#include <stdlib.h>#include <limits.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // A utility function to create a nodestruct node* newNode (int data){ struct node* temp = (struct node *) malloc( sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct BST from post[].// postIndex is used to keep track of index in post[].struct node* constructTreeUtil(int post[], int* postIndex, int key, int min, int max, int size){ // Base case if (*postIndex < 0) return NULL; struct node* root = NULL; // If current element of post[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this subtree and decrement // *postIndex root = newNode(key); *postIndex = *postIndex - 1; if (*postIndex >= 0) { // All nodes which are in range {key..max} will go in right // subtree, and first such node will be root of right subtree. root->right = constructTreeUtil(post, postIndex, post[*postIndex], key, max, size ); // Construct the subtree under root // All nodes which are in range {min .. key} will go in left // subtree, and first such node will be root of left subtree. root->left = constructTreeUtil(post, postIndex, post[*postIndex], min, key, size ); } } return root;} // The main function to construct BST from given postorder// traversal. This function mainly uses constructTreeUtil()struct node *constructTree (int post[], int size){ int postIndex = size-1; return constructTreeUtil(post, &postIndex, post[postIndex], INT_MIN, INT_MAX, size);} // A utility function to print inorder traversal of a Binary Treevoid printInorder (struct node* node){ if (node == NULL) return; printInorder(node->left); printf(\"%d \", node->data); printInorder(node->right);} // Driver program to test above functionsint main (){ int post[] = {1, 7, 5, 50, 40, 10}; int size = sizeof(post) / sizeof(post[0]); struct node *root = constructTree(post, size); printf(\"Inorder traversal of the constructed tree: \\n\"); printInorder(root); return 0;}", "e": 33550, "s": 30958, "text": null }, { "code": "/* A O(n) program for construction of BST from postorder traversal */ /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int data) { this.data = data; left = right = null; }} // Class containing variable that keeps a track of overall// calculated postindexclass Index{ int postindex = 0;} class BinaryTree{ // A recursive function to construct BST from post[]. // postIndex is used to keep track of index in post[]. Node constructTreeUtil(int post[], Index postIndex, int key, int min, int max, int size) { // Base case if (postIndex.postindex < 0) return null; Node root = null; // If current element of post[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this subtree and decrement // *postIndex root = new Node(key); postIndex.postindex = postIndex.postindex - 1; if (postIndex.postindex >= 0) { // All nodes which are in range {key..max} will go in // right subtree, and first such node will be root of right // subtree root.right = constructTreeUtil(post, postIndex, post[postIndex.postindex],key, max, size); // Construct the subtree under root // All nodes which are in range {min .. key} will go in left // subtree, and first such node will be root of left subtree. root.left = constructTreeUtil(post, postIndex, post[postIndex.postindex],min, key, size); } } return root; } // The main function to construct BST from given postorder // traversal. This function mainly uses constructTreeUtil() Node constructTree(int post[], int size) { Index index = new Index(); index.postindex = size - 1; return constructTreeUtil(post, index, post[index.postindex], Integer.MIN_VALUE, Integer.MAX_VALUE, size); } // A utility function to print inorder traversal of a Binary Tree void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(node.data + \" \"); printInorder(node.right); } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int post[] = new int[]{1, 7, 5, 50, 40, 10}; int size = post.length; Node root = tree.constructTree(post, size); System.out.println(\"Inorder traversal of the constructed tree:\"); tree.printInorder(root); }} // This code has been contributed by Mayank Jaiswal", "e": 36444, "s": 33550, "text": null }, { "code": "# A O(n) program for construction of BST# from postorder traversalINT_MIN = -2**31INT_MAX = 2**31 # A binary tree node has data, pointer to# left child and a pointer to right child# A utility function to create a nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # A recursive function to construct# BST from post[]. postIndex is used# to keep track of index in post[].def constructTreeUtil(post, postIndex, key, min, max, size): # Base case if (postIndex[0] < 0): return None root = None # If current element of post[] is # in range, then only it is part # of current subtree if (key > min and key < max) : # Allocate memory for root of this # subtree and decrement *postIndex root = newNode(key) postIndex[0] = postIndex[0] - 1 if (postIndex[0] >= 0) : # All nodes which are in range key.. # max will go in right subtree, and # first such node will be root of # right subtree. root.right = constructTreeUtil(post, postIndex, post[postIndex[0]], key, max, size ) # Construct the subtree under root # All nodes which are in range min .. # key will go in left subtree, and # first such node will be root of # left subtree. root.left = constructTreeUtil(post, postIndex, post[postIndex[0]], min, key, size ) return root # The main function to construct BST# from given postorder traversal. This# function mainly uses constructTreeUtil()def constructTree (post, size) : postIndex = [size-1] return constructTreeUtil(post, postIndex, post[postIndex[0]], INT_MIN, INT_MAX, size) # A utility function to printInorder# traversal of a Binary Treedef printInorder (node) : if (node == None) : return printInorder(node.left) print(node.data, end = \" \") printInorder(node.right) # Driver Codeif __name__ == '__main__': post = [1, 7, 5, 50, 40, 10] size = len(post) root = constructTree(post, size) print(\"Inorder traversal of the\", \"constructed tree: \") printInorder(root) # This code is contributed# by SHUBHAMSINGH10", "e": 38936, "s": 36444, "text": null }, { "code": "using System;/* A O(n) program forconstruction of BST frompostorder traversal */ /* A binary tree node has data,pointer to left child and a pointer to right child */class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} // Class containing variable// that keeps a track of overall// calculated postindexclass Index{ public int postindex = 0;} public class BinaryTree{ // A recursive function to // construct BST from post[]. // postIndex is used to // keep track of index in post[]. Node constructTreeUtil(int []post, Index postIndex, int key, int min, int max, int size) { // Base case if (postIndex.postindex < 0) return null; Node root = null; // If current element of post[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of // this subtree and decrement *postIndex root = new Node(key); postIndex.postindex = postIndex.postindex - 1; if (postIndex.postindex >= 0) { // All nodes which are in range // {key..max} will go in right subtree, // and first such node will be root of // right subtree root.right = constructTreeUtil(post, postIndex, post[postIndex.postindex], key, max, size); // Construct the subtree under root // All nodes which are in range // {min .. key} will go in left // subtree, and first such node // will be root of left subtree. root.left = constructTreeUtil(post, postIndex, post[postIndex.postindex],min, key, size); } } return root; } // The main function to construct // BST from given postorder traversal. // This function mainly uses constructTreeUtil() Node constructTree(int []post, int size) { Index index = new Index(); index.postindex = size - 1; return constructTreeUtil(post, index, post[index.postindex], int.MinValue, int.MaxValue, size); } // A utility function to print // inorder traversal of a Binary Tree void printInorder(Node node) { if (node == null) return; printInorder(node.left); Console.Write(node.data + \" \"); printInorder(node.right); } // Driver code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); int []post = new int[]{1, 7, 5, 50, 40, 10}; int size = post.Length; Node root = tree.constructTree(post, size); Console.WriteLine(\"Inorder traversal of\" + \"the constructed tree:\"); tree.printInorder(root); }} // This code has been contributed by PrinciRaj1992", "e": 41980, "s": 38936, "text": null }, { "code": "<script> /* A O(n) program forconstruction of BST frompostorder traversal */ /* A binary tree node has data,pointer to left child and a pointer to right child */ class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } // Class containing variable // that keeps a track of overall // calculated postindex class Index { constructor() { this.postindex = 0; } } class BinaryTree { // A recursive function to // construct BST from post[]. // postIndex is used to // keep track of index in post[]. constructTreeUtil(post, postIndex, key, min, max, size) { // Base case if (postIndex.postindex < 0) return null; var root = null; // If current element of post[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of // this subtree and decrement *postIndex root = new Node(key); postIndex.postindex = postIndex.postindex - 1; if (postIndex.postindex >= 0) { // All nodes which are in range // {key..max} will go in right subtree, // and first such node will be root of // right subtree root.right = this.constructTreeUtil( post, postIndex, post[postIndex.postindex], key, max, size ); // Construct the subtree under root // All nodes which are in range // {min .. key} will go in left // subtree, and first such node // will be root of left subtree. root.left = this.constructTreeUtil( post, postIndex, post[postIndex.postindex], min, key, size ); } } return root; } // The main function to construct // BST from given postorder traversal. // This function mainly uses constructTreeUtil() constructTree(post, size) { var index = new Index(); index.postindex = size - 1; return this.constructTreeUtil( post, index, post[index.postindex], -2147483648, 2147483647, size ); } // A utility function to print // inorder traversal of a Binary Tree printInorder(node) { if (node == null) return; this.printInorder(node.left); document.write(node.data + \" \"); this.printInorder(node.right); } } // Driver code var tree = new BinaryTree(); var post = [1, 7, 5, 50, 40, 10]; var size = post.length; var root = tree.constructTree(post, size); document.write(\"Inorder traversal of \" + \"the constructed tree: <br>\"); tree.printInorder(root); </script>", "e": 45116, "s": 41980, "text": null }, { "code": null, "e": 45124, "s": 45116, "text": "Output:" }, { "code": null, "e": 45184, "s": 45124, "text": "Inorder traversal of the constructed tree: \n1 5 7 10 40 50 " }, { "code": null, "e": 45321, "s": 45186, "text": "Note that the output to the program will always be a sorted sequence as we are printing the inorder traversal of a Binary Search Tree." }, { "code": null, "e": 45589, "s": 45323, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 45714, "s": 45589, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 45728, "s": 45714, "text": "princiraj1992" }, { "code": null, "e": 45743, "s": 45728, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 45756, "s": 45743, "text": "Akanksha_Rai" }, { "code": null, "e": 45763, "s": 45756, "text": "rdtank" }, { "code": null, "e": 45780, "s": 45763, "text": "himanshuaswalgfg" }, { "code": null, "e": 45793, "s": 45780, "text": "simmytarika5" }, { "code": null, "e": 45802, "s": 45793, "text": "SAP Labs" }, { "code": null, "e": 45821, "s": 45802, "text": "Binary Search Tree" }, { "code": null, "e": 45826, "s": 45821, "text": "Tree" }, { "code": null, "e": 45835, "s": 45826, "text": "SAP Labs" }, { "code": null, "e": 45854, "s": 45835, "text": "Binary Search Tree" }, { "code": null, "e": 45859, "s": 45854, "text": "Tree" }, { "code": null, "e": 45957, "s": 45859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45992, "s": 45957, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 46024, "s": 45992, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 46081, "s": 46024, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 46115, "s": 46081, "text": "Advantages of BST over Hash Table" }, { "code": null, "e": 46169, "s": 46115, "text": "Difference between Binary Tree and Binary Search Tree" }, { "code": null, "e": 46204, "s": 46169, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 46247, "s": 46204, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 46280, "s": 46247, "text": "Binary Tree | Set 2 (Properties)" } ]
Python PIL | ImageOps.colorize() Method - GeeksforGeeks
26 Aug, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. PIL.ImageOps.colorize() Colorize grayscale image. The black and white arguments should be RGB tuples; this function calculates a color wedge mapping all black pixels in the source image to the first color, and all white pixels to the second color. Syntax: PIL.ImageOps.colorize(image, black, white) Parameters: image – The image to colorize. black – The color to use for black input pixels. white – The color to use for white input pixels. Returns: An Image . Image Used: Code : # importing image object from PILfrom PIL import Image, ImageOps # creating an image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\pinktree.jpg").convert("L") # image colorize functionimg1 = ImageOps.colorize(img, black ="blue", white ="white")img1.show() Output: Another Example: Here we use different parameters. Image Used: Code : # importing image object from PILfrom PIL import Image, ImageOps # creating an image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\bird.jpg").convert("L") # image colorize functionimg1 = ImageOps.colorize(img, black ="red", white ="yellow")img1.show() Output: Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25629, "s": 25601, "text": "\n26 Aug, 2019" }, { "code": null, "e": 25956, "s": 25629, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images." }, { "code": null, "e": 26204, "s": 25956, "text": "PIL.ImageOps.colorize() Colorize grayscale image. The black and white arguments should be RGB tuples; this function calculates a color wedge mapping all black pixels in the source image to the first color, and all white pixels to the second color." }, { "code": null, "e": 26255, "s": 26204, "text": "Syntax: PIL.ImageOps.colorize(image, black, white)" }, { "code": null, "e": 26267, "s": 26255, "text": "Parameters:" }, { "code": null, "e": 26298, "s": 26267, "text": "image – The image to colorize." }, { "code": null, "e": 26347, "s": 26298, "text": "black – The color to use for black input pixels." }, { "code": null, "e": 26396, "s": 26347, "text": "white – The color to use for white input pixels." }, { "code": null, "e": 26416, "s": 26396, "text": "Returns: An Image ." }, { "code": null, "e": 26428, "s": 26416, "text": "Image Used:" }, { "code": null, "e": 26435, "s": 26428, "text": "Code :" }, { "code": " # importing image object from PILfrom PIL import Image, ImageOps # creating an image objectimg = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\pinktree.jpg\").convert(\"L\") # image colorize functionimg1 = ImageOps.colorize(img, black =\"blue\", white =\"white\")img1.show()", "e": 26704, "s": 26435, "text": null }, { "code": null, "e": 26712, "s": 26704, "text": "Output:" }, { "code": null, "e": 26763, "s": 26712, "text": "Another Example: Here we use different parameters." }, { "code": null, "e": 26775, "s": 26763, "text": "Image Used:" }, { "code": null, "e": 26782, "s": 26775, "text": "Code :" }, { "code": " # importing image object from PILfrom PIL import Image, ImageOps # creating an image objectimg = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\bird.jpg\").convert(\"L\") # image colorize functionimg1 = ImageOps.colorize(img, black =\"red\", white =\"yellow\")img1.show()", "e": 27047, "s": 26782, "text": null }, { "code": null, "e": 27055, "s": 27047, "text": "Output:" }, { "code": null, "e": 27062, "s": 27055, "text": "Python" }, { "code": null, "e": 27160, "s": 27062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27178, "s": 27160, "text": "Python Dictionary" }, { "code": null, "e": 27213, "s": 27178, "text": "Read a file line by line in Python" }, { "code": null, "e": 27245, "s": 27213, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27267, "s": 27245, "text": "Enumerate() in Python" }, { "code": null, "e": 27309, "s": 27267, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27339, "s": 27309, "text": "Iterate over a list in Python" }, { "code": null, "e": 27365, "s": 27339, "text": "Python String | replace()" }, { "code": null, "e": 27394, "s": 27365, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27438, "s": 27394, "text": "Reading and Writing to text files in Python" } ]
Difference Between Singleton Pattern and Static Class in Java - GeeksforGeeks
21 Feb, 2022 Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application. Different objects trying to invoke an object instantiated as singleton. If you look at the illustrated diagram above you will see different objects trying to invoke an object instantiated as a singleton. This single instance of the object is responsible to invoke underneath methods or events. Guidelines for Singleton Pattern are as follows: Advantages: Singleton controls concurrent access to the resource. It ensures there is only one object available across the application in a controlled state. Ensure that only one instance of the class exists. Provide global instance to that access by declaring all constructors of the class to be private, providing a static method that returns a reference to the instance, and the instance is stored as a private static variable. Example Java // Java Program to illustrate Difference Between// Singleton Pattern vs Static Class. // Here illustrating Singleton Pattern // Importing input output classesimport java.io.*; // Class 1// Helper classclass SingletonEagar { // Declaration and definition of variable occur // simultaneously // Eager initialisation private static SingletonEagar instance = new SingletonEagar(); // Private constructor of class 1 private SingletonEagar() {} public static SingletonEagar getInstance() { return instance; }} // Class 2// Helper Classclass Singleton { // Lazy declaration and initialisation private static Singleton instance; // Private constructor of Class 2 private Singleton() {} public static Singleton getInstance() { // Condition check // When instance is null // a new object of Singleton class is created if (instance == null) { instance = new Singleton(); } return instance; }} // Class 3// Helper classclass SingletonSynchronizedMethod { private static SingletonSynchronizedMethod instance; // Private constructor of Class 3 private SingletonSynchronizedMethod() {} public static synchronized SingletonSynchronizedMethod getInstance() { // Condition check // When instance is null // a new object of Singleton class is created if (instance == null) { instance = new SingletonSynchronizedMethod(); } return instance; }} // Class 4// Helper classclass SingletonSynchronized { private static SingletonSynchronized instance; // Private constructor of Class 4 private SingletonSynchronized() {} public static SingletonSynchronized getInstance() { // Again, condition check if (instance == null) { // synchronized block synchronized (SingletonSynchronized.class) { if (instance == null) { instance = new SingletonSynchronized(); } } } return instance; }} // Class 5// Main class (SingletonExample)public class GFG { // Main driver method public static void main(String[] args) { // Creating instance in main() method of class 1 SingletonEagar instance1 = SingletonEagar.getInstance(); // Display message only System.out.println( instance1 + " : Singleton Eager initialisation "); // Creating instance in main() method of class 2 Singleton instance2 = Singleton.getInstance(); // Display message only System.out.println( instance2 + " : Singleton Lazy initialisation "); // Creating instance in main() method of class 4 SingletonSynchronized instance3 = SingletonSynchronized.getInstance(); // Display message only System.out.println(instance3 + " : Synchronized Singleton"); }} SingletonEagar@2f4d3709 : Singleton Eager initialisation Singleton@1d81eb93 : Singleton Lazy initialisation SingletonSynchronized@34a245ab : Synchronized Singleton Static Class Static nested classes are nested classes that are declared static. In Java, Static classes are a convenient way of grouping classes together. Java doesn’t allow you to create top-level static classes; only nested (inner) classes. That is why a static class is also known as a static inner class or static nested class. Guidelines for Static class are as follows: Advantages: Defining the related or helper classes is possible inside the class by making it static. It can access the private member of the enclosing class through the object reference. The static class provides a nice namespace for the nested class. If the enclosing class gets updated, we are able to update the static class as well at the same location. In JVM, Classloader loads the static class at the time of the first usage only, not when its enclosing class gets loaded. Implementation: Static class can only be an inner class or a nested class. Static classes can use any type of access modifier (private, protected, public, or default) like any other static member. Static classes are able to access only the static members of their enclosing class. Static class can interact with the non-static member only through the object of its enclosing class only, as it cannot access the non-static members of its enclosing class directly. Example Java // Java Program to illustrate Difference Between// Singleton Pattern vs Static Class. // Here illustrating Static Class // Importing input output classesimport java.io.*; // Class 1// Helper Classclass GFG_Outer { // Custom input integer value static int x = 20; public static void display() { System.out.println(x); } // Class 2 // Static inner class // Can access all static variables of outer class // Can't access non-static members static class GFG_Inner { GFG_Inner() { // Display message System.out.println( "This is Inner Class Constructor..."); // Print the value of x from inside class thrown // on console System.out.println( "Value of \"x\" from inside Inner Class is : " + x); } } // Main driver method public static void main(String[] args) { // Printing value of x in the main() method System.out.println(GFG_Outer.x); // Calling display() method from class 1 GFG_Outer.display(); // static inner class object which is as follows: // OuterClass.InnerClass variable = new // OuterClass.InnerClass(); GFG_Outer.GFG_Inner object = new GFG_Outer.GFG_Inner(); }} 20 20 This is Inner Class Constructor... Value of "x" from inside Inner Class is : 20 Now we have understood the concepts and working of both of them and have seen conclusive differences in both of them. Now let’s wrap it up by illustrating all differences in a tabular format which is as follows: gulshankumarar231 kapoorsagar226 as5853535 Java-Pattern Picked Difference Between Java Java 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": "\n21 Feb, 2022" }, { "code": null, "e": 26605, "s": 26127, "text": "Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application." }, { "code": null, "e": 26677, "s": 26605, "text": "Different objects trying to invoke an object instantiated as singleton." }, { "code": null, "e": 26899, "s": 26677, "text": "If you look at the illustrated diagram above you will see different objects trying to invoke an object instantiated as a singleton. This single instance of the object is responsible to invoke underneath methods or events." }, { "code": null, "e": 26949, "s": 26899, "text": "Guidelines for Singleton Pattern are as follows: " }, { "code": null, "e": 26961, "s": 26949, "text": "Advantages:" }, { "code": null, "e": 27015, "s": 26961, "text": "Singleton controls concurrent access to the resource." }, { "code": null, "e": 27107, "s": 27015, "text": "It ensures there is only one object available across the application in a controlled state." }, { "code": null, "e": 27158, "s": 27107, "text": "Ensure that only one instance of the class exists." }, { "code": null, "e": 27380, "s": 27158, "text": "Provide global instance to that access by declaring all constructors of the class to be private, providing a static method that returns a reference to the instance, and the instance is stored as a private static variable." }, { "code": null, "e": 27388, "s": 27380, "text": "Example" }, { "code": null, "e": 27393, "s": 27388, "text": "Java" }, { "code": "// Java Program to illustrate Difference Between// Singleton Pattern vs Static Class. // Here illustrating Singleton Pattern // Importing input output classesimport java.io.*; // Class 1// Helper classclass SingletonEagar { // Declaration and definition of variable occur // simultaneously // Eager initialisation private static SingletonEagar instance = new SingletonEagar(); // Private constructor of class 1 private SingletonEagar() {} public static SingletonEagar getInstance() { return instance; }} // Class 2// Helper Classclass Singleton { // Lazy declaration and initialisation private static Singleton instance; // Private constructor of Class 2 private Singleton() {} public static Singleton getInstance() { // Condition check // When instance is null // a new object of Singleton class is created if (instance == null) { instance = new Singleton(); } return instance; }} // Class 3// Helper classclass SingletonSynchronizedMethod { private static SingletonSynchronizedMethod instance; // Private constructor of Class 3 private SingletonSynchronizedMethod() {} public static synchronized SingletonSynchronizedMethod getInstance() { // Condition check // When instance is null // a new object of Singleton class is created if (instance == null) { instance = new SingletonSynchronizedMethod(); } return instance; }} // Class 4// Helper classclass SingletonSynchronized { private static SingletonSynchronized instance; // Private constructor of Class 4 private SingletonSynchronized() {} public static SingletonSynchronized getInstance() { // Again, condition check if (instance == null) { // synchronized block synchronized (SingletonSynchronized.class) { if (instance == null) { instance = new SingletonSynchronized(); } } } return instance; }} // Class 5// Main class (SingletonExample)public class GFG { // Main driver method public static void main(String[] args) { // Creating instance in main() method of class 1 SingletonEagar instance1 = SingletonEagar.getInstance(); // Display message only System.out.println( instance1 + \" : Singleton Eager initialisation \"); // Creating instance in main() method of class 2 Singleton instance2 = Singleton.getInstance(); // Display message only System.out.println( instance2 + \" : Singleton Lazy initialisation \"); // Creating instance in main() method of class 4 SingletonSynchronized instance3 = SingletonSynchronized.getInstance(); // Display message only System.out.println(instance3 + \" : Synchronized Singleton\"); }}", "e": 30414, "s": 27393, "text": null }, { "code": null, "e": 30580, "s": 30414, "text": "SingletonEagar@2f4d3709 : Singleton Eager initialisation \nSingleton@1d81eb93 : Singleton Lazy initialisation \nSingletonSynchronized@34a245ab : Synchronized Singleton" }, { "code": null, "e": 30596, "s": 30582, "text": "Static Class " }, { "code": null, "e": 30916, "s": 30596, "text": "Static nested classes are nested classes that are declared static. In Java, Static classes are a convenient way of grouping classes together. Java doesn’t allow you to create top-level static classes; only nested (inner) classes. That is why a static class is also known as a static inner class or static nested class. " }, { "code": null, "e": 30960, "s": 30916, "text": "Guidelines for Static class are as follows:" }, { "code": null, "e": 30972, "s": 30960, "text": "Advantages:" }, { "code": null, "e": 31061, "s": 30972, "text": "Defining the related or helper classes is possible inside the class by making it static." }, { "code": null, "e": 31147, "s": 31061, "text": "It can access the private member of the enclosing class through the object reference." }, { "code": null, "e": 31212, "s": 31147, "text": "The static class provides a nice namespace for the nested class." }, { "code": null, "e": 31318, "s": 31212, "text": "If the enclosing class gets updated, we are able to update the static class as well at the same location." }, { "code": null, "e": 31440, "s": 31318, "text": "In JVM, Classloader loads the static class at the time of the first usage only, not when its enclosing class gets loaded." }, { "code": null, "e": 31457, "s": 31440, "text": "Implementation: " }, { "code": null, "e": 31516, "s": 31457, "text": "Static class can only be an inner class or a nested class." }, { "code": null, "e": 31638, "s": 31516, "text": "Static classes can use any type of access modifier (private, protected, public, or default) like any other static member." }, { "code": null, "e": 31722, "s": 31638, "text": "Static classes are able to access only the static members of their enclosing class." }, { "code": null, "e": 31904, "s": 31722, "text": "Static class can interact with the non-static member only through the object of its enclosing class only, as it cannot access the non-static members of its enclosing class directly." }, { "code": null, "e": 31913, "s": 31904, "text": "Example " }, { "code": null, "e": 31918, "s": 31913, "text": "Java" }, { "code": "// Java Program to illustrate Difference Between// Singleton Pattern vs Static Class. // Here illustrating Static Class // Importing input output classesimport java.io.*; // Class 1// Helper Classclass GFG_Outer { // Custom input integer value static int x = 20; public static void display() { System.out.println(x); } // Class 2 // Static inner class // Can access all static variables of outer class // Can't access non-static members static class GFG_Inner { GFG_Inner() { // Display message System.out.println( \"This is Inner Class Constructor...\"); // Print the value of x from inside class thrown // on console System.out.println( \"Value of \\\"x\\\" from inside Inner Class is : \" + x); } } // Main driver method public static void main(String[] args) { // Printing value of x in the main() method System.out.println(GFG_Outer.x); // Calling display() method from class 1 GFG_Outer.display(); // static inner class object which is as follows: // OuterClass.InnerClass variable = new // OuterClass.InnerClass(); GFG_Outer.GFG_Inner object = new GFG_Outer.GFG_Inner(); }}", "e": 33228, "s": 31918, "text": null }, { "code": null, "e": 33314, "s": 33228, "text": "20\n20\nThis is Inner Class Constructor...\nValue of \"x\" from inside Inner Class is : 20" }, { "code": null, "e": 33526, "s": 33314, "text": "Now we have understood the concepts and working of both of them and have seen conclusive differences in both of them. Now let’s wrap it up by illustrating all differences in a tabular format which is as follows:" }, { "code": null, "e": 33544, "s": 33526, "text": "gulshankumarar231" }, { "code": null, "e": 33559, "s": 33544, "text": "kapoorsagar226" }, { "code": null, "e": 33569, "s": 33559, "text": "as5853535" }, { "code": null, "e": 33582, "s": 33569, "text": "Java-Pattern" }, { "code": null, "e": 33589, "s": 33582, "text": "Picked" }, { "code": null, "e": 33608, "s": 33589, "text": "Difference Between" }, { "code": null, "e": 33613, "s": 33608, "text": "Java" }, { "code": null, "e": 33618, "s": 33613, "text": "Java" }, { "code": null, "e": 33716, "s": 33618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33777, "s": 33716, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33845, "s": 33777, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 33903, "s": 33845, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 33958, "s": 33903, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 34024, "s": 33958, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 34039, "s": 34024, "text": "Arrays in Java" }, { "code": null, "e": 34083, "s": 34039, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34105, "s": 34083, "text": "For-each loop in Java" }, { "code": null, "e": 34156, "s": 34105, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
MySQL query to check if a string contains a value (substring) within the same row?
Since we need to match strings from the same row, use LIKE operator. Let us first create a table − mysql> create table DemoTable ( FirstName varchar(100), FullName varchar(100) ); Query OK, 0 rows affected (0.53 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('John','John Smith'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values('David','John Miller'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Bob','Sam Miller'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('Chris','Chris Brown'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-----------+-------------+ | FirstName | FullName | +-----------+-------------+ | John | John Smith | | David | John Miller | | Bob | Sam Miller | | Chris | Chris Brown | +-----------+-------------+ 4 rows in set (0.00 sec) Following is the query to check if a string contains a value within the same row − mysql> select FirstName,FullName from DemoTable where FullName LIKE concat('%', FirstName, '%'); This will produce the following output − +-----------+-------------+ | FirstName | FullName | +-----------+-------------+ | John | John Smith | | Chris | Chris Brown | +-----------+-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1161, "s": 1062, "text": "Since we need to match strings from the same row, use LIKE operator. Let us first create a table −" }, { "code": null, "e": 1285, "s": 1161, "text": "mysql> create table DemoTable\n(\n FirstName varchar(100),\n FullName varchar(100)\n);\nQuery OK, 0 rows affected (0.53 sec)" }, { "code": null, "e": 1341, "s": 1285, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1720, "s": 1341, "text": "mysql> insert into DemoTable values('John','John Smith');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable values('David','John Miller');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Bob','Sam Miller');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values('Chris','Chris Brown');\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 1780, "s": 1720, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1811, "s": 1780, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1852, "s": 1811, "text": "This will produce the following output −" }, { "code": null, "e": 2101, "s": 1852, "text": "+-----------+-------------+\n| FirstName | FullName |\n+-----------+-------------+\n| John | John Smith |\n| David | John Miller |\n| Bob | Sam Miller |\n| Chris | Chris Brown |\n+-----------+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2184, "s": 2101, "text": "Following is the query to check if a string contains a value within the same row −" }, { "code": null, "e": 2284, "s": 2184, "text": "mysql> select FirstName,FullName from DemoTable\n where FullName LIKE concat('%', FirstName, '%');" }, { "code": null, "e": 2325, "s": 2284, "text": "This will produce the following output −" }, { "code": null, "e": 2518, "s": 2325, "text": "+-----------+-------------+\n| FirstName | FullName |\n+-----------+-------------+\n| John | John Smith |\n| Chris | Chris Brown |\n+-----------+-------------+\n2 rows in set (0.00 sec)" } ]
IntUnaryOperator Interface in Java - GeeksforGeeks
18 Nov, 2019 The IntUnaryOperator Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and operates on it. Both its argument and return type are of int data type.It is very similar to using an object of type UnaryOperator<Integer>. The lambda expression assigned to an object of IntUnaryOperator type is used to define its applyAsInt() which eventually applies the given operation on its argument. The IntUnaryOperator interface consists of the following functions: This method returns an IntUnaryOperator which takes in one int value and returns it. The returned IntUnaryOperator does not perform any operation on its only value. Syntax: static IntUnaryOperator identity() Parameters: This method does not take in any parameter Returns: A IntUnaryOperator which takes in one value and returns it. Below is the code to illustrate identity() method: Program import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = IntUnaryOperator.identity(); System.out.println(op.applyAsInt(12)); }} 12 This method takes in one int value, performs the given operation and returns an int-valued result. Syntax: int applyAsInt(int operand) Parameters: This method takes in one int valued parameter Returns:: It returns an int valued result. Below is the code to illustrate applyAsInt() method: import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> 2 * a; System.out.println(op.applyAsInt(12)); }} 24 It returns a composed IntUnaryOperator wherein the parameterized operator will be executed after the first one. If either operation throws an error, it is relayed to the caller of the composed operation. Syntax: default IntUnaryOperator andThen(IntUnaryOperator after) Parameters: This method accepts a parameter after which is the operation to be applied after the current one. Return Value: This method returns a composed IntUnaryOperator that applies the current operation first and then the after operation. Exception: This method throws NullPointerException if the after operation is null. Below is the code to illustrate addThen() method: Program 1: import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> 2 * a; op = op.andThen(a -> 3 * a); System.out.println(op.applyAsInt(12)); }} 72 Program 2: To demonstrate when NullPointerException is returned. import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> 2 * a; op = op.andThen(null); System.out.println(op.applyAsInt(12)); }} java.lang.NullPointerException It returns a composed IntUnaryOperator wherein the parameterized operation will be executed first and then the first one. If either operation throws an error, it is relayed to the caller of the composed operation. Syntax: default IntUnaryOperator compose(IntUnaryOperator before) Parameters: This method accepts a parameter before which is the operation to be applied first and then the current one Return Value: This method returns a composed IntUnaryOperator that applies the current operator after the parameterized operator Exception: This method throws NullPointerException if the before operation is null. Below is the code to illustrate compose() method: Program 1: import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> a / 3; op = op.compose(a -> a * 6); System.out.println(op.applyAsInt(12)); }} 24 Program 2: To demonstrate when NullPointerException is returned. import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> a / 3; op = op.compose(null); System.out.println(op.applyAsInt(12)); }} java.lang.NullPointerException Akanksha_Rai Java - util package Java 8 java-basics Java-Functional Programming java-interfaces Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 25663, "s": 25635, "text": "\n18 Nov, 2019" }, { "code": null, "e": 26021, "s": 25663, "text": "The IntUnaryOperator Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and operates on it. Both its argument and return type are of int data type.It is very similar to using an object of type UnaryOperator<Integer>." }, { "code": null, "e": 26187, "s": 26021, "text": "The lambda expression assigned to an object of IntUnaryOperator type is used to define its applyAsInt() which eventually applies the given operation on its argument." }, { "code": null, "e": 26255, "s": 26187, "text": "The IntUnaryOperator interface consists of the following functions:" }, { "code": null, "e": 26420, "s": 26255, "text": "This method returns an IntUnaryOperator which takes in one int value and returns it. The returned IntUnaryOperator does not perform any operation on its only value." }, { "code": null, "e": 26428, "s": 26420, "text": "Syntax:" }, { "code": null, "e": 26464, "s": 26428, "text": "static IntUnaryOperator identity()" }, { "code": null, "e": 26519, "s": 26464, "text": "Parameters: This method does not take in any parameter" }, { "code": null, "e": 26588, "s": 26519, "text": "Returns: A IntUnaryOperator which takes in one value and returns it." }, { "code": null, "e": 26639, "s": 26588, "text": "Below is the code to illustrate identity() method:" }, { "code": null, "e": 26647, "s": 26639, "text": "Program" }, { "code": "import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = IntUnaryOperator.identity(); System.out.println(op.applyAsInt(12)); }}", "e": 26868, "s": 26647, "text": null }, { "code": null, "e": 26872, "s": 26868, "text": "12\n" }, { "code": null, "e": 26971, "s": 26872, "text": "This method takes in one int value, performs the given operation and returns an int-valued result." }, { "code": null, "e": 26979, "s": 26971, "text": "Syntax:" }, { "code": null, "e": 27007, "s": 26979, "text": "int applyAsInt(int operand)" }, { "code": null, "e": 27065, "s": 27007, "text": "Parameters: This method takes in one int valued parameter" }, { "code": null, "e": 27108, "s": 27065, "text": "Returns:: It returns an int valued result." }, { "code": null, "e": 27161, "s": 27108, "text": "Below is the code to illustrate applyAsInt() method:" }, { "code": "import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> 2 * a; System.out.println(op.applyAsInt(12)); }}", "e": 27365, "s": 27161, "text": null }, { "code": null, "e": 27369, "s": 27365, "text": "24\n" }, { "code": null, "e": 27573, "s": 27369, "text": "It returns a composed IntUnaryOperator wherein the parameterized operator will be executed after the first one. If either operation throws an error, it is relayed to the caller of the composed operation." }, { "code": null, "e": 27581, "s": 27573, "text": "Syntax:" }, { "code": null, "e": 27638, "s": 27581, "text": "default IntUnaryOperator andThen(IntUnaryOperator after)" }, { "code": null, "e": 27748, "s": 27638, "text": "Parameters: This method accepts a parameter after which is the operation to be applied after the current one." }, { "code": null, "e": 27881, "s": 27748, "text": "Return Value: This method returns a composed IntUnaryOperator that applies the current operation first and then the after operation." }, { "code": null, "e": 27964, "s": 27881, "text": "Exception: This method throws NullPointerException if the after operation is null." }, { "code": null, "e": 28014, "s": 27964, "text": "Below is the code to illustrate addThen() method:" }, { "code": null, "e": 28025, "s": 28014, "text": "Program 1:" }, { "code": "import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> 2 * a; op = op.andThen(a -> 3 * a); System.out.println(op.applyAsInt(12)); }}", "e": 28265, "s": 28025, "text": null }, { "code": null, "e": 28269, "s": 28265, "text": "72\n" }, { "code": null, "e": 28334, "s": 28269, "text": "Program 2: To demonstrate when NullPointerException is returned." }, { "code": "import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> 2 * a; op = op.andThen(null); System.out.println(op.applyAsInt(12)); }}", "e": 28568, "s": 28334, "text": null }, { "code": null, "e": 28600, "s": 28568, "text": "java.lang.NullPointerException\n" }, { "code": null, "e": 28814, "s": 28600, "text": "It returns a composed IntUnaryOperator wherein the parameterized operation will be executed first and then the first one. If either operation throws an error, it is relayed to the caller of the composed operation." }, { "code": null, "e": 28822, "s": 28814, "text": "Syntax:" }, { "code": null, "e": 28880, "s": 28822, "text": "default IntUnaryOperator compose(IntUnaryOperator before)" }, { "code": null, "e": 28999, "s": 28880, "text": "Parameters: This method accepts a parameter before which is the operation to be applied first and then the current one" }, { "code": null, "e": 29128, "s": 28999, "text": "Return Value: This method returns a composed IntUnaryOperator that applies the current operator after the parameterized operator" }, { "code": null, "e": 29212, "s": 29128, "text": "Exception: This method throws NullPointerException if the before operation is null." }, { "code": null, "e": 29262, "s": 29212, "text": "Below is the code to illustrate compose() method:" }, { "code": null, "e": 29273, "s": 29262, "text": "Program 1:" }, { "code": "import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> a / 3; op = op.compose(a -> a * 6); System.out.println(op.applyAsInt(12)); }}", "e": 29513, "s": 29273, "text": null }, { "code": null, "e": 29517, "s": 29513, "text": "24\n" }, { "code": null, "e": 29582, "s": 29517, "text": "Program 2: To demonstrate when NullPointerException is returned." }, { "code": "import java.util.function.IntUnaryOperator; public class GFG { public static void main(String args[]) { IntUnaryOperator op = a -> a / 3; op = op.compose(null); System.out.println(op.applyAsInt(12)); }}", "e": 29816, "s": 29582, "text": null }, { "code": null, "e": 29848, "s": 29816, "text": "java.lang.NullPointerException\n" }, { "code": null, "e": 29861, "s": 29848, "text": "Akanksha_Rai" }, { "code": null, "e": 29881, "s": 29861, "text": "Java - util package" }, { "code": null, "e": 29888, "s": 29881, "text": "Java 8" }, { "code": null, "e": 29900, "s": 29888, "text": "java-basics" }, { "code": null, "e": 29928, "s": 29900, "text": "Java-Functional Programming" }, { "code": null, "e": 29944, "s": 29928, "text": "java-interfaces" }, { "code": null, "e": 29949, "s": 29944, "text": "Java" }, { "code": null, "e": 29954, "s": 29949, "text": "Java" }, { "code": null, "e": 30052, "s": 29954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30103, "s": 30052, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30133, "s": 30103, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30152, "s": 30133, "text": "Interfaces in Java" }, { "code": null, "e": 30183, "s": 30152, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30215, "s": 30183, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 30233, "s": 30215, "text": "ArrayList in Java" }, { "code": null, "e": 30253, "s": 30233, "text": "Stack Class in Java" }, { "code": null, "e": 30277, "s": 30253, "text": "Singleton Class in Java" }, { "code": null, "e": 30309, "s": 30277, "text": "Multidimensional Arrays in Java" } ]
Check if a binary tree is subtree of another binary tree | Set 2 - GeeksforGeeks
16 Mar, 2022 Given two binary trees, check if the first tree is subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 is a subtree of Tree2. Tree1 x / \ a b \ c Tree2 z / \ x e / \ \ a b k \ c We have discussed a O(n2) solution for this problem. In this post a O(n) solution is discussed. The idea is based on the fact that inorder and preorder/postorder uniquely identify a binary tree. Tree S is a subtree of T if both inorder and preorder traversals of S arew substrings of inorder and preorder traversals of T respectively.Following are detailed steps.1) Find inorder and preorder traversals of T, store them in two auxiliary arrays inT[] and preT[].2) Find inorder and preorder traversals of S, store them in two auxiliary arrays inS[] and preS[].3) If inS[] is a subarray of inT[] and preS[] is a subarray preT[], then S is a subtree of T. Else not.We can also use postorder traversal in place of preorder in the above algorithm.Let us consider the above example Inorder and Preorder traversals of the big tree are. inT[] = {a, c, x, b, z, e, k} preT[] = {z, x, a, c, b, e, k} Inorder and Preorder traversals of small tree are inS[] = {a, c, x, b} preS[] = {x, a, c, b} We can easily figure out that inS[] is a subarray of inT[] and preS[] is a subarray of preT[]. EDIT The above algorithm doesn't work for cases where a tree is present in another tree, but not as a subtree. Consider the following example. Tree1 x / \ a b / c Tree2 x / \ a b / \ c d Inorder and Preorder traversals of the big tree or Tree2 are. inT[] = {c, a, x, b, d} preT[] = {x, a, c, b, d} Inorder and Preorder traversals of small tree or Tree1 are- inS[] = {c, a, x, b} preS[] = {x, a, c, b} The Tree2 is not a subtree of Tree1, but inS[] and preS[] are subarrays of inT[] and preT[] respectively. The above algorithm can be extended to handle such cases by adding a special character whenever we encounter NULL in inorder and preorder traversals. Thanks to Shivam Goel for suggesting this extension. Following is the implementation of the above algorithm. C++ Java Python3 C# Javascript #include <cstring>#include <iostream>using namespace std;#define MAX 100 // Structure of a tree nodestruct Node { char key; struct Node *left, *right;}; // A utility function to create a new BST nodeNode* newNode(char item){ Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to store inorder traversal of tree rooted// with root in an array arr[]. Note that i is passed as referencevoid storeInorder(Node* root, char arr[], int& i){ if (root == NULL) { arr[i++] = '$'; return; } storeInorder(root->left, arr, i); arr[i++] = root->key; storeInorder(root->right, arr, i);} // A utility function to store preorder traversal of tree rooted// with root in an array arr[]. Note that i is passed as referencevoid storePreOrder(Node* root, char arr[], int& i){ if (root == NULL) { arr[i++] = '$'; return; } arr[i++] = root->key; storePreOrder(root->left, arr, i); storePreOrder(root->right, arr, i);} /* This function returns true if S is a subtree of T, otherwise false */bool isSubtree(Node* T, Node* S){ /* base cases */ if (S == NULL) return true; if (T == NULL) return false; // Store Inorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively int m = 0, n = 0; char inT[MAX], inS[MAX]; storeInorder(T, inT, m); storeInorder(S, inS, n); inT[m] = '\0', inS[n] = '\0'; // If inS[] is not a substring of inT[], return false if (strstr(inT, inS) == NULL) return false; // Store Preorder traversals of T and S in preT[0..m-1] // and preS[0..n-1] respectively m = 0, n = 0; char preT[MAX], preS[MAX]; storePreOrder(T, preT, m); storePreOrder(S, preS, n); preT[m] = '\0', preS[n] = '\0'; // If preS[] is not a substring of preT[], return false // Else return true return (strstr(preT, preS) != NULL);} // Driver program to test above functionint main(){ Node* T = newNode('a'); T->left = newNode('b'); T->right = newNode('d'); T->left->left = newNode('c'); T->right->right = newNode('e'); Node* S = newNode('a'); S->left = newNode('b'); S->left->left = newNode('c'); S->right = newNode('d'); if (isSubtree(T, S)) cout << "Yes: S is a subtree of T"; else cout << "No: S is NOT a subtree of T"; return 0;} // Java program to check if binary tree// is subtree of another binary treeclass Node { char data; Node left, right; Node(char item) { data = item; left = right = null; }} class Passing { int i; int m = 0; int n = 0;} class BinaryTree { static Node root; Passing p = new Passing(); String strstr(String haystack, String needle) { if (haystack == null || needle == null) { return null; } int hLength = haystack.length(); int nLength = needle.length(); if (hLength < nLength) { return null; } if (nLength == 0) { return haystack; } for (int i = 0; i <= hLength - nLength; i++) { if (haystack.charAt(i) == needle.charAt(0)) { int j = 0; for (; j < nLength; j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { break; } } if (j == nLength) { return haystack.substring(i); } } } return null; } // A utility function to store inorder traversal of tree rooted // with root in an array arr[]. Note that i is passed as reference void storeInorder(Node node, char arr[], Passing i) { if (node == null) { arr[i.i++] = '$'; return; } storeInorder(node.left, arr, i); arr[i.i++] = node.data; storeInorder(node.right, arr, i); } // A utility function to store preorder traversal of tree rooted // with root in an array arr[]. Note that i is passed as reference void storePreOrder(Node node, char arr[], Passing i) { if (node == null) { arr[i.i++] = '$'; return; } arr[i.i++] = node.data; storePreOrder(node.left, arr, i); storePreOrder(node.right, arr, i); } /* This function returns true if S is a subtree of T, otherwise false */ boolean isSubtree(Node T, Node S) { /* base cases */ if (S == null) { return true; } if (T == null) { return false; } // Store Inorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively char inT[] = new char[100]; String op1 = String.valueOf(inT); char inS[] = new char[100]; String op2 = String.valueOf(inS); storeInorder(T, inT, p); storeInorder(S, inS, p); inT[p.m] = '\0'; inS[p.m] = '\0'; // If inS[] is not a substring of preS[], return false if (strstr(op1, op2) != null) { return false; } // Store Preorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively p.m = 0; p.n = 0; char preT[] = new char[100]; char preS[] = new char[100]; String op3 = String.valueOf(preT); String op4 = String.valueOf(preS); storePreOrder(T, preT, p); storePreOrder(S, preS, p); preT[p.m] = '\0'; preS[p.n] = '\0'; // If inS[] is not a substring of preS[], return false // Else return true return (strstr(op3, op4) != null); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); Node T = new Node('a'); T.left = new Node('b'); T.right = new Node('d'); T.left.left = new Node('c'); T.right.right = new Node('e'); Node S = new Node('a'); S.left = new Node('b'); S.right = new Node('d'); S.left.left = new Node('c'); if (tree.isSubtree(T, S)) { System.out.println("Yes, S is a subtree of T"); } else { System.out.println("No, S is not a subtree of T"); } }} // This code is contributed by Mayank Jaiswal MAX = 100 # class for a tree nodeclass Node: def __init__(self): self.key = ' ' self.left = None self.right = None # A utility function to create a new BST nodedef newNode(item): temp = Node() temp.key = item return temp # A utility function to store inorder traversal of tree rooted# with root in an array arr[]. Note that i is passed as referencedef storeInorder(root, i): if (root == None): return '$' res = storeInorder(root.left, i) res += root.key res += storeInorder(root.right, i) return res # A utility function to store preorder traversal of tree rooted# with root in an array arr[]. Note that i is passed as referencedef storePreOrder(root, i): if (root == None): return '$' res = root.key res += storePreOrder(root.left, i) res += storePreOrder(root.right, i) return res # This function returns true if S is a subtree of T, otherwise falsedef isSubtree(T, S): # base cases if (S == None): return True if (T == None): return False # Store Inorder traversals of T and S in inT[0..m-1] # and inS[0..n-1] respectively m = 0 n = 0 inT = storeInorder(T, m) inS = storeInorder(S, n) # If inS[] is not a substring of inT[], return false res = True if inS in inT: res = True else: res = False if(res == False): return res # Store Preorder traversals of T and S in preT[0..m-1] # and preS[0..n-1] respectively m = 0 n = 0 preT = storePreOrder(T, m) preS = storePreOrder(S, n) # If preS[] is not a substring of preT[], return false # Else return true if preS in preT: return True else: return False # Driver program to test above functionT = newNode('a')T.left = newNode('b')T.right = newNode('d')T.left.left = newNode('c')T.right.right = newNode('e') S = newNode('a')S.left = newNode('b')S.left.left = newNode('c')S.right = newNode('d') if (isSubtree(T, S)): print("Yes: S is a subtree of T")else: print("No: S is NOT a subtree of T") # This code is contributed by rj13to. // C# program to check if binary tree is// subtree of another binary treeusing System; public class Node { public char data; public Node left, right; public Node(char item) { data = item; left = right = null; }} public class Passing { public int i; public int m = 0; public int n = 0;} public class BinaryTree { static Node root; Passing p = new Passing(); String strstr(String haystack, String needle) { if (haystack == null || needle == null) { return null; } int hLength = haystack.Length; int nLength = needle.Length; if (hLength < nLength) { return null; } if (nLength == 0) { return haystack; } for (int i = 0; i <= hLength - nLength; i++) { if (haystack[i] == needle[0]) { int j = 0; for (; j < nLength; j++) { if (haystack[i + j] != needle[j]) { break; } } if (j == nLength) { return haystack.Substring(i); } } } return null; } // A utility function to store inorder // traversal of tree rooted with root in // an array arr[]. Note that i is passed as reference void storeInorder(Node node, char[] arr, Passing i) { if (node == null) { arr[i.i++] = '$'; return; } storeInorder(node.left, arr, i); arr[i.i++] = node.data; storeInorder(node.right, arr, i); } // A utility function to store preorder // traversal of tree rooted with root in // an array arr[]. Note that i is passed as reference void storePreOrder(Node node, char[] arr, Passing i) { if (node == null) { arr[i.i++] = '$'; return; } arr[i.i++] = node.data; storePreOrder(node.left, arr, i); storePreOrder(node.right, arr, i); } /* This function returns true if S is a subtree of T, otherwise false */ bool isSubtree(Node T, Node S) { /* base cases */ if (S == null) { return true; } if (T == null) { return false; } // Store Inorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively char[] inT = new char[100]; String op1 = String.Join("", inT); char[] inS = new char[100]; String op2 = String.Join("", inS); storeInorder(T, inT, p); storeInorder(S, inS, p); inT[p.m] = '\0'; inS[p.m] = '\0'; // If inS[] is not a substring of preS[], return false if (strstr(op1, op2) != null) { return false; } // Store Preorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively p.m = 0; p.n = 0; char[] preT = new char[100]; char[] preS = new char[100]; String op3 = String.Join("", preT); String op4 = String.Join("", preS); storePreOrder(T, preT, p); storePreOrder(S, preS, p); preT[p.m] = '\0'; preS[p.n] = '\0'; // If inS[] is not a substring of preS[], return false // Else return true return (strstr(op3, op4) != null); } // Driver program to test above functions public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); Node T = new Node('a'); T.left = new Node('b'); T.right = new Node('d'); T.left.left = new Node('c'); T.right.right = new Node('e'); Node S = new Node('a'); S.left = new Node('b'); S.right = new Node('d'); S.left.left = new Node('c'); if (tree.isSubtree(T, S)) { Console.WriteLine("Yes, S is a subtree of T"); } else { Console.WriteLine("No, S is not a subtree of T"); } }} // This code contributed by Rajput-Ji <script> const MAX = 100 // class for a tree nodeclass Node{ constructor(){ this.key = ' ' this.left = null this.right = null }} // A utility function to create a new BST nodefunction newNode(item){ temp = new Node() temp.key = item return temp} // A utility function to store inorder traversal of tree rooted// with root in an array arr[]. Note that i is passed as referencefunction storeInorder(root, i){ if (root == null) return '$' res = storeInorder(root.left, i) res += root.key res += storeInorder(root.right, i) return res} // A utility function to store preorder traversal of tree rooted// with root in an array arr[]. Note that i is passed as referencefunction storePreOrder(root, i){ if (root == null) return '$' res = root.key res += storePreOrder(root.left, i) res += storePreOrder(root.right, i) return res} // This function returns true if S is a subtree of T, otherwise falsefunction isSubtree(T, S){ // base cases if (S == null) return true if (T == null) return false // Store Inorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively let m = 0 let n = 0 let inT = storeInorder(T, m) let inS = storeInorder(S, n) // If inS[] is not a substring of inT[], return false res = true if(inT.indexOf(inT) !== -1) res = true else res = false if(res == false) return res // Store Preorder traversals of T and S in preT[0..m-1] // and preS[0..n-1] respectively m = 0 n = 0 let preT = storePreOrder(T, m) let preS = storePreOrder(S, n) // If preS[] is not a substring of preT[], return false // Else return true if(preT.indexOf(preS) !== -1) return true else return false} // Driver program to test above function let T = new newNode('a')T.left = new newNode('b')T.right = new newNode('d')T.left.left = new newNode('c')T.right.right = new newNode('e') let S = new newNode('a')S.left = new newNode('b')S.left.left = new newNode('c')S.right = new newNode('d') if (isSubtree(T, S)) document.write("Yes: S is a subtree of T","</br>")else document.write("No: S is NOT a subtree of T","</br>") // This code is contributed by shinjanpatra </script> Output: No: S is NOT a subtree of T Time Complexity: Inorder and Preorder traversals of Binary Tree take O(n) time. The function strstr() can also be implemented in O(n) time using KMP string matching algorithm.Auxiliary Space: O(n)Thanks to Ashwini Singh for suggesting this method. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Rajput-Ji aayushpatni rj13to vivekmaddheshiya205 shinjanpatra Amazon Cavisson System MakeMyTrip Microsoft Tree Amazon Microsoft MakeMyTrip Cavisson System Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Introduction to Tree Data Structure Expression Tree Deletion in a Binary Tree AVL Tree | Set 2 (Deletion) BFS vs DFS for Binary Tree Binary Tree (Array implementation) Sorted Array to Balanced BST Inorder Tree Traversal without recursion and without stack! Relationship between number of nodes and height of binary tree
[ { "code": null, "e": 26585, "s": 26557, "text": "\n16 Mar, 2022" }, { "code": null, "e": 26956, "s": 26585, "text": "Given two binary trees, check if the first tree is subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 is a subtree of Tree2. " }, { "code": null, "e": 27165, "s": 26956, "text": " Tree1\n x \n / \\\n a b\n \\\n c\n\n\n Tree2\n z\n / \\\n x e\n / \\ \\\n a b k\n \\\n c" }, { "code": null, "e": 27944, "s": 27167, "text": "We have discussed a O(n2) solution for this problem. In this post a O(n) solution is discussed. The idea is based on the fact that inorder and preorder/postorder uniquely identify a binary tree. Tree S is a subtree of T if both inorder and preorder traversals of S arew substrings of inorder and preorder traversals of T respectively.Following are detailed steps.1) Find inorder and preorder traversals of T, store them in two auxiliary arrays inT[] and preT[].2) Find inorder and preorder traversals of S, store them in two auxiliary arrays inS[] and preS[].3) If inS[] is a subarray of inT[] and preS[] is a subarray preT[], then S is a subtree of T. Else not.We can also use postorder traversal in place of preorder in the above algorithm.Let us consider the above example " }, { "code": null, "e": 28255, "s": 27944, "text": "Inorder and Preorder traversals of the big tree are.\ninT[] = {a, c, x, b, z, e, k}\npreT[] = {z, x, a, c, b, e, k}\n\nInorder and Preorder traversals of small tree are\ninS[] = {a, c, x, b}\npreS[] = {x, a, c, b}\n\nWe can easily figure out that inS[] is a subarray of\ninT[] and preS[] is a subarray of preT[]. " }, { "code": null, "e": 28260, "s": 28255, "text": "EDIT" }, { "code": null, "e": 28912, "s": 28260, "text": "The above algorithm doesn't work for cases where a tree is present\nin another tree, but not as a subtree. Consider the following example.\n\n Tree1\n x \n / \\\n a b\n / \n c \n\n\n Tree2\n x \n / \\\n a b\n / \\\n c d\n\nInorder and Preorder traversals of the big tree or Tree2 are.\ninT[] = {c, a, x, b, d}\npreT[] = {x, a, c, b, d}\n\nInorder and Preorder traversals of small tree or Tree1 are-\ninS[] = {c, a, x, b}\npreS[] = {x, a, c, b}\n\nThe Tree2 is not a subtree of Tree1, but inS[] and preS[] are\nsubarrays of inT[] and preT[] respectively." }, { "code": null, "e": 29172, "s": 28912, "text": "The above algorithm can be extended to handle such cases by adding a special character whenever we encounter NULL in inorder and preorder traversals. Thanks to Shivam Goel for suggesting this extension. Following is the implementation of the above algorithm. " }, { "code": null, "e": 29176, "s": 29172, "text": "C++" }, { "code": null, "e": 29181, "s": 29176, "text": "Java" }, { "code": null, "e": 29189, "s": 29181, "text": "Python3" }, { "code": null, "e": 29192, "s": 29189, "text": "C#" }, { "code": null, "e": 29203, "s": 29192, "text": "Javascript" }, { "code": "#include <cstring>#include <iostream>using namespace std;#define MAX 100 // Structure of a tree nodestruct Node { char key; struct Node *left, *right;}; // A utility function to create a new BST nodeNode* newNode(char item){ Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to store inorder traversal of tree rooted// with root in an array arr[]. Note that i is passed as referencevoid storeInorder(Node* root, char arr[], int& i){ if (root == NULL) { arr[i++] = '$'; return; } storeInorder(root->left, arr, i); arr[i++] = root->key; storeInorder(root->right, arr, i);} // A utility function to store preorder traversal of tree rooted// with root in an array arr[]. Note that i is passed as referencevoid storePreOrder(Node* root, char arr[], int& i){ if (root == NULL) { arr[i++] = '$'; return; } arr[i++] = root->key; storePreOrder(root->left, arr, i); storePreOrder(root->right, arr, i);} /* This function returns true if S is a subtree of T, otherwise false */bool isSubtree(Node* T, Node* S){ /* base cases */ if (S == NULL) return true; if (T == NULL) return false; // Store Inorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively int m = 0, n = 0; char inT[MAX], inS[MAX]; storeInorder(T, inT, m); storeInorder(S, inS, n); inT[m] = '\\0', inS[n] = '\\0'; // If inS[] is not a substring of inT[], return false if (strstr(inT, inS) == NULL) return false; // Store Preorder traversals of T and S in preT[0..m-1] // and preS[0..n-1] respectively m = 0, n = 0; char preT[MAX], preS[MAX]; storePreOrder(T, preT, m); storePreOrder(S, preS, n); preT[m] = '\\0', preS[n] = '\\0'; // If preS[] is not a substring of preT[], return false // Else return true return (strstr(preT, preS) != NULL);} // Driver program to test above functionint main(){ Node* T = newNode('a'); T->left = newNode('b'); T->right = newNode('d'); T->left->left = newNode('c'); T->right->right = newNode('e'); Node* S = newNode('a'); S->left = newNode('b'); S->left->left = newNode('c'); S->right = newNode('d'); if (isSubtree(T, S)) cout << \"Yes: S is a subtree of T\"; else cout << \"No: S is NOT a subtree of T\"; return 0;}", "e": 31595, "s": 29203, "text": null }, { "code": "// Java program to check if binary tree// is subtree of another binary treeclass Node { char data; Node left, right; Node(char item) { data = item; left = right = null; }} class Passing { int i; int m = 0; int n = 0;} class BinaryTree { static Node root; Passing p = new Passing(); String strstr(String haystack, String needle) { if (haystack == null || needle == null) { return null; } int hLength = haystack.length(); int nLength = needle.length(); if (hLength < nLength) { return null; } if (nLength == 0) { return haystack; } for (int i = 0; i <= hLength - nLength; i++) { if (haystack.charAt(i) == needle.charAt(0)) { int j = 0; for (; j < nLength; j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { break; } } if (j == nLength) { return haystack.substring(i); } } } return null; } // A utility function to store inorder traversal of tree rooted // with root in an array arr[]. Note that i is passed as reference void storeInorder(Node node, char arr[], Passing i) { if (node == null) { arr[i.i++] = '$'; return; } storeInorder(node.left, arr, i); arr[i.i++] = node.data; storeInorder(node.right, arr, i); } // A utility function to store preorder traversal of tree rooted // with root in an array arr[]. Note that i is passed as reference void storePreOrder(Node node, char arr[], Passing i) { if (node == null) { arr[i.i++] = '$'; return; } arr[i.i++] = node.data; storePreOrder(node.left, arr, i); storePreOrder(node.right, arr, i); } /* This function returns true if S is a subtree of T, otherwise false */ boolean isSubtree(Node T, Node S) { /* base cases */ if (S == null) { return true; } if (T == null) { return false; } // Store Inorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively char inT[] = new char[100]; String op1 = String.valueOf(inT); char inS[] = new char[100]; String op2 = String.valueOf(inS); storeInorder(T, inT, p); storeInorder(S, inS, p); inT[p.m] = '\\0'; inS[p.m] = '\\0'; // If inS[] is not a substring of preS[], return false if (strstr(op1, op2) != null) { return false; } // Store Preorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively p.m = 0; p.n = 0; char preT[] = new char[100]; char preS[] = new char[100]; String op3 = String.valueOf(preT); String op4 = String.valueOf(preS); storePreOrder(T, preT, p); storePreOrder(S, preS, p); preT[p.m] = '\\0'; preS[p.n] = '\\0'; // If inS[] is not a substring of preS[], return false // Else return true return (strstr(op3, op4) != null); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); Node T = new Node('a'); T.left = new Node('b'); T.right = new Node('d'); T.left.left = new Node('c'); T.right.right = new Node('e'); Node S = new Node('a'); S.left = new Node('b'); S.right = new Node('d'); S.left.left = new Node('c'); if (tree.isSubtree(T, S)) { System.out.println(\"Yes, S is a subtree of T\"); } else { System.out.println(\"No, S is not a subtree of T\"); } }} // This code is contributed by Mayank Jaiswal", "e": 35515, "s": 31595, "text": null }, { "code": "MAX = 100 # class for a tree nodeclass Node: def __init__(self): self.key = ' ' self.left = None self.right = None # A utility function to create a new BST nodedef newNode(item): temp = Node() temp.key = item return temp # A utility function to store inorder traversal of tree rooted# with root in an array arr[]. Note that i is passed as referencedef storeInorder(root, i): if (root == None): return '$' res = storeInorder(root.left, i) res += root.key res += storeInorder(root.right, i) return res # A utility function to store preorder traversal of tree rooted# with root in an array arr[]. Note that i is passed as referencedef storePreOrder(root, i): if (root == None): return '$' res = root.key res += storePreOrder(root.left, i) res += storePreOrder(root.right, i) return res # This function returns true if S is a subtree of T, otherwise falsedef isSubtree(T, S): # base cases if (S == None): return True if (T == None): return False # Store Inorder traversals of T and S in inT[0..m-1] # and inS[0..n-1] respectively m = 0 n = 0 inT = storeInorder(T, m) inS = storeInorder(S, n) # If inS[] is not a substring of inT[], return false res = True if inS in inT: res = True else: res = False if(res == False): return res # Store Preorder traversals of T and S in preT[0..m-1] # and preS[0..n-1] respectively m = 0 n = 0 preT = storePreOrder(T, m) preS = storePreOrder(S, n) # If preS[] is not a substring of preT[], return false # Else return true if preS in preT: return True else: return False # Driver program to test above functionT = newNode('a')T.left = newNode('b')T.right = newNode('d')T.left.left = newNode('c')T.right.right = newNode('e') S = newNode('a')S.left = newNode('b')S.left.left = newNode('c')S.right = newNode('d') if (isSubtree(T, S)): print(\"Yes: S is a subtree of T\")else: print(\"No: S is NOT a subtree of T\") # This code is contributed by rj13to.", "e": 37602, "s": 35515, "text": null }, { "code": "// C# program to check if binary tree is// subtree of another binary treeusing System; public class Node { public char data; public Node left, right; public Node(char item) { data = item; left = right = null; }} public class Passing { public int i; public int m = 0; public int n = 0;} public class BinaryTree { static Node root; Passing p = new Passing(); String strstr(String haystack, String needle) { if (haystack == null || needle == null) { return null; } int hLength = haystack.Length; int nLength = needle.Length; if (hLength < nLength) { return null; } if (nLength == 0) { return haystack; } for (int i = 0; i <= hLength - nLength; i++) { if (haystack[i] == needle[0]) { int j = 0; for (; j < nLength; j++) { if (haystack[i + j] != needle[j]) { break; } } if (j == nLength) { return haystack.Substring(i); } } } return null; } // A utility function to store inorder // traversal of tree rooted with root in // an array arr[]. Note that i is passed as reference void storeInorder(Node node, char[] arr, Passing i) { if (node == null) { arr[i.i++] = '$'; return; } storeInorder(node.left, arr, i); arr[i.i++] = node.data; storeInorder(node.right, arr, i); } // A utility function to store preorder // traversal of tree rooted with root in // an array arr[]. Note that i is passed as reference void storePreOrder(Node node, char[] arr, Passing i) { if (node == null) { arr[i.i++] = '$'; return; } arr[i.i++] = node.data; storePreOrder(node.left, arr, i); storePreOrder(node.right, arr, i); } /* This function returns true if S is a subtree of T, otherwise false */ bool isSubtree(Node T, Node S) { /* base cases */ if (S == null) { return true; } if (T == null) { return false; } // Store Inorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively char[] inT = new char[100]; String op1 = String.Join(\"\", inT); char[] inS = new char[100]; String op2 = String.Join(\"\", inS); storeInorder(T, inT, p); storeInorder(S, inS, p); inT[p.m] = '\\0'; inS[p.m] = '\\0'; // If inS[] is not a substring of preS[], return false if (strstr(op1, op2) != null) { return false; } // Store Preorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively p.m = 0; p.n = 0; char[] preT = new char[100]; char[] preS = new char[100]; String op3 = String.Join(\"\", preT); String op4 = String.Join(\"\", preS); storePreOrder(T, preT, p); storePreOrder(S, preS, p); preT[p.m] = '\\0'; preS[p.n] = '\\0'; // If inS[] is not a substring of preS[], return false // Else return true return (strstr(op3, op4) != null); } // Driver program to test above functions public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); Node T = new Node('a'); T.left = new Node('b'); T.right = new Node('d'); T.left.left = new Node('c'); T.right.right = new Node('e'); Node S = new Node('a'); S.left = new Node('b'); S.right = new Node('d'); S.left.left = new Node('c'); if (tree.isSubtree(T, S)) { Console.WriteLine(\"Yes, S is a subtree of T\"); } else { Console.WriteLine(\"No, S is not a subtree of T\"); } }} // This code contributed by Rajput-Ji", "e": 41571, "s": 37602, "text": null }, { "code": "<script> const MAX = 100 // class for a tree nodeclass Node{ constructor(){ this.key = ' ' this.left = null this.right = null }} // A utility function to create a new BST nodefunction newNode(item){ temp = new Node() temp.key = item return temp} // A utility function to store inorder traversal of tree rooted// with root in an array arr[]. Note that i is passed as referencefunction storeInorder(root, i){ if (root == null) return '$' res = storeInorder(root.left, i) res += root.key res += storeInorder(root.right, i) return res} // A utility function to store preorder traversal of tree rooted// with root in an array arr[]. Note that i is passed as referencefunction storePreOrder(root, i){ if (root == null) return '$' res = root.key res += storePreOrder(root.left, i) res += storePreOrder(root.right, i) return res} // This function returns true if S is a subtree of T, otherwise falsefunction isSubtree(T, S){ // base cases if (S == null) return true if (T == null) return false // Store Inorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively let m = 0 let n = 0 let inT = storeInorder(T, m) let inS = storeInorder(S, n) // If inS[] is not a substring of inT[], return false res = true if(inT.indexOf(inT) !== -1) res = true else res = false if(res == false) return res // Store Preorder traversals of T and S in preT[0..m-1] // and preS[0..n-1] respectively m = 0 n = 0 let preT = storePreOrder(T, m) let preS = storePreOrder(S, n) // If preS[] is not a substring of preT[], return false // Else return true if(preT.indexOf(preS) !== -1) return true else return false} // Driver program to test above function let T = new newNode('a')T.left = new newNode('b')T.right = new newNode('d')T.left.left = new newNode('c')T.right.right = new newNode('e') let S = new newNode('a')S.left = new newNode('b')S.left.left = new newNode('c')S.right = new newNode('d') if (isSubtree(T, S)) document.write(\"Yes: S is a subtree of T\",\"</br>\")else document.write(\"No: S is NOT a subtree of T\",\"</br>\") // This code is contributed by shinjanpatra </script>", "e": 43850, "s": 41571, "text": null }, { "code": null, "e": 43859, "s": 43850, "text": "Output: " }, { "code": null, "e": 43887, "s": 43859, "text": "No: S is NOT a subtree of T" }, { "code": null, "e": 44260, "s": 43887, "text": "Time Complexity: Inorder and Preorder traversals of Binary Tree take O(n) time. The function strstr() can also be implemented in O(n) time using KMP string matching algorithm.Auxiliary Space: O(n)Thanks to Ashwini Singh for suggesting this method. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 44270, "s": 44260, "text": "Rajput-Ji" }, { "code": null, "e": 44282, "s": 44270, "text": "aayushpatni" }, { "code": null, "e": 44289, "s": 44282, "text": "rj13to" }, { "code": null, "e": 44309, "s": 44289, "text": "vivekmaddheshiya205" }, { "code": null, "e": 44322, "s": 44309, "text": "shinjanpatra" }, { "code": null, "e": 44329, "s": 44322, "text": "Amazon" }, { "code": null, "e": 44345, "s": 44329, "text": "Cavisson System" }, { "code": null, "e": 44356, "s": 44345, "text": "MakeMyTrip" }, { "code": null, "e": 44366, "s": 44356, "text": "Microsoft" }, { "code": null, "e": 44371, "s": 44366, "text": "Tree" }, { "code": null, "e": 44378, "s": 44371, "text": "Amazon" }, { "code": null, "e": 44388, "s": 44378, "text": "Microsoft" }, { "code": null, "e": 44399, "s": 44388, "text": "MakeMyTrip" }, { "code": null, "e": 44415, "s": 44399, "text": "Cavisson System" }, { "code": null, "e": 44420, "s": 44415, "text": "Tree" }, { "code": null, "e": 44518, "s": 44420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44532, "s": 44518, "text": "Decision Tree" }, { "code": null, "e": 44568, "s": 44532, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 44584, "s": 44568, "text": "Expression Tree" }, { "code": null, "e": 44610, "s": 44584, "text": "Deletion in a Binary Tree" }, { "code": null, "e": 44638, "s": 44610, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 44665, "s": 44638, "text": "BFS vs DFS for Binary Tree" }, { "code": null, "e": 44700, "s": 44665, "text": "Binary Tree (Array implementation)" }, { "code": null, "e": 44729, "s": 44700, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 44789, "s": 44729, "text": "Inorder Tree Traversal without recursion and without stack!" } ]
Expression Parsing Using Stack
Infix notation is easier for humans to read and understand whereas for electronic machines like computers, postfix is the best form of expression to parse. We shall see here a program to convert and evaluate infix notation to postfix notation − #include<stdio.h> #include<string.h> //char stack char stack[25]; int top = -1; void push(char item) { stack[++top] = item; } char pop() { return stack[top--]; } //returns precedence of operators int precedence(char symbol) { switch(symbol) { case '+': case '-': return 2; break; case '*': case '/': return 3; break; case '^': return 4; break; case '(': case ')': case '#': return 1; break; } } //check whether the symbol is operator? int isOperator(char symbol) { switch(symbol) { case '+': case '-': case '*': case '/': case '^': case '(': case ')': return 1; break; default: return 0; } } //converts infix expression to postfix void convert(char infix[],char postfix[]) { int i,symbol,j = 0; stack[++top] = '#'; for(i = 0;i<strlen(infix);i++) { symbol = infix[i]; if(isOperator(symbol) == 0) { postfix[j] = symbol; j++; } else { if(symbol == '(') { push(symbol); } else { if(symbol == ')') { while(stack[top] != '(') { postfix[j] = pop(); j++; } pop(); //pop out (. } else { if(precedence(symbol)>precedence(stack[top])) { push(symbol); } else { while(precedence(symbol)<=precedence(stack[top])) { postfix[j] = pop(); j++; } push(symbol); } } } } } while(stack[top] != '#') { postfix[j] = pop(); j++; } postfix[j]='\0'; //null terminate string. } //int stack int stack_int[25]; int top_int = -1; void push_int(int item) { stack_int[++top_int] = item; } char pop_int() { return stack_int[top_int--]; } //evaluates postfix expression int evaluate(char *postfix){ char ch; int i = 0,operand1,operand2; while( (ch = postfix[i++]) != '\0') { if(isdigit(ch)) { push_int(ch-'0'); // Push the operand } else { //Operator,pop two operands operand2 = pop_int(); operand1 = pop_int(); switch(ch) { case '+': push_int(operand1+operand2); break; case '-': push_int(operand1-operand2); break; case '*': push_int(operand1*operand2); break; case '/': push_int(operand1/operand2); break; } } } return stack_int[top_int]; } void main() { char infix[25] = "1*(2+3)",postfix[25]; convert(infix,postfix); printf("Infix expression is: %s\n" , infix); printf("Postfix expression is: %s\n" , postfix); printf("Evaluated expression is: %d\n" , evaluate(postfix)); } If we compile and run the above program, it will produce the following result − Infix expression is: 1*(2+3) Postfix expression is: 123+* Result is: 5 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2825, "s": 2580, "text": "Infix notation is easier for humans to read and understand whereas for electronic machines like computers, postfix is the best form of expression to parse. We shall see here a program to convert and evaluate infix notation to postfix notation −" }, { "code": null, "e": 5974, "s": 2825, "text": "#include<stdio.h> \n#include<string.h> \n\n//char stack\nchar stack[25]; \nint top = -1; \n\nvoid push(char item) {\n stack[++top] = item; \n} \n\nchar pop() {\n return stack[top--]; \n} \n\n//returns precedence of operators\nint precedence(char symbol) {\n\n switch(symbol) {\n case '+': \n case '-':\n return 2; \n break; \n case '*': \n case '/':\n return 3; \n break; \n case '^': \n return 4; \n break; \n case '(': \n case ')': \n case '#':\n return 1; \n break; \n } \n} \n\n//check whether the symbol is operator?\nint isOperator(char symbol) {\n\n switch(symbol) {\n case '+': \n case '-': \n case '*': \n case '/': \n case '^': \n case '(': \n case ')':\n return 1; \n break; \n default:\n return 0; \n } \n} \n\n//converts infix expression to postfix\nvoid convert(char infix[],char postfix[]) {\n int i,symbol,j = 0; \n stack[++top] = '#'; \n\t\n for(i = 0;i<strlen(infix);i++) {\n symbol = infix[i]; \n\t\t\n if(isOperator(symbol) == 0) {\n postfix[j] = symbol; \n j++; \n } else {\n if(symbol == '(') {\n push(symbol); \n } else {\n if(symbol == ')') {\n\t\t\t\t\n while(stack[top] != '(') {\n postfix[j] = pop(); \n j++; \n } \n\t\t\t\t\t\n pop(); //pop out (. \n } else {\n if(precedence(symbol)>precedence(stack[top])) {\n push(symbol); \n } else {\n\t\t\t\t\t\n while(precedence(symbol)<=precedence(stack[top])) {\n postfix[j] = pop(); \n j++; \n } \n\t\t\t\t\t\t\n push(symbol); \n }\n }\n }\n }\n }\n\t\n while(stack[top] != '#') {\n postfix[j] = pop(); \n j++; \n } \n\t\n postfix[j]='\\0'; //null terminate string. \n} \n\n//int stack\nint stack_int[25]; \nint top_int = -1; \n\nvoid push_int(int item) {\n stack_int[++top_int] = item; \n} \n\nchar pop_int() {\n return stack_int[top_int--]; \n} \n\n//evaluates postfix expression\nint evaluate(char *postfix){\n\n char ch;\n int i = 0,operand1,operand2;\n\n while( (ch = postfix[i++]) != '\\0') {\n\t\n if(isdigit(ch)) {\n\t push_int(ch-'0'); // Push the operand \n } else {\n //Operator,pop two operands \n operand2 = pop_int();\n operand1 = pop_int();\n\t\t\t\n switch(ch) {\n case '+':\n push_int(operand1+operand2);\n break;\n case '-':\n push_int(operand1-operand2);\n break;\n case '*':\n push_int(operand1*operand2);\n break;\n case '/':\n push_int(operand1/operand2);\n break;\n }\n }\n }\n\t\n return stack_int[top_int];\n}\n\nvoid main() { \n char infix[25] = \"1*(2+3)\",postfix[25]; \n convert(infix,postfix); \n\t\n printf(\"Infix expression is: %s\\n\" , infix);\n printf(\"Postfix expression is: %s\\n\" , postfix);\n printf(\"Evaluated expression is: %d\\n\" , evaluate(postfix));\n} " }, { "code": null, "e": 6054, "s": 5974, "text": "If we compile and run the above program, it will produce the following result −" }, { "code": null, "e": 6126, "s": 6054, "text": "Infix expression is: 1*(2+3)\nPostfix expression is: 123+*\nResult is: 5\n" }, { "code": null, "e": 6161, "s": 6126, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6173, "s": 6161, "text": " Ravi Kiran" }, { "code": null, "e": 6208, "s": 6173, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 6227, "s": 6208, "text": " Arnab Chakraborty" }, { "code": null, "e": 6262, "s": 6227, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6277, "s": 6262, "text": " Parth Panjabi" }, { "code": null, "e": 6310, "s": 6277, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 6329, "s": 6310, "text": " Arnab Chakraborty" }, { "code": null, "e": 6363, "s": 6329, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6391, "s": 6363, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6427, "s": 6391, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 6455, "s": 6427, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6462, "s": 6455, "text": " Print" }, { "code": null, "e": 6473, "s": 6462, "text": " Add Notes" } ]
LISP - Arithmetic Operators
The following table shows all the arithmetic operators supported by LISP. Assume variable A holds 10 and variable B holds 20 then − Create a new source code file named main.lisp and type the following code in it. (setq a 10) (setq b 20) (format t "~% A + B = ~d" (+ a b)) (format t "~% A - B = ~d" (- a b)) (format t "~% A x B = ~d" (* a b)) (format t "~% B / A = ~d" (/ b a)) (format t "~% Increment A by 3 = ~d" (incf a 3)) (format t "~% Decrement A by 4 = ~d" (decf a 4)) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − A + B = 30 A - B = -10 A x B = 200 B / A = 2 Increment A by 3 = 13 Decrement A by 4 = 9 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2192, "s": 2060, "text": "The following table shows all the arithmetic operators supported by LISP. Assume variable A holds 10 and variable B holds 20 then −" }, { "code": null, "e": 2273, "s": 2192, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 2535, "s": 2273, "text": "(setq a 10)\n(setq b 20)\n(format t \"~% A + B = ~d\" (+ a b))\n(format t \"~% A - B = ~d\" (- a b))\n(format t \"~% A x B = ~d\" (* a b))\n(format t \"~% B / A = ~d\" (/ b a))\n(format t \"~% Increment A by 3 = ~d\" (incf a 3))\n(format t \"~% Decrement A by 4 = ~d\" (decf a 4))" }, { "code": null, "e": 2644, "s": 2535, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 2733, "s": 2644, "text": "A + B = 30\nA - B = -10\nA x B = 200\nB / A = 2\nIncrement A by 3 = 13\nDecrement A by 4 = 9\n" }, { "code": null, "e": 2766, "s": 2733, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 2781, "s": 2766, "text": " Arnold Higuit" }, { "code": null, "e": 2788, "s": 2781, "text": " Print" }, { "code": null, "e": 2799, "s": 2788, "text": " Add Notes" } ]
A Comparison of Seaborn and Altair | by Soner Yıldırım | Towards Data Science
Data visualization is a substantial part of data science. It helps to better understand the data by unveiling the relationships among variables. The underlying structure within a dataset can also be explored using well-designed data visualizations. In this article, we will compare two popular data visualization libraries for Python: Seaborn and Altair. The comparison will be based on creating 3 sets of visualizations using both libraries. The focus of comparison is on the syntax, the structure of figures, and how these libraries handle the relationships between variables. We will use a marketing dataset to create the visualizations. Let’s start by importing the dependencies and reading the dataset into a Pandas dataframe. import numpy as npimport pandas as pdimport seaborn as snsimport altair as altdf_marketing = pd.read_csv("/content/DirectMarketing.csv")df_marketing.head() The first set of visualizations includes basic histogram plots. In Seaborn, we pass the name of the dataframe and the name of the column to be plotted. The height and aspect parameters are used to modify the size of the plot. Aspect is the ratio of the width to height. sns.displot(df_marketing, x='AmountSpent', aspect=1.5) In Altair, we start with a top-level Chart object which takes the dataframe as argument. Then we specify the type of plot. The encode function takes the columns, relations, and transformations to be plotted. Anything we put in the encode function needs to be linked to the dataframe passed to the Chart. Finally, the properties function adjusts the size of the plot. alt.Chart(df_marketing).mark_bar().encode( alt.X('AmountSpent:Q', bin=True), y='count()').properties(height=300, width=450) Altair is quite efficient at data transformations. Let’s explain the transformation done to create the above histogram. alt.X('AmountSpent:Q', bin=True), y='count()' What this line does is that it divides the amount spent column into bins and count the number of data points in each bin. Both Seaborn and Altair provides simple ways to distinguish the data points of numerical variables based on different groups in categorical variables. In Seaborn, this separation can be achieved by hue, col, or row parameters. Following code will return a scatter plot of the amount spent and salary columns and separation will be done according to gender. sns.relplot( data=df_marketing, x='AmountSpent', y='Salary', kind='scatter', hue='Gender', aspect=1.5) In Altair, we use the color parameter inside the encode function. It is similar to the hue parameter of Seaborn. alt.Chart(df_marketing).mark_circle().encode( x='AmountSpent', y='Salary', color='Gender').properties(height=300, width=450) In some cases, it is more appealing or informative to use multiple plots in one visualization. Each subplot can be used to emphasize a certain feature or relationship so the overall visualization conveys more information. There are many ways to create multi-plot visualizations. In Seaborn, we can use the pyplot interface of Matplotlib to manually create a grid by specifying the number of Axes objects in a Figure. Then we can generate a plot for each Axes object. Another way is to use the FacetGrid or PairGrid to automatically generate a grid of plots. Based on the given variables (i.e. features), FacetGrid creates a grid of subplots which allows for transferring the structure of the dataset to the visualization. Row, col, and hue parameters can be considered as the three dimensions of FacetGrid objects. g = sns.FacetGrid( data=df_marketing, col='Gender', row='Location', hue='OwnHome', height=4, aspect=1.4)g.map(sns.scatterplot, "Salary", "AmountSpent").add_legend() We first construct the pattern using the hue, col, and row parameters. Hue parameter uses different colors for separation whereas col and row parameters use x axis and y axis, respectively. Then the map function is used to specify the type of plot along with the variables (i.e. columns in dataframe) to be plotted. In Altair, the logic for creating such grids is quite similar to Seaborn. alt.Chart(df_marketing).mark_circle().encode( x='AmountSpent', y='Salary', color='OwnHome', column='Gender', row='Location').properties(height=200, width=300) In addition to the color parameter, we use the column and row parameters in the encode function to add dimensions to the returned visualization. Both Seaborn and Altair are popular data visualization libraries for Python. Either one will be enough for most of the data visualizations tasks. There are small advantages of one over another in different aspects. I think the syntax of Seaborn is a little simpler and easier to read than the syntax of Altair. On the other hand, Altair is superior to Seaborn with respect to data transformations. Altair also provides interactive visualizations. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 420, "s": 171, "text": "Data visualization is a substantial part of data science. It helps to better understand the data by unveiling the relationships among variables. The underlying structure within a dataset can also be explored using well-designed data visualizations." }, { "code": null, "e": 526, "s": 420, "text": "In this article, we will compare two popular data visualization libraries for Python: Seaborn and Altair." }, { "code": null, "e": 750, "s": 526, "text": "The comparison will be based on creating 3 sets of visualizations using both libraries. The focus of comparison is on the syntax, the structure of figures, and how these libraries handle the relationships between variables." }, { "code": null, "e": 903, "s": 750, "text": "We will use a marketing dataset to create the visualizations. Let’s start by importing the dependencies and reading the dataset into a Pandas dataframe." }, { "code": null, "e": 1059, "s": 903, "text": "import numpy as npimport pandas as pdimport seaborn as snsimport altair as altdf_marketing = pd.read_csv(\"/content/DirectMarketing.csv\")df_marketing.head()" }, { "code": null, "e": 1123, "s": 1059, "text": "The first set of visualizations includes basic histogram plots." }, { "code": null, "e": 1329, "s": 1123, "text": "In Seaborn, we pass the name of the dataframe and the name of the column to be plotted. The height and aspect parameters are used to modify the size of the plot. Aspect is the ratio of the width to height." }, { "code": null, "e": 1384, "s": 1329, "text": "sns.displot(df_marketing, x='AmountSpent', aspect=1.5)" }, { "code": null, "e": 1751, "s": 1384, "text": "In Altair, we start with a top-level Chart object which takes the dataframe as argument. Then we specify the type of plot. The encode function takes the columns, relations, and transformations to be plotted. Anything we put in the encode function needs to be linked to the dataframe passed to the Chart. Finally, the properties function adjusts the size of the plot." }, { "code": null, "e": 1876, "s": 1751, "text": "alt.Chart(df_marketing).mark_bar().encode( alt.X('AmountSpent:Q', bin=True), y='count()').properties(height=300, width=450)" }, { "code": null, "e": 1996, "s": 1876, "text": "Altair is quite efficient at data transformations. Let’s explain the transformation done to create the above histogram." }, { "code": null, "e": 2042, "s": 1996, "text": "alt.X('AmountSpent:Q', bin=True), y='count()'" }, { "code": null, "e": 2164, "s": 2042, "text": "What this line does is that it divides the amount spent column into bins and count the number of data points in each bin." }, { "code": null, "e": 2315, "s": 2164, "text": "Both Seaborn and Altair provides simple ways to distinguish the data points of numerical variables based on different groups in categorical variables." }, { "code": null, "e": 2521, "s": 2315, "text": "In Seaborn, this separation can be achieved by hue, col, or row parameters. Following code will return a scatter plot of the amount spent and salary columns and separation will be done according to gender." }, { "code": null, "e": 2631, "s": 2521, "text": "sns.relplot( data=df_marketing, x='AmountSpent', y='Salary', kind='scatter', hue='Gender', aspect=1.5)" }, { "code": null, "e": 2744, "s": 2631, "text": "In Altair, we use the color parameter inside the encode function. It is similar to the hue parameter of Seaborn." }, { "code": null, "e": 2870, "s": 2744, "text": "alt.Chart(df_marketing).mark_circle().encode( x='AmountSpent', y='Salary', color='Gender').properties(height=300, width=450)" }, { "code": null, "e": 3092, "s": 2870, "text": "In some cases, it is more appealing or informative to use multiple plots in one visualization. Each subplot can be used to emphasize a certain feature or relationship so the overall visualization conveys more information." }, { "code": null, "e": 3337, "s": 3092, "text": "There are many ways to create multi-plot visualizations. In Seaborn, we can use the pyplot interface of Matplotlib to manually create a grid by specifying the number of Axes objects in a Figure. Then we can generate a plot for each Axes object." }, { "code": null, "e": 3685, "s": 3337, "text": "Another way is to use the FacetGrid or PairGrid to automatically generate a grid of plots. Based on the given variables (i.e. features), FacetGrid creates a grid of subplots which allows for transferring the structure of the dataset to the visualization. Row, col, and hue parameters can be considered as the three dimensions of FacetGrid objects." }, { "code": null, "e": 3857, "s": 3685, "text": "g = sns.FacetGrid( data=df_marketing, col='Gender', row='Location', hue='OwnHome', height=4, aspect=1.4)g.map(sns.scatterplot, \"Salary\", \"AmountSpent\").add_legend()" }, { "code": null, "e": 4173, "s": 3857, "text": "We first construct the pattern using the hue, col, and row parameters. Hue parameter uses different colors for separation whereas col and row parameters use x axis and y axis, respectively. Then the map function is used to specify the type of plot along with the variables (i.e. columns in dataframe) to be plotted." }, { "code": null, "e": 4247, "s": 4173, "text": "In Altair, the logic for creating such grids is quite similar to Seaborn." }, { "code": null, "e": 4408, "s": 4247, "text": "alt.Chart(df_marketing).mark_circle().encode( x='AmountSpent', y='Salary', color='OwnHome', column='Gender', row='Location').properties(height=200, width=300)" }, { "code": null, "e": 4553, "s": 4408, "text": "In addition to the color parameter, we use the column and row parameters in the encode function to add dimensions to the returned visualization." }, { "code": null, "e": 4768, "s": 4553, "text": "Both Seaborn and Altair are popular data visualization libraries for Python. Either one will be enough for most of the data visualizations tasks. There are small advantages of one over another in different aspects." }, { "code": null, "e": 5000, "s": 4768, "text": "I think the syntax of Seaborn is a little simpler and easier to read than the syntax of Altair. On the other hand, Altair is superior to Seaborn with respect to data transformations. Altair also provides interactive visualizations." } ]
Currency getCurrencyCode() Method in Java with Examples - GeeksforGeeks
27 Dec, 2018 The getCurrencyCode() Method of Currency class in Java is used to retrieve the currency code of this currency which is actually the official ISO 4217 currency code. Syntax: CURRENCY.getCurrencyCode() Parameters: This method does not accept any parameters. Return Value: This method returns the ISO 4217 currency code of the currency. Exceptions: The method throws Runtime Error if an invalid code is called. Below program illustrates the working of getCurrencyCode() method: Program 1: // Java Code to illustrate// getCurrencyCode() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { // Creating a currency with the code Currency curr_ency = Currency.getInstance("INR"); // Getting the currency code String currency_code = curr_ency.getCurrencyCode(); System.out.println("Currency Code of India is: " + currency_code); }} Currency Code of India is: INR Program 2: // Java Code to illustrate// getCurrencyCode() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { // Creating a currency with the code Currency curr_ency = Currency.getInstance("USD"); // Getting the currency code String currency_code = curr_ency.getCurrencyCode(); System.out.println("Currency Code of USA is: " + currency_code); }} Currency Code of USA is: USD Program 3: For an invalid Currency Code. // Java Code to illustrate getCurrencyCode() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { try { // Creating a currency with the code Currency curr_ency = Currency.getInstance("USDA"); // Getting the currency code String currency_code = curr_ency.getCurrencyCode(); System.out.println("Invalid Currency Code: " + currency_code); } catch (Exception e) { System.out.println(e); } }} java.lang.IllegalArgumentException Java - util package Java-Currency Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Initialize an ArrayList in Java Overriding in Java Collections in Java Singleton Class in Java Multithreading in Java
[ { "code": null, "e": 24448, "s": 24420, "text": "\n27 Dec, 2018" }, { "code": null, "e": 24613, "s": 24448, "text": "The getCurrencyCode() Method of Currency class in Java is used to retrieve the currency code of this currency which is actually the official ISO 4217 currency code." }, { "code": null, "e": 24621, "s": 24613, "text": "Syntax:" }, { "code": null, "e": 24648, "s": 24621, "text": "CURRENCY.getCurrencyCode()" }, { "code": null, "e": 24704, "s": 24648, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 24782, "s": 24704, "text": "Return Value: This method returns the ISO 4217 currency code of the currency." }, { "code": null, "e": 24856, "s": 24782, "text": "Exceptions: The method throws Runtime Error if an invalid code is called." }, { "code": null, "e": 24923, "s": 24856, "text": "Below program illustrates the working of getCurrencyCode() method:" }, { "code": null, "e": 24934, "s": 24923, "text": "Program 1:" }, { "code": "// Java Code to illustrate// getCurrencyCode() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { // Creating a currency with the code Currency curr_ency = Currency.getInstance(\"INR\"); // Getting the currency code String currency_code = curr_ency.getCurrencyCode(); System.out.println(\"Currency Code of India is: \" + currency_code); }}", "e": 25414, "s": 24934, "text": null }, { "code": null, "e": 25446, "s": 25414, "text": "Currency Code of India is: INR\n" }, { "code": null, "e": 25457, "s": 25446, "text": "Program 2:" }, { "code": "// Java Code to illustrate// getCurrencyCode() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { // Creating a currency with the code Currency curr_ency = Currency.getInstance(\"USD\"); // Getting the currency code String currency_code = curr_ency.getCurrencyCode(); System.out.println(\"Currency Code of USA is: \" + currency_code); }}", "e": 25935, "s": 25457, "text": null }, { "code": null, "e": 25965, "s": 25935, "text": "Currency Code of USA is: USD\n" }, { "code": null, "e": 26006, "s": 25965, "text": "Program 3: For an invalid Currency Code." }, { "code": "// Java Code to illustrate getCurrencyCode() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { try { // Creating a currency with the code Currency curr_ency = Currency.getInstance(\"USDA\"); // Getting the currency code String currency_code = curr_ency.getCurrencyCode(); System.out.println(\"Invalid Currency Code: \" + currency_code); } catch (Exception e) { System.out.println(e); } }}", "e": 26607, "s": 26006, "text": null }, { "code": null, "e": 26643, "s": 26607, "text": "java.lang.IllegalArgumentException\n" }, { "code": null, "e": 26663, "s": 26643, "text": "Java - util package" }, { "code": null, "e": 26677, "s": 26663, "text": "Java-Currency" }, { "code": null, "e": 26692, "s": 26677, "text": "Java-Functions" }, { "code": null, "e": 26697, "s": 26692, "text": "Java" }, { "code": null, "e": 26702, "s": 26697, "text": "Java" }, { "code": null, "e": 26800, "s": 26702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26809, "s": 26800, "text": "Comments" }, { "code": null, "e": 26822, "s": 26809, "text": "Old Comments" }, { "code": null, "e": 26852, "s": 26822, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26871, "s": 26852, "text": "Interfaces in Java" }, { "code": null, "e": 26922, "s": 26871, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26940, "s": 26922, "text": "ArrayList in Java" }, { "code": null, "e": 26971, "s": 26940, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27003, "s": 26971, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27022, "s": 27003, "text": "Overriding in Java" }, { "code": null, "e": 27042, "s": 27022, "text": "Collections in Java" }, { "code": null, "e": 27066, "s": 27042, "text": "Singleton Class in Java" } ]
Understanding DBSCAN and K-NN with Random Geometric Graphs | by Bruno Gonçalves | Towards Data Science
In this post, we explore in more detail the specific properties of spatial networks and use them to gain some insight into two popular Machine Learning algorithms, k-Nearest Neighbors and DBSCAN. We start our exploration of Spatial Networks by focusing on its simplest example, the Random Geometric Graph (RGG). RGGs are constructed by simply placing nodes at random in some (say, 2D) space and adding an edge between any pair of nodes that is within a certain distance d. While this construction might seem like the kind of stuff that only the purest of mathematicians might play with, it is a surprisingly useful graph structure with real world practical applications in ad-hoc networks such as the ones used to connect drones in close proximity. Amazon even has a recent patent for this kind of application, that you can read more over at the USPTO and researchers at the University of Nevada Robotics Lab proposed an algorithm for drones to coordinate search and rescue operations. Without further ado, let us build our very own RGG. We start by randomly placing 100 nodes in the unit square: The next step is to connect all the nodes that are within a certain distance, d. For this we compute the distance matrix containing the distance between all pairs of nodes. Computing the full distance matrix is a bit wasteful as it requires O(N2) work. A more sophisticated approach would use KDTrees to achieve linear performance, but that’s beyond the scope of this post as we’re just trying to get familiar with these concepts instead of developing a practical implementation. Using this matrix we can easily compute the distribution of distances, P(d) and the cumulative distribution of distances, C(d), between each pair of nodes. The distribution follows a quasi-bell shaped curve (the real distribution is a bit more interesting). From the cumulative distribution, it becomes clear that depending on what the threshold d we choose to use for our RGG then we will get more or less edges. In the GitHub repository, you can play around with an interactive tool to see how the distance matrix and Graph change as you change the threshold: If you’re more mathematically inclined, you can think of this thresholded distance matrix as a weighted adjacency matrix for the graph. We will have a lot more to say about Adjacency Matrices in future posts but for now all you need to know is that an adjacency matrix is just a matrix where each non-zero element corresponds to an individual edge between two nodes. The k-Nearest Neighbors algorithm is a well known family of a Machine Learning algorithms that can be used for classification or regression. The fundamental idea in both cases is fairly straightforward. If you want to know what the label or value of a new data point should be, you can consult its k-nearest neighbors and simply go with the majority. The specific value of k is a hyper parameter that must be defined when training the model. The connection with Random Geometric Graphs should now be clear. Instead of just connecting each node with every other node within a certain distance d we simply connect it with its k nearest nodes. When we play this game and connect each of our previous nodes to its 5 nearest neighbors we obtain: If you examine this matrix closely you’ll start noticing something... unusual. It is not symmetric! The easiest place to confirm this is along the main diagonal where you will occasionally notice a value on one side than isn’t present on the other. This seems like a pretty strange result. If our distance metric is symmetric, and the euclidean distance certainly is, then how can the network not be symmetric? The reason can be made clear with a simple example. Imagine that for some strange twist of fate, you find yourself completely alone and lost in the middle of the Sahara desert. The 5 people that at that precise moment are geographically closest to you might be in whatever the nearest city is, but they will all have many other people closer to them than you! You’re just a weird... outlier. One way to verify this intuition is to check the in-degree distribution of the nodes. You’ll find that unlike the out-degree where each node has exactly k outgoing edges, a node can have either more or fewer incoming edges depending on how close to the periphery of cluster it is and how many outliers there are. Here lies the fundamental insight that this graph perspective can give use about k-NN algorithms. Nodes that are more central will be connected through many short-distance links while outliers will be connected to nodes that are far away and have few or not incoming edges at all. A visualization can drive this point home. Here we plot the directed graph corresponding to the distance matrix in the previous figure. If you look closely at the isolated nodes close to the center of the figure you’ll notice that while it has 5 long outgoing edges it has only one incoming one due to its peripheral position... lost and alone in the middle of the Sahara. Naturally, if we were to measure the distance distribution in this graph it would look very different from the one we saw before as we severely restricting the distances allowed by keeping only the k shortest outgoing edges for each node. Density-Based Spatial Clustering of Applications with Noise (DBSCAN) is an unsupervised clustering algorithm that has the explicit goal of identifying clusters of arbitrary shapes in an efficient way. The original KDD paper outlines the algorithm as: To find a cluster, DBSCAN starts with an arbitrary point p and retrieves all points density-reachable from p wrt. Eps and MinPts. If p is a core point, this procedure yields a cluster wrt. Eps and MinPts (see Lemma 2). If p is a border point, no points are density-reachable from p and DBSCAN visits the next point of the database. We can put this algorithm into a more intuitive way of by casting it into a network algorithm that explicitly takes advantage of the features of RGG and k-NN algorithms we discussed above. DBSCAN identifies clusters in data sets by connecting (with directed edges) points (nodes) that lie less than a certain distance away (like in RGGs). Peripheral and outlier nodes have fewer than k out-going (like in k-NN). By contrast, any node that has k or more neighbors within the prescribed distance is said to be a “core node”. Finally, clusters in the data can be uniquely identified with the connected components in the resulting graph. This approach of explicitly building out neighborhood of each node is computationally intensive and requires O(N2) storage space while more efficient implementations (as the one in the original paper) can reduce memory and computational requirements significantly. def net_DBSCAN(X, eps=0.17, min_samples=5): # Building the neighborhood matrix and truncate it # at the maximum distance matrix = distance_matrix(X, X) matrix[matrix >= eps] = 0 # Build the directed graph using the non-zero elements of the matrix G = nx.DiGraph() G.add_edges_from(np.asarray(np.nonzero(matrix)).T) # Create an undirected version of the network for ease of core computation G2 = G.to_undirected() # Find all core nodes results = {} results['core_sample_indices_'] = [node_i for node_i, k in G2.degree() if k >= min_samples-1] # Use the connected components to label each node # as belonging to each cluster labels = [] for label, comp in enumerate(nx.connected_components(G2)): for node in comp: labels.append(label) results['labels_'] = np.asarray(labels) results['G'] = G # Identify the outlier nodes. results['non_core'] = set(np.arange(X.shape[0])) - set(results['core_sample_indices_']) return results When we apply the code above to the two moons dataset, we obtain: Where blue and purple identify the two clusters in the dataset and the green squares are the ‘non-core’ nodes. A perfect match with the sklearn implementation: We hope you enjoyed this way of looking at the venerable k-NN and DBSCAN algorithms and that you gained some new insights about how they work. You can find all the code for the analysis in this post in our companion GitHub Repository https://github.com/DataForScience/Graphs4Sci And of course, don’t forget to Sign Up to my newsletter so that you never miss another post.
[ { "code": null, "e": 243, "s": 47, "text": "In this post, we explore in more detail the specific properties of spatial networks and use them to gain some insight into two popular Machine Learning algorithms, k-Nearest Neighbors and DBSCAN." }, { "code": null, "e": 520, "s": 243, "text": "We start our exploration of Spatial Networks by focusing on its simplest example, the Random Geometric Graph (RGG). RGGs are constructed by simply placing nodes at random in some (say, 2D) space and adding an edge between any pair of nodes that is within a certain distance d." }, { "code": null, "e": 796, "s": 520, "text": "While this construction might seem like the kind of stuff that only the purest of mathematicians might play with, it is a surprisingly useful graph structure with real world practical applications in ad-hoc networks such as the ones used to connect drones in close proximity." }, { "code": null, "e": 1033, "s": 796, "text": "Amazon even has a recent patent for this kind of application, that you can read more over at the USPTO and researchers at the University of Nevada Robotics Lab proposed an algorithm for drones to coordinate search and rescue operations." }, { "code": null, "e": 1144, "s": 1033, "text": "Without further ado, let us build our very own RGG. We start by randomly placing 100 nodes in the unit square:" }, { "code": null, "e": 1317, "s": 1144, "text": "The next step is to connect all the nodes that are within a certain distance, d. For this we compute the distance matrix containing the distance between all pairs of nodes." }, { "code": null, "e": 1624, "s": 1317, "text": "Computing the full distance matrix is a bit wasteful as it requires O(N2) work. A more sophisticated approach would use KDTrees to achieve linear performance, but that’s beyond the scope of this post as we’re just trying to get familiar with these concepts instead of developing a practical implementation." }, { "code": null, "e": 1780, "s": 1624, "text": "Using this matrix we can easily compute the distribution of distances, P(d) and the cumulative distribution of distances, C(d), between each pair of nodes." }, { "code": null, "e": 2038, "s": 1780, "text": "The distribution follows a quasi-bell shaped curve (the real distribution is a bit more interesting). From the cumulative distribution, it becomes clear that depending on what the threshold d we choose to use for our RGG then we will get more or less edges." }, { "code": null, "e": 2186, "s": 2038, "text": "In the GitHub repository, you can play around with an interactive tool to see how the distance matrix and Graph change as you change the threshold:" }, { "code": null, "e": 2553, "s": 2186, "text": "If you’re more mathematically inclined, you can think of this thresholded distance matrix as a weighted adjacency matrix for the graph. We will have a lot more to say about Adjacency Matrices in future posts but for now all you need to know is that an adjacency matrix is just a matrix where each non-zero element corresponds to an individual edge between two nodes." }, { "code": null, "e": 2995, "s": 2553, "text": "The k-Nearest Neighbors algorithm is a well known family of a Machine Learning algorithms that can be used for classification or regression. The fundamental idea in both cases is fairly straightforward. If you want to know what the label or value of a new data point should be, you can consult its k-nearest neighbors and simply go with the majority. The specific value of k is a hyper parameter that must be defined when training the model." }, { "code": null, "e": 3194, "s": 2995, "text": "The connection with Random Geometric Graphs should now be clear. Instead of just connecting each node with every other node within a certain distance d we simply connect it with its k nearest nodes." }, { "code": null, "e": 3294, "s": 3194, "text": "When we play this game and connect each of our previous nodes to its 5 nearest neighbors we obtain:" }, { "code": null, "e": 3757, "s": 3294, "text": "If you examine this matrix closely you’ll start noticing something... unusual. It is not symmetric! The easiest place to confirm this is along the main diagonal where you will occasionally notice a value on one side than isn’t present on the other. This seems like a pretty strange result. If our distance metric is symmetric, and the euclidean distance certainly is, then how can the network not be symmetric? The reason can be made clear with a simple example." }, { "code": null, "e": 4410, "s": 3757, "text": "Imagine that for some strange twist of fate, you find yourself completely alone and lost in the middle of the Sahara desert. The 5 people that at that precise moment are geographically closest to you might be in whatever the nearest city is, but they will all have many other people closer to them than you! You’re just a weird... outlier. One way to verify this intuition is to check the in-degree distribution of the nodes. You’ll find that unlike the out-degree where each node has exactly k outgoing edges, a node can have either more or fewer incoming edges depending on how close to the periphery of cluster it is and how many outliers there are." }, { "code": null, "e": 4691, "s": 4410, "text": "Here lies the fundamental insight that this graph perspective can give use about k-NN algorithms. Nodes that are more central will be connected through many short-distance links while outliers will be connected to nodes that are far away and have few or not incoming edges at all." }, { "code": null, "e": 5064, "s": 4691, "text": "A visualization can drive this point home. Here we plot the directed graph corresponding to the distance matrix in the previous figure. If you look closely at the isolated nodes close to the center of the figure you’ll notice that while it has 5 long outgoing edges it has only one incoming one due to its peripheral position... lost and alone in the middle of the Sahara." }, { "code": null, "e": 5303, "s": 5064, "text": "Naturally, if we were to measure the distance distribution in this graph it would look very different from the one we saw before as we severely restricting the distances allowed by keeping only the k shortest outgoing edges for each node." }, { "code": null, "e": 5554, "s": 5303, "text": "Density-Based Spatial Clustering of Applications with Noise (DBSCAN) is an unsupervised clustering algorithm that has the explicit goal of identifying clusters of arbitrary shapes in an efficient way. The original KDD paper outlines the algorithm as:" }, { "code": null, "e": 5886, "s": 5554, "text": "To find a cluster, DBSCAN starts with an arbitrary point p and retrieves all points density-reachable from p wrt. Eps and MinPts. If p is a core point, this procedure yields a cluster wrt. Eps and MinPts (see Lemma 2). If p is a border point, no points are density-reachable from p and DBSCAN visits the next point of the database." }, { "code": null, "e": 6520, "s": 5886, "text": "We can put this algorithm into a more intuitive way of by casting it into a network algorithm that explicitly takes advantage of the features of RGG and k-NN algorithms we discussed above. DBSCAN identifies clusters in data sets by connecting (with directed edges) points (nodes) that lie less than a certain distance away (like in RGGs). Peripheral and outlier nodes have fewer than k out-going (like in k-NN). By contrast, any node that has k or more neighbors within the prescribed distance is said to be a “core node”. Finally, clusters in the data can be uniquely identified with the connected components in the resulting graph." }, { "code": null, "e": 6785, "s": 6520, "text": "This approach of explicitly building out neighborhood of each node is computationally intensive and requires O(N2) storage space while more efficient implementations (as the one in the original paper) can reduce memory and computational requirements significantly." }, { "code": null, "e": 7860, "s": 6785, "text": "def net_DBSCAN(X, eps=0.17, min_samples=5): # Building the neighborhood matrix and truncate it # at the maximum distance matrix = distance_matrix(X, X) matrix[matrix >= eps] = 0 # Build the directed graph using the non-zero elements of the matrix G = nx.DiGraph() G.add_edges_from(np.asarray(np.nonzero(matrix)).T) # Create an undirected version of the network for ease of core computation G2 = G.to_undirected() # Find all core nodes results = {} results['core_sample_indices_'] = [node_i for node_i, k in G2.degree() if k >= min_samples-1] # Use the connected components to label each node # as belonging to each cluster labels = [] for label, comp in enumerate(nx.connected_components(G2)): for node in comp: labels.append(label) results['labels_'] = np.asarray(labels) results['G'] = G # Identify the outlier nodes. results['non_core'] = set(np.arange(X.shape[0])) - set(results['core_sample_indices_']) return results" }, { "code": null, "e": 7926, "s": 7860, "text": "When we apply the code above to the two moons dataset, we obtain:" }, { "code": null, "e": 8086, "s": 7926, "text": "Where blue and purple identify the two clusters in the dataset and the green squares are the ‘non-core’ nodes. A perfect match with the sklearn implementation:" }, { "code": null, "e": 8365, "s": 8086, "text": "We hope you enjoyed this way of looking at the venerable k-NN and DBSCAN algorithms and that you gained some new insights about how they work. You can find all the code for the analysis in this post in our companion GitHub Repository https://github.com/DataForScience/Graphs4Sci" } ]
Deficient Number - GeeksforGeeks
25 Jan, 2022 A number n is said to be Deficient Number if sum of all the divisors of the number denoted by divisorsSum(n) is less than twice the value of the number n. And the difference between these two values is called the deficiency.Mathematically, if below condition holds the number is said to be Deficient: divisorsSum(n) < 2 * n deficiency = (2 * n) - divisorsSum(n) The first few Deficient Numbers are:1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 19 .....Given a number n, our task is to find if this number is Deficient number or not. Examples : Input: 21 Output: YES Divisors are 1, 3, 7 and 21. Sum of divisors is 32. This sum is less than 2*21 or 42. Input: 12 Output: NO Input: 17 Output: YES A Simple solution is to iterate all the numbers from 1 to n and check if the number divides n and calculate the sum. Check if this sum is less than 2 * n or not.Time Complexity of this approach: O ( n )Optimized Solution: If we observe carefully, the divisors of the number n are present in pairs. For example if n = 100, then all the pairs of divisors are: (1, 100), (2, 50), (4, 25), (5, 20), (10, 10)Using this fact we can speed up our program. While checking divisors we will have to be careful if there are two equal divisors as in case of (10, 10). In such case we will take only one of them in calculation of sum.Implementation of Optimized approach C++ Java Python3 C# PHP Javascript // C++ program to implement an Optimized Solution// to check Deficient Number#include <bits/stdc++.h>using namespace std; // Function to calculate sum of divisorsint divisorsSum(int n){ int sum = 0; // Initialize sum of prime factors // Note that this loop runs till square root of n for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, take only one // of them if (n / i == i) { sum = sum + i; } else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } return sum;} // Function to check Deficient Numberbool isDeficient(int n){ // Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n));} /* Driver program to test above function */int main(){ isDeficient(12) ? cout << "YES\n" : cout << "NO\n"; isDeficient(15) ? cout << "YES\n" : cout << "NO\n"; return 0;} // Java program to check Deficient Number import java.io.*; class GFG { // Function to calculate sum of divisors static int divisorsSum(int n) { int sum = 0; // Initialize sum of prime factors // Note that this loop runs till square root of n for (int i = 1; i <= (Math.sqrt(n)); i++) { if (n % i == 0) { // If divisors are equal, take only one // of them if (n / i == i) { sum = sum + i; } else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } return sum; } // Function to check Deficient Number static boolean isDeficient(int n) { // Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n)); } /* Driver program to test above function */ public static void main(String args[]) { if (isDeficient(12)) System.out.println("YES"); else System.out.println("NO"); if (isDeficient(15)) System.out.println("YES"); else System.out.println("NO"); }} // This code is contributed by Nikita Tiwari # Python program to implement an Optimized# Solution to check Deficient Numberimport math # Function to calculate sum of divisorsdef divisorsSum(n) : sum = 0 # Initialize sum of prime factors # Note that this loop runs till square # root of n i = 1 while i<= math.sqrt(n) : if (n % i == 0) : # If divisors are equal, take only one # of them if (n // i == i) : sum = sum + i else : # Otherwise take both sum = sum + i; sum = sum + (n // i) i = i + 1 return sum # Function to check Deficient Numberdef isDeficient(n) : # Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n)) # Driver program to test above functionif ( isDeficient(12) ): print ("YES")else : print ("NO")if ( isDeficient(15) ) : print ("YES")else : print ("NO") # This Code is contributed by Nikita Tiwari // C# program to implement an Optimized Solution// to check Deficient Numberusing System; class GFG { // Function to calculate sum of // divisors static int divisorsSum(int n) { // Initialize sum of prime factors int sum = 0; // Note that this loop runs till // square root of n for (int i = 1; i <= (Math.Sqrt(n)); i++) { if (n % i == 0) { // If divisors are equal, // take only one of them if (n / i == i) { sum = sum + i; } else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } return sum; } // Function to check Deficient Number static bool isDeficient(int n) { // Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n)); } /* Driver program to test above function */ public static void Main() { string var = isDeficient(12) ? "YES" : "NO"; Console.WriteLine(var); string var1 = isDeficient(15) ? "YES" : "NO"; Console.WriteLine(var1); }} // This code is contributed by vt_m <?php// PHP program to implement// an Optimized Solution// to check Deficient Number // Function to calculate// sum of divisorsfunction divisorsSum($n){ // Initialize sum of // prime factors $sum = 0; // Note that this loop runs // till square root of n for ($i = 1; $i <= sqrt($n); $i++) { if ($n % $i==0) { // If divisors are equal, // take only one of them if ($n / $i == $i) { $sum = $sum + $i; } // Otherwise take both else { $sum = $sum + $i; $sum = $sum + ($n / $i); } } } return $sum;} // Function to check// Deficient Numberfunction isDeficient($n){ // Check if sum(n) < 2 * n return (divisorsSum($n) < (2 * $n));} // Driver Code$ds = isDeficient(12) ? "YES\n" : "NO\n"; echo($ds);$ds = isDeficient(15) ? "YES\n" : "NO\n"; echo($ds); // This code is contributed by ajit;.?> <script> // Javascript program to check Deficient Number // Function to calculate sum of divisors function divisorsSum(n) { let sum = 0; // Initialize sum of prime factors // Note that this loop runs till square root of n for (let i = 1; i <= (Math.sqrt(n)); i++) { if (n % i == 0) { // If divisors are equal, take only one // of them if (n / i == i) { sum = sum + i; } else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } return sum; } // Function to check Deficient Number function isDeficient(n) { // Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n)); } // Driver code to test above methods if (isDeficient(12)) document.write("YES" + "<br/>"); else document.write("NO" + "<br/>"); if (isDeficient(15)) document.write("YES" + "<br/>"); else document.write("NO" + "<br/>"); // This code is contributed by avijitmondal1998.</script> Output : NO YES Time Complexity : O( sqrt( n )) Auxiliary Space : O( 1 )References : https://en.wikipedia.org/wiki/Deficient_numberThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Akanksha_Rai avijitmondal1998 amartyaghoshgfg prime-factor series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1 Euclidean algorithms (Basic and Extended) Find minimum number of coins that make a given value Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 25072, "s": 25044, "text": "\n25 Jan, 2022" }, { "code": null, "e": 25375, "s": 25072, "text": "A number n is said to be Deficient Number if sum of all the divisors of the number denoted by divisorsSum(n) is less than twice the value of the number n. And the difference between these two values is called the deficiency.Mathematically, if below condition holds the number is said to be Deficient: " }, { "code": null, "e": 25436, "s": 25375, "text": "divisorsSum(n) < 2 * n\ndeficiency = (2 * n) - divisorsSum(n)" }, { "code": null, "e": 25626, "s": 25436, "text": "The first few Deficient Numbers are:1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 19 .....Given a number n, our task is to find if this number is Deficient number or not. Examples : " }, { "code": null, "e": 25779, "s": 25626, "text": "Input: 21\nOutput: YES\nDivisors are 1, 3, 7 and 21. Sum of divisors is 32.\nThis sum is less than 2*21 or 42.\n\nInput: 12\nOutput: NO\n\nInput: 17\nOutput: YES" }, { "code": null, "e": 26440, "s": 25781, "text": "A Simple solution is to iterate all the numbers from 1 to n and check if the number divides n and calculate the sum. Check if this sum is less than 2 * n or not.Time Complexity of this approach: O ( n )Optimized Solution: If we observe carefully, the divisors of the number n are present in pairs. For example if n = 100, then all the pairs of divisors are: (1, 100), (2, 50), (4, 25), (5, 20), (10, 10)Using this fact we can speed up our program. While checking divisors we will have to be careful if there are two equal divisors as in case of (10, 10). In such case we will take only one of them in calculation of sum.Implementation of Optimized approach " }, { "code": null, "e": 26444, "s": 26440, "text": "C++" }, { "code": null, "e": 26449, "s": 26444, "text": "Java" }, { "code": null, "e": 26457, "s": 26449, "text": "Python3" }, { "code": null, "e": 26460, "s": 26457, "text": "C#" }, { "code": null, "e": 26464, "s": 26460, "text": "PHP" }, { "code": null, "e": 26475, "s": 26464, "text": "Javascript" }, { "code": "// C++ program to implement an Optimized Solution// to check Deficient Number#include <bits/stdc++.h>using namespace std; // Function to calculate sum of divisorsint divisorsSum(int n){ int sum = 0; // Initialize sum of prime factors // Note that this loop runs till square root of n for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, take only one // of them if (n / i == i) { sum = sum + i; } else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } return sum;} // Function to check Deficient Numberbool isDeficient(int n){ // Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n));} /* Driver program to test above function */int main(){ isDeficient(12) ? cout << \"YES\\n\" : cout << \"NO\\n\"; isDeficient(15) ? cout << \"YES\\n\" : cout << \"NO\\n\"; return 0;}", "e": 27447, "s": 26475, "text": null }, { "code": "// Java program to check Deficient Number import java.io.*; class GFG { // Function to calculate sum of divisors static int divisorsSum(int n) { int sum = 0; // Initialize sum of prime factors // Note that this loop runs till square root of n for (int i = 1; i <= (Math.sqrt(n)); i++) { if (n % i == 0) { // If divisors are equal, take only one // of them if (n / i == i) { sum = sum + i; } else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } return sum; } // Function to check Deficient Number static boolean isDeficient(int n) { // Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n)); } /* Driver program to test above function */ public static void main(String args[]) { if (isDeficient(12)) System.out.println(\"YES\"); else System.out.println(\"NO\"); if (isDeficient(15)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }} // This code is contributed by Nikita Tiwari", "e": 28699, "s": 27447, "text": null }, { "code": "# Python program to implement an Optimized# Solution to check Deficient Numberimport math # Function to calculate sum of divisorsdef divisorsSum(n) : sum = 0 # Initialize sum of prime factors # Note that this loop runs till square # root of n i = 1 while i<= math.sqrt(n) : if (n % i == 0) : # If divisors are equal, take only one # of them if (n // i == i) : sum = sum + i else : # Otherwise take both sum = sum + i; sum = sum + (n // i) i = i + 1 return sum # Function to check Deficient Numberdef isDeficient(n) : # Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n)) # Driver program to test above functionif ( isDeficient(12) ): print (\"YES\")else : print (\"NO\")if ( isDeficient(15) ) : print (\"YES\")else : print (\"NO\") # This Code is contributed by Nikita Tiwari", "e": 29620, "s": 28699, "text": null }, { "code": "// C# program to implement an Optimized Solution// to check Deficient Numberusing System; class GFG { // Function to calculate sum of // divisors static int divisorsSum(int n) { // Initialize sum of prime factors int sum = 0; // Note that this loop runs till // square root of n for (int i = 1; i <= (Math.Sqrt(n)); i++) { if (n % i == 0) { // If divisors are equal, // take only one of them if (n / i == i) { sum = sum + i; } else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } return sum; } // Function to check Deficient Number static bool isDeficient(int n) { // Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n)); } /* Driver program to test above function */ public static void Main() { string var = isDeficient(12) ? \"YES\" : \"NO\"; Console.WriteLine(var); string var1 = isDeficient(15) ? \"YES\" : \"NO\"; Console.WriteLine(var1); }} // This code is contributed by vt_m", "e": 30841, "s": 29620, "text": null }, { "code": "<?php// PHP program to implement// an Optimized Solution// to check Deficient Number // Function to calculate// sum of divisorsfunction divisorsSum($n){ // Initialize sum of // prime factors $sum = 0; // Note that this loop runs // till square root of n for ($i = 1; $i <= sqrt($n); $i++) { if ($n % $i==0) { // If divisors are equal, // take only one of them if ($n / $i == $i) { $sum = $sum + $i; } // Otherwise take both else { $sum = $sum + $i; $sum = $sum + ($n / $i); } } } return $sum;} // Function to check// Deficient Numberfunction isDeficient($n){ // Check if sum(n) < 2 * n return (divisorsSum($n) < (2 * $n));} // Driver Code$ds = isDeficient(12) ? \"YES\\n\" : \"NO\\n\"; echo($ds);$ds = isDeficient(15) ? \"YES\\n\" : \"NO\\n\"; echo($ds); // This code is contributed by ajit;.?>", "e": 31885, "s": 30841, "text": null }, { "code": "<script> // Javascript program to check Deficient Number // Function to calculate sum of divisors function divisorsSum(n) { let sum = 0; // Initialize sum of prime factors // Note that this loop runs till square root of n for (let i = 1; i <= (Math.sqrt(n)); i++) { if (n % i == 0) { // If divisors are equal, take only one // of them if (n / i == i) { sum = sum + i; } else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } return sum; } // Function to check Deficient Number function isDeficient(n) { // Check if sum(n) < 2 * n return (divisorsSum(n) < (2 * n)); } // Driver code to test above methods if (isDeficient(12)) document.write(\"YES\" + \"<br/>\"); else document.write(\"NO\" + \"<br/>\"); if (isDeficient(15)) document.write(\"YES\" + \"<br/>\"); else document.write(\"NO\" + \"<br/>\"); // This code is contributed by avijitmondal1998.</script>", "e": 33126, "s": 31885, "text": null }, { "code": null, "e": 33137, "s": 33126, "text": "Output : " }, { "code": null, "e": 33144, "s": 33137, "text": "NO\nYES" }, { "code": null, "e": 33681, "s": 33144, "text": "Time Complexity : O( sqrt( n )) Auxiliary Space : O( 1 )References : https://en.wikipedia.org/wiki/Deficient_numberThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33687, "s": 33681, "text": "jit_t" }, { "code": null, "e": 33700, "s": 33687, "text": "Akanksha_Rai" }, { "code": null, "e": 33717, "s": 33700, "text": "avijitmondal1998" }, { "code": null, "e": 33733, "s": 33717, "text": "amartyaghoshgfg" }, { "code": null, "e": 33746, "s": 33733, "text": "prime-factor" }, { "code": null, "e": 33753, "s": 33746, "text": "series" }, { "code": null, "e": 33766, "s": 33753, "text": "Mathematical" }, { "code": null, "e": 33779, "s": 33766, "text": "Mathematical" }, { "code": null, "e": 33786, "s": 33779, "text": "series" }, { "code": null, "e": 33884, "s": 33786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33908, "s": 33884, "text": "Merge two sorted arrays" }, { "code": null, "e": 33951, "s": 33908, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33965, "s": 33951, "text": "Prime Numbers" }, { "code": null, "e": 34014, "s": 33965, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 34048, "s": 34014, "text": "Program for factorial of a number" }, { "code": null, "e": 34069, "s": 34048, "text": "Operators in C / C++" }, { "code": null, "e": 34112, "s": 34069, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 34154, "s": 34112, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 34207, "s": 34154, "text": "Find minimum number of coins that make a given value" } ]
Macro & Preprocessor in C - GeeksQuiz
05 Nov, 2020 C What is the output of the above program? 3 5 3 or 5 depending on value of X Compile time error In the first look, the output seems to be compile-time error because macro X has not been defined. In C, if a macro is not defined, the pre-processor assigns 0 to it by default. Hence, the control goes to the conditional else part and 5 is printed. See the next question for better understanding. printf("Quiz"); int main() { return 0; } #include #define X 3 int main() { #if !X printf("Geeks"); #else printf("Quiz"); #endif return 0; } #define square(x) ((x)*(x)) int main() { int var12 = 100; printf("%d", var12); return 0; } Which file is generated after pre-processing of a C program? .p .i .o .m After the pre-processing of a C program, a .i file is generated which is passed to the compiler for compilation. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Must Do Coding Questions for Product Based Companies Microsoft Interview Experience for Internship (Via Engage) Difference between var, let and const keywords in JavaScript Find number of rectangles that can be formed from a given set of coordinates Array of Objects in C++ with Examples How to Replace Values in Column Based on Condition in Pandas? C Program to read contents of Whole File How to Replace Values in a List in Python? How to Read Text Files with Pandas? Infosys DSE Interview Experience | On-Campus 2021
[ { "code": null, "e": 27219, "s": 27191, "text": "\n05 Nov, 2020" }, { "code": null, "e": 27221, "s": 27219, "text": "C" }, { "code": null, "e": 27263, "s": 27221, "text": "What is the output of the above program? " }, { "code": null, "e": 27266, "s": 27263, "text": "3 " }, { "code": null, "e": 27269, "s": 27266, "text": "5 " }, { "code": null, "e": 27301, "s": 27269, "text": "3 or 5 depending on value of X " }, { "code": null, "e": 27321, "s": 27301, "text": "Compile time error " }, { "code": null, "e": 27619, "s": 27321, "text": "In the first look, the output seems to be compile-time error because macro X has not been defined. In C, if a macro is not defined, the pre-processor assigns 0 to it by default. Hence, the control goes to the conditional else part and 5 is printed. See the next question for better understanding. " }, { "code": null, "e": 27669, "s": 27619, "text": "printf(\"Quiz\");\nint main()\n{\n return 0;\n}\n" }, { "code": null, "e": 27784, "s": 27669, "text": "#include \n#define X 3\n\nint main()\n{\n#if !X\n printf(\"Geeks\");\n#else\n printf(\"Quiz\");\n\n#endif\n return 0;\n}\n" }, { "code": null, "e": 27815, "s": 27784, "text": "#define square(x) ((x)*(x)) \n" }, { "code": null, "e": 27892, "s": 27815, "text": "int main() \n{ \n int var12 = 100; \n printf(\"%d\", var12); \n return 0; \n}" }, { "code": null, "e": 27954, "s": 27892, "text": "Which file is generated after pre-processing of a C program? " }, { "code": null, "e": 27958, "s": 27954, "text": ".p " }, { "code": null, "e": 27962, "s": 27958, "text": ".i " }, { "code": null, "e": 27966, "s": 27962, "text": ".o " }, { "code": null, "e": 27970, "s": 27966, "text": ".m " }, { "code": null, "e": 28085, "s": 27970, "text": "After the pre-processing of a C program, a .i file is generated which is passed to the compiler for compilation. " }, { "code": null, "e": 28183, "s": 28085, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 28192, "s": 28183, "text": "Comments" }, { "code": null, "e": 28205, "s": 28192, "text": "Old Comments" }, { "code": null, "e": 28258, "s": 28205, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 28317, "s": 28258, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 28378, "s": 28317, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28455, "s": 28378, "text": "Find number of rectangles that can be formed from a given set of coordinates" }, { "code": null, "e": 28493, "s": 28455, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 28555, "s": 28493, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 28596, "s": 28555, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28639, "s": 28596, "text": "How to Replace Values in a List in Python?" }, { "code": null, "e": 28675, "s": 28639, "text": "How to Read Text Files with Pandas?" } ]
Display a blue shadow on image hover with CSS
To display a shadow on image hover, use the CSS box-shadow property Live Demo <!DOCTYPE html> <html> <head> <style> img { border: 2px solid orange; border-radius: 3px; padding: 7px; } img:hover { box-shadow: 0 0 2px 2px blue; } </style> </head> <body> <img src = "https://www.tutorialspoint.com/videotutorials/images/coding_ground_home.jpg" alt="Online Compiler" width="300" height="300"> </body> </html>
[ { "code": null, "e": 1130, "s": 1062, "text": "To display a shadow on image hover, use the CSS box-shadow property" }, { "code": null, "e": 1140, "s": 1130, "text": "Live Demo" }, { "code": null, "e": 1581, "s": 1140, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n img {\n border: 2px solid orange;\n border-radius: 3px;\n padding: 7px;\n }\n img:hover {\n box-shadow: 0 0 2px 2px blue;\n }\n </style>\n </head>\n <body>\n <img src = \"https://www.tutorialspoint.com/videotutorials/images/coding_ground_home.jpg\" alt=\"Online Compiler\" width=\"300\" height=\"300\">\n </body>\n</html>" } ]
How to make a resizable element in React JS
In this article, we will see how to make a resizable element in React JS. We always create resizable textarea in HTML, but when it comes to creating other elements resizable, it seems impossible. In React, we can create resizable elements easily using a simple library. First install the following package − npm install --save re-resizable re-resizable is used to import a resizable container which will be used to add Resizable functionality to any DOM element. Add the following lines of code in App.js − import React, { useState } from "react"; import { Resizable } from "re-resizable"; export default function App() { const [state, setState] = useState({ width: 320, height: 200 }); return ( <Resizable style={{ marginLeft: 500, marginTop: 200, border: "1px solid black" }} size={{ width: state.width, height: state.height }} onResizeStop={(e, direction, ref, d) => { setState({ width: state.width + d.width, height: state.height + d.height,}); }}> Sample with size </Resizable> ); } Adding any element inside <Resizable> makes it resizable. Adding any element inside <Resizable> makes it resizable. The size attribute defines the size of the resizable component. The size attribute defines the size of the resizable component. onResizeStop defines what to do when the user tries to resize the element. Here we change width and height of the element in State which makes the required changes in the size attribute. onResizeStop defines what to do when the user tries to resize the element. Here we change width and height of the element in State which makes the required changes in the size attribute. Arguments like d.width and d.height define how much the width or height should increase or decrease. Arguments like d.width and d.height define how much the width or height should increase or decrease. On execution, it will produce the following output − Your browser does not support HTML5 video.
[ { "code": null, "e": 1332, "s": 1062, "text": "In this article, we will see how to make a resizable element in\nReact JS. We always create resizable textarea in HTML, but when it\ncomes to creating other elements resizable, it seems impossible. In\nReact, we can create resizable elements easily using a simple library." }, { "code": null, "e": 1370, "s": 1332, "text": "First install the following package −" }, { "code": null, "e": 1402, "s": 1370, "text": "npm install --save re-resizable" }, { "code": null, "e": 1525, "s": 1402, "text": "re-resizable is used to import a resizable container which will be used to add Resizable functionality to any DOM element." }, { "code": null, "e": 1569, "s": 1525, "text": "Add the following lines of code in App.js −" }, { "code": null, "e": 2146, "s": 1569, "text": "import React, { useState } from \"react\";\nimport { Resizable } from \"re-resizable\";\nexport default function App() {\n const [state, setState] = useState({ width: 320, height: 200 });\n return (\n <Resizable\n style={{ marginLeft: 500, marginTop: 200, border: \"1px solid black\" }}\n size={{ width: state.width, height: state.height }}\n onResizeStop={(e, direction, ref, d) => {\n setState({\n width: state.width + d.width, height: state.height + d.height,});\n }}>\n Sample with size\n </Resizable>\n );\n}" }, { "code": null, "e": 2204, "s": 2146, "text": "Adding any element inside <Resizable> makes it resizable." }, { "code": null, "e": 2262, "s": 2204, "text": "Adding any element inside <Resizable> makes it resizable." }, { "code": null, "e": 2326, "s": 2262, "text": "The size attribute defines the size of the resizable component." }, { "code": null, "e": 2390, "s": 2326, "text": "The size attribute defines the size of the resizable component." }, { "code": null, "e": 2577, "s": 2390, "text": "onResizeStop defines what to do when the user tries to resize the element. Here we change width and height of the element in State which makes the required changes in the size attribute." }, { "code": null, "e": 2764, "s": 2577, "text": "onResizeStop defines what to do when the user tries to resize the element. Here we change width and height of the element in State which makes the required changes in the size attribute." }, { "code": null, "e": 2865, "s": 2764, "text": "Arguments like d.width and d.height define how much the width or height should increase or decrease." }, { "code": null, "e": 2966, "s": 2865, "text": "Arguments like d.width and d.height define how much the width or height should increase or decrease." }, { "code": null, "e": 3019, "s": 2966, "text": "On execution, it will produce the following output −" }, { "code": null, "e": 3062, "s": 3019, "text": "Your browser does not support HTML5 video." } ]
How to find the size of a list in C#?
Declare and initialize a list. var products = new List <string>(); products.Add("Accessories"); products.Add("Clothing"); products.Add("Footwear"); To get the size, use the Capacity property. products.Capacity Now let us see the complete code to find the size of a list. Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main(string[] args) { var products = new List <string>(); products.Add("Accessories"); products.Add("Clothing"); products.Add("Footwear"); Console.WriteLine("Our list...."); foreach(var p in products) { Console.WriteLine(p); } Console.WriteLine("Size of list = " + products.Capacity); } } Our list.... Accessories Clothing Footwear Size of list = 4
[ { "code": null, "e": 1093, "s": 1062, "text": "Declare and initialize a list." }, { "code": null, "e": 1210, "s": 1093, "text": "var products = new List <string>();\nproducts.Add(\"Accessories\");\nproducts.Add(\"Clothing\");\nproducts.Add(\"Footwear\");" }, { "code": null, "e": 1254, "s": 1210, "text": "To get the size, use the Capacity property." }, { "code": null, "e": 1272, "s": 1254, "text": "products.Capacity" }, { "code": null, "e": 1333, "s": 1272, "text": "Now let us see the complete code to find the size of a list." }, { "code": null, "e": 1344, "s": 1333, "text": " Live Demo" }, { "code": null, "e": 1783, "s": 1344, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(string[] args) {\n var products = new List <string>();\n products.Add(\"Accessories\");\n products.Add(\"Clothing\");\n products.Add(\"Footwear\");\n Console.WriteLine(\"Our list....\");\n foreach(var p in products) {\n Console.WriteLine(p);\n }\n Console.WriteLine(\"Size of list = \" + products.Capacity);\n }\n}" }, { "code": null, "e": 1843, "s": 1783, "text": "Our list....\nAccessories\nClothing\nFootwear\nSize of list = 4" } ]
WAScan - web application security scanner in Kali Linux - GeeksforGeeks
23 Aug, 2021 WAScan stands for Web Application Scanner. It is an open-source web application vulnerability scanner. The tool uses the technique of black-box to find various vulnerabilities. This technique will not scan the whole source code of a web application but work like a fuzzer Which means it scans the pages of the whole website or web application. This tool extracts links and forms of the web application and scans one by one to find vulnerabilities. Wascan provides a powerful environment in which open source web-based reconnaissance can be conducted and you can gather all information about the target. This tool is written in python language you must have python language installed in your kali Linux operating system. Step 1: Use the following command to install the tool in your kali Linux operating system. git clone https://github.com/m4ll0k/WAScan.git wascan Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool. cd WAScan Step 3: You are in the directory of the WAScan. Now you have to install a dependency of the WAScan using the following command. pip install BeautifulSoup Step 4: All the dependencies have been installed in your kali Linux operating system. Now use the following command to run the tool. python wascan.py The wascan tool has been downloaded and installed successfully. Now we will see examples to use the tool. Example 1: Use the wascan to scan a domain for fingerprints/footprints. python wascan.py --url <domain> --scan 0 Example 2: Use the wascan to scan a domain for attacks. python wascan.py --url <domain> --scan 1 Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples SORT command in Linux/Unix with examples curl command in Linux with Examples 'crontab' in Linux with Examples UDP Server-Client implementation in C diff command in Linux with examples Conditional Statements | Shell Script Cat command in Linux with examples
[ { "code": null, "e": 24520, "s": 24492, "text": "\n23 Aug, 2021" }, { "code": null, "e": 24969, "s": 24520, "text": "WAScan stands for Web Application Scanner. It is an open-source web application vulnerability scanner. The tool uses the technique of black-box to find various vulnerabilities. This technique will not scan the whole source code of a web application but work like a fuzzer Which means it scans the pages of the whole website or web application. This tool extracts links and forms of the web application and scans one by one to find vulnerabilities. " }, { "code": null, "e": 25241, "s": 24969, "text": "Wascan provides a powerful environment in which open source web-based reconnaissance can be conducted and you can gather all information about the target. This tool is written in python language you must have python language installed in your kali Linux operating system." }, { "code": null, "e": 25332, "s": 25241, "text": "Step 1: Use the following command to install the tool in your kali Linux operating system." }, { "code": null, "e": 25386, "s": 25332, "text": "git clone https://github.com/m4ll0k/WAScan.git wascan" }, { "code": null, "e": 25524, "s": 25386, "text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool." }, { "code": null, "e": 25534, "s": 25524, "text": "cd WAScan" }, { "code": null, "e": 25662, "s": 25534, "text": "Step 3: You are in the directory of the WAScan. Now you have to install a dependency of the WAScan using the following command." }, { "code": null, "e": 25688, "s": 25662, "text": "pip install BeautifulSoup" }, { "code": null, "e": 25821, "s": 25688, "text": "Step 4: All the dependencies have been installed in your kali Linux operating system. Now use the following command to run the tool." }, { "code": null, "e": 25838, "s": 25821, "text": "python wascan.py" }, { "code": null, "e": 25944, "s": 25838, "text": "The wascan tool has been downloaded and installed successfully. Now we will see examples to use the tool." }, { "code": null, "e": 26016, "s": 25944, "text": "Example 1: Use the wascan to scan a domain for fingerprints/footprints." }, { "code": null, "e": 26057, "s": 26016, "text": "python wascan.py --url <domain> --scan 0" }, { "code": null, "e": 26113, "s": 26057, "text": "Example 2: Use the wascan to scan a domain for attacks." }, { "code": null, "e": 26154, "s": 26113, "text": "python wascan.py --url <domain> --scan 1" }, { "code": null, "e": 26165, "s": 26154, "text": "Kali-Linux" }, { "code": null, "e": 26177, "s": 26165, "text": "Linux-Tools" }, { "code": null, "e": 26188, "s": 26177, "text": "Linux-Unix" }, { "code": null, "e": 26286, "s": 26188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26324, "s": 26286, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26359, "s": 26324, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 26394, "s": 26359, "text": "tar command in Linux with examples" }, { "code": null, "e": 26435, "s": 26394, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 26471, "s": 26435, "text": "curl command in Linux with Examples" }, { "code": null, "e": 26504, "s": 26471, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 26542, "s": 26504, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26578, "s": 26542, "text": "diff command in Linux with examples" }, { "code": null, "e": 26616, "s": 26578, "text": "Conditional Statements | Shell Script" } ]
Python - Basics of Pandas using Iris Dataset - GeeksforGeeks
27 Aug, 2021 Python language is one of the most trending programming languages as it is dynamic than others. Python is a simple high-level and an open-source language used for general-purpose programming. It has many open-source libraries and Pandas is one of them. Pandas is a powerful, fast, flexible open-source library used for data analysis and manipulations of data frames/datasets. Pandas can be used to read and write data in a dataset of different formats like CSV(comma separated values), txt, xls(Microsoft Excel) etc. In this post, you will learn about various features of Pandas in Python and how to use it to practice.Prerequisites: Basic knowledge about coding in Python.Installation:So if you are new to practice Pandas, then firstly you should install Pandas on your system. Go to Command Prompt and run it as administrator. Make sure you are connected with an internet connection to download and install it on your system.Then type “pip install pandas“, then press Enter key. Download the Dataset “Iris.csv” from hereIris dataset is the Hello World for the Data Science, so if you have started your career in Data Science and Machine Learning you will be practicing basic ML algorithms on this famous dataset. Iris dataset contains five columns such as Petal Length, Petal Width, Sepal Length, Sepal Width and Species Type. Iris is a flowering plant, the researchers have measured various features of the different iris flowers and recorded digitally. Getting Started with Pandas:Code: Importing pandas to use in our code as pd. Python3 import pandas as pd Code: Reading the dataset “Iris.csv”. Python3 data = pd.read_csv("your downloaded dataset location ") Code: Displaying up the top rows of the dataset with their columns The function head() will display the top rows of the dataset, the default value of this function is 5, that is it will show top 5 rows when no argument is given to it. Python3 data.head() Output: Displaying the number of rows randomly. In sample() function, it will also display the rows according to arguments given, but it will display the rows randomly. Python3 data.sample(10) Output: Code: Displaying the number of columns and names of the columns. The column() function prints all the columns of the dataset in a list form. Python3 data.columns Output: Code: Displaying the shape of the dataset. The shape of the dataset means to print the total number of rows or entries and the total number of columns or features of that particular dataset. Python3 #The first one is the number of rows and# the other one is the number of columns.data.shape Output: Code: Display the whole dataset Python3 print(data) Output: Code: Slicing the rows. Slicing means if you want to print or work upon a particular group of lines that is from 10th row to 20th row. Python3 #data[start:end]#start is inclusive whereas end is exclusiveprint(data[10:21])# it will print the rows from 10 to 20. # you can also save it in a variable for further use in analysissliced_data=data[10:21]print(sliced_data) Output: Code: Displaying only specific columns. In any dataset, it is sometimes needed to work upon only specific features or columns, so we can do this by the following code. Python3 #here in the case of Iris dataset#we will save it in a another variable named "specific_data" specific_data=data[["Id","Species"]]#data[["column_name1","column_name2","column_name3"]] #now we will print the first 10 columns of the specific_data dataframe.print(specific_data.head(10)) Output: Filtering:Displaying the specific rows using “iloc” and “loc” functions. The “loc” functions use the index name of the row to display the particular row of the dataset. The “iloc” functions use the index integer of the row, which gives complete information about the row. Code: Python3 #here we will use iloc data.iloc[5]#it will display records only with species "Iris-setosa".data.loc[data["Species"] == "Iris-setosa"] Output: iloc()[/caption] loc() Code: Counting the number of counts of unique values using “value_counts()”. The value_counts() function, counts the number of times a particular instance or data has occurred. Python3 #In this dataset we will work on the Species column, it will count number of times a particular species has occurred.data["Species"].value_counts()#it will display in descending order. Output: Calculating sum, mean and mode of a particular column. We can also calculate the sum, mean and mode of any integer columns as I have done in the following code. Python3 # data["column_name"].sum() sum_data = data["SepalLengthCm"].sum()mean_data = data["SepalLengthCm"].mean()median_data = data["SepalLengthCm"].median() print("Sum:",sum_data, "\nMean:", mean_data, "\nMedian:",median_data) Output: Code: Extracting minimum and maximum from a column. Identifying minimum and maximum integer, from a particular column or row can also be done in a dataset. Python3 min_data=data["SepalLengthCm"].min()max_data=data["SepalLengthCm"].max() print("Minimum:",min_data, "\nMaximum:", max_data) Output: Code: Adding a column to the dataset. If want to add a new column in our dataset, as we are doing any calculations or extracting some information from the dataset, and if you want to save it a new column. This can be done by the following code by taking a case where we have added all integer values of all columns. Python3 # For example, if we want to add a column let say "total_values",# that means if you want to add all the integer value of that particular# row and get total answer in the new column "total_values".# first we will extract the columns which have integer values.cols = data.columns # it will print the list of column names.print(cols) # we will take that columns which have integer values.cols = cols[1:5] # we will save it in the new dataframe variabledata1 = data[cols] # now adding new column "total_values" to dataframe data.data["total_values"]=data1[cols].sum(axis=1) # here axis=1 means you are working in rows,# whereas axis=0 means you are working in columns. Output: Code: Renaming the columns. Renaming our column names can also be possible in python pandas libraries. We have used the rename() function, where we have created a dictionary “newcols” to update our new column names. The following code illustrates that. Python3 newcols={"Id":"id","SepalLengthCm":"sepallength""SepalWidthCm":"sepalwidth"} data.rename(columns=newcols,inplace=True) print(data.head()) Output: Formatting and Styling: Conditional formatting can be applied to your dataframe by using Dataframe.style function. Styling is used to visualize your data, and most convenient way of visualizing your dataset is in tabular form. Here we will highlight the minimum and maximum from each row and columns. Python3 #this is an example of rendering a datagram,which is not visualised by any styles.data.style Output: Now we will highlight the maximum and minimum column-wise, row-wise, and the whole dataframe wise using Styler.apply function. The Styler.apply function passes each column or row of the dataframe depending upon the keyword argument axis. For column-wise use axis=0, row-wise use axis=1, and for the entire table at once use axis=None. Python3 # we will here print only the top 10 rows of the dataset,# if you want to see the result of the whole dataset remove#.head(10) from the below code data.head(10).style.highlight_max(color='lightgreen', axis=0) data.head(10).style.highlight_max(color='lightgreen', axis=1) data.head(10).style.highlight_max(color='lightgreen', axis=None) Output: for axis=0 for axis=1 for axis=None Code: Cleaning and detecting missing values In this dataset, we will now try to find the missing values i.e NaN, which can occur due to several reasons. Python3 data.isnull()#if there is data is missing, it will display True else False. Output: isnull() Code: Summarizing the missing values. We will display how many missing values are present in each column. Python3 data.isnull.sum() Output: Heatmap: Importing seaborn The heatmap is a data visualisation technique which is used to analyse the dataset as colors in two dimensions. Basically it shows correlation between all numerical variables in the dataset. Heatmap is an attribute of the Seaborn library. Code: Python3 import seaborn as sns iris = sns.load_dataset("iris")sns.heatmap(iris.corr(),camp = "YlGnBu", linecolor = 'white', linewidths = 1) Output: Code: Annotate each cell with the numeric value using integer formatting Python3 sns.heatmap(iris.corr(),camp = "YlGnBu", linecolor = 'white', linewidths = 1, annot = True ) Output: heatmap with annot=True Pandas Dataframe Correlation: Pandas correlation is used to determine pairwise correlation of all the columns of the dataset. In dataframe.corr(), the missing values are excluded and non-numeric columns are also ignored. Code: Python3 data.corr(method='pearson') Output: data.corr() The output dataframe can be seen as for any cell, row variable correlation with the column variable is the value of the cell. The correlation of a variable with itself is 1. For that reason, all the diagonal values are 1.00.Multivariate Analysis: Pair plot is used to visualize the relationship between each type of column variable. It is implemented only by one line code, which is as follows : Code: Python3 g = sns.pairplot(data,hue="Species") Output: Pairplot of variable “Species”, to make it more understandable. anikakapoor Python-pandas Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Linear Regression Decision Tree Search Algorithms in AI Python | Decision tree implementation Reinforcement learning Read JSON file using Python Python map() function Python Dictionary Taking input in Python Read a file line by line in Python
[ { "code": null, "e": 25270, "s": 25242, "text": "\n27 Aug, 2021" }, { "code": null, "e": 26252, "s": 25270, "text": "Python language is one of the most trending programming languages as it is dynamic than others. Python is a simple high-level and an open-source language used for general-purpose programming. It has many open-source libraries and Pandas is one of them. Pandas is a powerful, fast, flexible open-source library used for data analysis and manipulations of data frames/datasets. Pandas can be used to read and write data in a dataset of different formats like CSV(comma separated values), txt, xls(Microsoft Excel) etc. In this post, you will learn about various features of Pandas in Python and how to use it to practice.Prerequisites: Basic knowledge about coding in Python.Installation:So if you are new to practice Pandas, then firstly you should install Pandas on your system. Go to Command Prompt and run it as administrator. Make sure you are connected with an internet connection to download and install it on your system.Then type “pip install pandas“, then press Enter key. " }, { "code": null, "e": 26730, "s": 26252, "text": "Download the Dataset “Iris.csv” from hereIris dataset is the Hello World for the Data Science, so if you have started your career in Data Science and Machine Learning you will be practicing basic ML algorithms on this famous dataset. Iris dataset contains five columns such as Petal Length, Petal Width, Sepal Length, Sepal Width and Species Type. Iris is a flowering plant, the researchers have measured various features of the different iris flowers and recorded digitally. " }, { "code": null, "e": 26808, "s": 26730, "text": "Getting Started with Pandas:Code: Importing pandas to use in our code as pd. " }, { "code": null, "e": 26816, "s": 26808, "text": "Python3" }, { "code": "import pandas as pd", "e": 26836, "s": 26816, "text": null }, { "code": null, "e": 26875, "s": 26836, "text": "Code: Reading the dataset “Iris.csv”. " }, { "code": null, "e": 26883, "s": 26875, "text": "Python3" }, { "code": "data = pd.read_csv(\"your downloaded dataset location \")", "e": 26939, "s": 26883, "text": null }, { "code": null, "e": 27175, "s": 26939, "text": "Code: Displaying up the top rows of the dataset with their columns The function head() will display the top rows of the dataset, the default value of this function is 5, that is it will show top 5 rows when no argument is given to it. " }, { "code": null, "e": 27183, "s": 27175, "text": "Python3" }, { "code": "data.head()", "e": 27195, "s": 27183, "text": null }, { "code": null, "e": 27205, "s": 27195, "text": "Output: " }, { "code": null, "e": 27367, "s": 27205, "text": "Displaying the number of rows randomly. In sample() function, it will also display the rows according to arguments given, but it will display the rows randomly. " }, { "code": null, "e": 27375, "s": 27367, "text": "Python3" }, { "code": "data.sample(10)", "e": 27391, "s": 27375, "text": null }, { "code": null, "e": 27401, "s": 27391, "text": "Output: " }, { "code": null, "e": 27543, "s": 27401, "text": "Code: Displaying the number of columns and names of the columns. The column() function prints all the columns of the dataset in a list form. " }, { "code": null, "e": 27551, "s": 27543, "text": "Python3" }, { "code": "data.columns", "e": 27564, "s": 27551, "text": null }, { "code": null, "e": 27574, "s": 27564, "text": "Output: " }, { "code": null, "e": 27766, "s": 27574, "text": "Code: Displaying the shape of the dataset. The shape of the dataset means to print the total number of rows or entries and the total number of columns or features of that particular dataset. " }, { "code": null, "e": 27774, "s": 27766, "text": "Python3" }, { "code": "#The first one is the number of rows and# the other one is the number of columns.data.shape", "e": 27866, "s": 27774, "text": null }, { "code": null, "e": 27876, "s": 27866, "text": "Output: " }, { "code": null, "e": 27909, "s": 27876, "text": "Code: Display the whole dataset " }, { "code": null, "e": 27917, "s": 27909, "text": "Python3" }, { "code": "print(data)", "e": 27929, "s": 27917, "text": null }, { "code": null, "e": 27939, "s": 27929, "text": "Output: " }, { "code": null, "e": 28075, "s": 27939, "text": "Code: Slicing the rows. Slicing means if you want to print or work upon a particular group of lines that is from 10th row to 20th row. " }, { "code": null, "e": 28083, "s": 28075, "text": "Python3" }, { "code": "#data[start:end]#start is inclusive whereas end is exclusiveprint(data[10:21])# it will print the rows from 10 to 20. # you can also save it in a variable for further use in analysissliced_data=data[10:21]print(sliced_data)", "e": 28307, "s": 28083, "text": null }, { "code": null, "e": 28317, "s": 28307, "text": "Output: " }, { "code": null, "e": 28486, "s": 28317, "text": "Code: Displaying only specific columns. In any dataset, it is sometimes needed to work upon only specific features or columns, so we can do this by the following code. " }, { "code": null, "e": 28494, "s": 28486, "text": "Python3" }, { "code": "#here in the case of Iris dataset#we will save it in a another variable named \"specific_data\" specific_data=data[[\"Id\",\"Species\"]]#data[[\"column_name1\",\"column_name2\",\"column_name3\"]] #now we will print the first 10 columns of the specific_data dataframe.print(specific_data.head(10))", "e": 28779, "s": 28494, "text": null }, { "code": null, "e": 28789, "s": 28779, "text": "Output: " }, { "code": null, "e": 28863, "s": 28789, "text": "Filtering:Displaying the specific rows using “iloc” and “loc” functions. " }, { "code": null, "e": 29070, "s": 28863, "text": "The “loc” functions use the index name of the row to display the particular row of the dataset. The “iloc” functions use the index integer of the row, which gives complete information about the row. Code: " }, { "code": null, "e": 29078, "s": 29070, "text": "Python3" }, { "code": "#here we will use iloc data.iloc[5]#it will display records only with species \"Iris-setosa\".data.loc[data[\"Species\"] == \"Iris-setosa\"]", "e": 29213, "s": 29078, "text": null }, { "code": null, "e": 29223, "s": 29213, "text": "Output: " }, { "code": null, "e": 29241, "s": 29223, "text": "iloc()[/caption] " }, { "code": null, "e": 29247, "s": 29241, "text": "loc()" }, { "code": null, "e": 29425, "s": 29247, "text": "Code: Counting the number of counts of unique values using “value_counts()”. The value_counts() function, counts the number of times a particular instance or data has occurred. " }, { "code": null, "e": 29433, "s": 29425, "text": "Python3" }, { "code": "#In this dataset we will work on the Species column, it will count number of times a particular species has occurred.data[\"Species\"].value_counts()#it will display in descending order.", "e": 29618, "s": 29433, "text": null }, { "code": null, "e": 29628, "s": 29618, "text": "Output: " }, { "code": null, "e": 29790, "s": 29628, "text": "Calculating sum, mean and mode of a particular column. We can also calculate the sum, mean and mode of any integer columns as I have done in the following code. " }, { "code": null, "e": 29798, "s": 29790, "text": "Python3" }, { "code": "# data[\"column_name\"].sum() sum_data = data[\"SepalLengthCm\"].sum()mean_data = data[\"SepalLengthCm\"].mean()median_data = data[\"SepalLengthCm\"].median() print(\"Sum:\",sum_data, \"\\nMean:\", mean_data, \"\\nMedian:\",median_data)", "e": 30019, "s": 29798, "text": null }, { "code": null, "e": 30029, "s": 30019, "text": "Output: " }, { "code": null, "e": 30186, "s": 30029, "text": "Code: Extracting minimum and maximum from a column. Identifying minimum and maximum integer, from a particular column or row can also be done in a dataset. " }, { "code": null, "e": 30194, "s": 30186, "text": "Python3" }, { "code": "min_data=data[\"SepalLengthCm\"].min()max_data=data[\"SepalLengthCm\"].max() print(\"Minimum:\",min_data, \"\\nMaximum:\", max_data)", "e": 30318, "s": 30194, "text": null }, { "code": null, "e": 30328, "s": 30318, "text": "Output: " }, { "code": null, "e": 30645, "s": 30328, "text": "Code: Adding a column to the dataset. If want to add a new column in our dataset, as we are doing any calculations or extracting some information from the dataset, and if you want to save it a new column. This can be done by the following code by taking a case where we have added all integer values of all columns. " }, { "code": null, "e": 30653, "s": 30645, "text": "Python3" }, { "code": "# For example, if we want to add a column let say \"total_values\",# that means if you want to add all the integer value of that particular# row and get total answer in the new column \"total_values\".# first we will extract the columns which have integer values.cols = data.columns # it will print the list of column names.print(cols) # we will take that columns which have integer values.cols = cols[1:5] # we will save it in the new dataframe variabledata1 = data[cols] # now adding new column \"total_values\" to dataframe data.data[\"total_values\"]=data1[cols].sum(axis=1) # here axis=1 means you are working in rows,# whereas axis=0 means you are working in columns.", "e": 31319, "s": 30653, "text": null }, { "code": null, "e": 31329, "s": 31319, "text": "Output: " }, { "code": null, "e": 31583, "s": 31329, "text": "Code: Renaming the columns. Renaming our column names can also be possible in python pandas libraries. We have used the rename() function, where we have created a dictionary “newcols” to update our new column names. The following code illustrates that. " }, { "code": null, "e": 31591, "s": 31583, "text": "Python3" }, { "code": "newcols={\"Id\":\"id\",\"SepalLengthCm\":\"sepallength\"\"SepalWidthCm\":\"sepalwidth\"} data.rename(columns=newcols,inplace=True) print(data.head())", "e": 31729, "s": 31591, "text": null }, { "code": null, "e": 31739, "s": 31729, "text": "Output: " }, { "code": null, "e": 32041, "s": 31739, "text": "Formatting and Styling: Conditional formatting can be applied to your dataframe by using Dataframe.style function. Styling is used to visualize your data, and most convenient way of visualizing your dataset is in tabular form. Here we will highlight the minimum and maximum from each row and columns. " }, { "code": null, "e": 32049, "s": 32041, "text": "Python3" }, { "code": "#this is an example of rendering a datagram,which is not visualised by any styles.data.style", "e": 32142, "s": 32049, "text": null }, { "code": null, "e": 32152, "s": 32142, "text": "Output: " }, { "code": null, "e": 32488, "s": 32152, "text": "Now we will highlight the maximum and minimum column-wise, row-wise, and the whole dataframe wise using Styler.apply function. The Styler.apply function passes each column or row of the dataframe depending upon the keyword argument axis. For column-wise use axis=0, row-wise use axis=1, and for the entire table at once use axis=None. " }, { "code": null, "e": 32496, "s": 32488, "text": "Python3" }, { "code": "# we will here print only the top 10 rows of the dataset,# if you want to see the result of the whole dataset remove#.head(10) from the below code data.head(10).style.highlight_max(color='lightgreen', axis=0) data.head(10).style.highlight_max(color='lightgreen', axis=1) data.head(10).style.highlight_max(color='lightgreen', axis=None)", "e": 32832, "s": 32496, "text": null }, { "code": null, "e": 32842, "s": 32832, "text": "Output: " }, { "code": null, "e": 32853, "s": 32842, "text": "for axis=0" }, { "code": null, "e": 32866, "s": 32855, "text": "for axis=1" }, { "code": null, "e": 32882, "s": 32868, "text": "for axis=None" }, { "code": null, "e": 33036, "s": 32882, "text": "Code: Cleaning and detecting missing values In this dataset, we will now try to find the missing values i.e NaN, which can occur due to several reasons. " }, { "code": null, "e": 33044, "s": 33036, "text": "Python3" }, { "code": "data.isnull()#if there is data is missing, it will display True else False.", "e": 33120, "s": 33044, "text": null }, { "code": null, "e": 33130, "s": 33120, "text": "Output: " }, { "code": null, "e": 33139, "s": 33130, "text": "isnull()" }, { "code": null, "e": 33246, "s": 33139, "text": "Code: Summarizing the missing values. We will display how many missing values are present in each column. " }, { "code": null, "e": 33254, "s": 33246, "text": "Python3" }, { "code": "data.isnull.sum()", "e": 33272, "s": 33254, "text": null }, { "code": null, "e": 33282, "s": 33272, "text": "Output: " }, { "code": null, "e": 33556, "s": 33282, "text": "Heatmap: Importing seaborn The heatmap is a data visualisation technique which is used to analyse the dataset as colors in two dimensions. Basically it shows correlation between all numerical variables in the dataset. Heatmap is an attribute of the Seaborn library. Code: " }, { "code": null, "e": 33564, "s": 33556, "text": "Python3" }, { "code": "import seaborn as sns iris = sns.load_dataset(\"iris\")sns.heatmap(iris.corr(),camp = \"YlGnBu\", linecolor = 'white', linewidths = 1)", "e": 33695, "s": 33564, "text": null }, { "code": null, "e": 33705, "s": 33695, "text": "Output: " }, { "code": null, "e": 33779, "s": 33705, "text": "Code: Annotate each cell with the numeric value using integer formatting " }, { "code": null, "e": 33787, "s": 33779, "text": "Python3" }, { "code": "sns.heatmap(iris.corr(),camp = \"YlGnBu\", linecolor = 'white', linewidths = 1, annot = True )", "e": 33880, "s": 33787, "text": null }, { "code": null, "e": 33890, "s": 33880, "text": "Output: " }, { "code": null, "e": 33914, "s": 33890, "text": "heatmap with annot=True" }, { "code": null, "e": 34143, "s": 33914, "text": "Pandas Dataframe Correlation: Pandas correlation is used to determine pairwise correlation of all the columns of the dataset. In dataframe.corr(), the missing values are excluded and non-numeric columns are also ignored. Code: " }, { "code": null, "e": 34151, "s": 34143, "text": "Python3" }, { "code": "data.corr(method='pearson')", "e": 34179, "s": 34151, "text": null }, { "code": null, "e": 34189, "s": 34179, "text": "Output: " }, { "code": null, "e": 34201, "s": 34189, "text": "data.corr()" }, { "code": null, "e": 34605, "s": 34201, "text": "The output dataframe can be seen as for any cell, row variable correlation with the column variable is the value of the cell. The correlation of a variable with itself is 1. For that reason, all the diagonal values are 1.00.Multivariate Analysis: Pair plot is used to visualize the relationship between each type of column variable. It is implemented only by one line code, which is as follows : Code: " }, { "code": null, "e": 34613, "s": 34605, "text": "Python3" }, { "code": "g = sns.pairplot(data,hue=\"Species\")", "e": 34650, "s": 34613, "text": null }, { "code": null, "e": 34660, "s": 34650, "text": "Output: " }, { "code": null, "e": 34724, "s": 34660, "text": "Pairplot of variable “Species”, to make it more understandable." }, { "code": null, "e": 34738, "s": 34726, "text": "anikakapoor" }, { "code": null, "e": 34752, "s": 34738, "text": "Python-pandas" }, { "code": null, "e": 34769, "s": 34752, "text": "Machine Learning" }, { "code": null, "e": 34776, "s": 34769, "text": "Python" }, { "code": null, "e": 34793, "s": 34776, "text": "Machine Learning" }, { "code": null, "e": 34891, "s": 34793, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34900, "s": 34891, "text": "Comments" }, { "code": null, "e": 34913, "s": 34900, "text": "Old Comments" }, { "code": null, "e": 34936, "s": 34913, "text": "ML | Linear Regression" }, { "code": null, "e": 34950, "s": 34936, "text": "Decision Tree" }, { "code": null, "e": 34974, "s": 34950, "text": "Search Algorithms in AI" }, { "code": null, "e": 35012, "s": 34974, "text": "Python | Decision tree implementation" }, { "code": null, "e": 35035, "s": 35012, "text": "Reinforcement learning" }, { "code": null, "e": 35063, "s": 35035, "text": "Read JSON file using Python" }, { "code": null, "e": 35085, "s": 35063, "text": "Python map() function" }, { "code": null, "e": 35103, "s": 35085, "text": "Python Dictionary" }, { "code": null, "e": 35126, "s": 35103, "text": "Taking input in Python" } ]
Java Program to subtract 1 year from the calendar
Firstly, you need to import the following package for Calendar class in Java import java.util.Calendar; Create a Calendar object and display the current date and time Calendar calendar = Calendar.getInstance(); System.out.println("Current Date and Time = " + calendar.getTime()); Now, let us subtract 1 year using the calendar.add() method and Calendar.YEAR constant. Set a negative value since we are decrementing here − calendar.add(Calendar.YEAR, -1); The following is an example Live Demo import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.println("Current Date = " + calendar.getTime()); // Subtract 1 year from the Calendar calendar.add(Calendar.YEAR, -1); System.out.println("Updated Date = " + calendar.getTime()); } } Current Date = Fri Nov 23 06:39:40 UTC 2018 Updated Date = Thu Nov 23 06:39:40 UTC 2017
[ { "code": null, "e": 1139, "s": 1062, "text": "Firstly, you need to import the following package for Calendar class in Java" }, { "code": null, "e": 1166, "s": 1139, "text": "import java.util.Calendar;" }, { "code": null, "e": 1229, "s": 1166, "text": "Create a Calendar object and display the current date and time" }, { "code": null, "e": 1342, "s": 1229, "text": "Calendar calendar = Calendar.getInstance();\nSystem.out.println(\"Current Date and Time = \" + calendar.getTime());" }, { "code": null, "e": 1484, "s": 1342, "text": "Now, let us subtract 1 year using the calendar.add() method and Calendar.YEAR constant. Set a negative value since we are decrementing here −" }, { "code": null, "e": 1517, "s": 1484, "text": "calendar.add(Calendar.YEAR, -1);" }, { "code": null, "e": 1545, "s": 1517, "text": "The following is an example" }, { "code": null, "e": 1556, "s": 1545, "text": " Live Demo" }, { "code": null, "e": 1918, "s": 1556, "text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar calendar = Calendar.getInstance();\n System.out.println(\"Current Date = \" + calendar.getTime());\n // Subtract 1 year from the Calendar\n calendar.add(Calendar.YEAR, -1);\n System.out.println(\"Updated Date = \" + calendar.getTime());\n }\n}" }, { "code": null, "e": 2006, "s": 1918, "text": "Current Date = Fri Nov 23 06:39:40 UTC 2018\nUpdated Date = Thu Nov 23 06:39:40 UTC 2017" } ]
Fetch all href link using selenium in python.
We can fetch href links in a page in Selenium by using the method find_elements(). All the links in the webpage are designed in a html document such that they are enclosed within the anchor tag. To fetch all the elements having <anchor> tagname, we shall use the method find_elements_by_tag_name(). It will fetch a list of elements of anchor tag name as given in the method argument. If there is no matching tagname in the page, an empty list shall be returned. Code Implementation. from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") driver.maximize_window() driver.get("https://www.google.com/") # identify elements with tagname <a> lnks=driver.find_elements_by_tag_name("a") # traverse list for lnk in lnks: # get_attribute() to get all href print(lnk.get_attribute(href)) driver.quit()
[ { "code": null, "e": 1257, "s": 1062, "text": "We can fetch href links in a page in Selenium by using the method find_elements(). All the links in the webpage are designed in a html document such that they are enclosed within the anchor tag." }, { "code": null, "e": 1524, "s": 1257, "text": "To fetch all the elements having <anchor> tagname, we shall use the method find_elements_by_tag_name(). It will fetch a list of elements of anchor tag name as given in the method argument. If there is no matching tagname in the page, an empty list shall be returned." }, { "code": null, "e": 1545, "s": 1524, "text": "Code Implementation." }, { "code": null, "e": 1904, "s": 1545, "text": "from selenium import webdriver\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\ndriver.maximize_window()\ndriver.get(\"https://www.google.com/\")\n# identify elements with tagname <a>\nlnks=driver.find_elements_by_tag_name(\"a\")\n# traverse list\nfor lnk in lnks:\n # get_attribute() to get all href\n print(lnk.get_attribute(href))\ndriver.quit()" } ]
Count of rooks that can attack each other out of K rooks placed on a N*N chessboard - GeeksforGeeks
07 Jan, 2022 Given pair of coordinates of K rooks on an N X N chessboard, the task is to count the number of rooks that can attack each other. Note: 1 <= K <= N*NExamples: Input: K = 2, arr[][] = { {2, 2}, {2, 3} }, N = 8Output: 2Explanation: Both the rooks can attack each other, because they are in the same row. Therefore, count of rooks that can attack each other is 2 Input: K = 1, arr[][] = { {4, 5} }, N = 4Output: 0 Approach: The task can easily be solved using the fact that, 2 rooks can attack each other if they are either in the same row or in the same column, else they can’t attack each other. Below is the implementation of the above code: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the number of attacking rooksint willAttack(vector<vector<int> >& arr, int k, int N){ int ans = 0; for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { if (i != j) { // Check if rooks are in same row // or same column if ((arr[i][0] == arr[j][0]) || (arr[i][1] == arr[j][1])) ans++; } } } return ans;} // Driver Codeint main(){ vector<vector<int> > arr = { { 2, 2 }, { 2, 3 } }; int K = 2, N = 8; cout << willAttack(arr, K, N); return 0;} import java.io.*;import java.util.*; class Solution { static int willAttack(int arr[][], int k, int N) { int ans = 0; for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { if (i != j) { // Check if rooks are in same row // or same column if ((arr[i][0] == arr[j][0]) || (arr[i][1] == arr[j][1])) ans++; } } } return ans; } // Driver code public static void main(String[] args) { int[][] arr = { { 2, 2 }, { 2, 3 } }; int K = 2, N = 8; System.out.println(willAttack(arr, K, N)); }} // This code is contributed by dwivediyash. # python program for the above approach # Function to count the number of attacking rooksdef willAttack(arr, k, N): ans = 0 for i in range(0, k): for j in range(0, k): if (i != j): # Check if rooks are in same row # or same column if ((arr[i][0] == arr[j][0]) or (arr[i][1] == arr[j][1])): ans += 1 return ans # Driver Codeif __name__ == "__main__": arr = [[2, 2], [2, 3]] K = 2 N = 8 print(willAttack(arr, K, N)) # This code is contributed by rakeshsahni using System;class Solution{ static int willAttack(int[,] arr, int k, int N) { int ans = 0; for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { if (i != j) { // Check if rooks are in same row // or same column if ((arr[i, 0] == arr[j, 0]) || (arr[i, 1] == arr[j, 1])) ans++; } } } return ans; } // Driver code public static void Main() { int[,] arr = { { 2, 2 }, { 2, 3 } }; int K = 2, N = 8; Console.WriteLine(willAttack(arr, K, N)); }} // This code is contributed by gfgking <script> // JavaScript code for the above approach // Function to count the number of attacking rooks function willAttack(arr, k, N) { let ans = 0; for (let i = 0; i < k; i++) { for (let j = 0; j < k; j++) { if (i != j) { // Check if rooks are in same row // or same column if ((arr[i][0] == arr[j][0]) || (arr[i][1] == arr[j][1])) ans++; } } } return ans; } // Driver Code let arr = [[2, 2], [2, 3]]; let K = 2, N = 8; document.write(willAttack(arr, K, N)); // This code is contributed by Potta Lokesh </script> 2 Time Complexity: O(K*K)Auxiliary Space: O(1) lokeshpotta20 dwivediyash rakeshsahni gfgking Algo-Geek 2021 chessboard-problems Algo Geek Greedy Matrix Greedy Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of operation required to water all the plants Lexicographically smallest string formed by concatenating any prefix and its mirrored form Divide given number into two even parts Check if an edge is a part of any Minimum Spanning Tree Check if the given string is valid English word or not Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26160, "s": 26132, "text": "\n07 Jan, 2022" }, { "code": null, "e": 26319, "s": 26160, "text": "Given pair of coordinates of K rooks on an N X N chessboard, the task is to count the number of rooks that can attack each other. Note: 1 <= K <= N*NExamples:" }, { "code": null, "e": 26521, "s": 26319, "text": "Input: K = 2, arr[][] = { {2, 2}, {2, 3} }, N = 8Output: 2Explanation: Both the rooks can attack each other, because they are in the same row. Therefore, count of rooks that can attack each other is 2 " }, { "code": null, "e": 26572, "s": 26521, "text": "Input: K = 1, arr[][] = { {4, 5} }, N = 4Output: 0" }, { "code": null, "e": 26756, "s": 26572, "text": "Approach: The task can easily be solved using the fact that, 2 rooks can attack each other if they are either in the same row or in the same column, else they can’t attack each other." }, { "code": null, "e": 26803, "s": 26756, "text": "Below is the implementation of the above code:" }, { "code": null, "e": 26807, "s": 26803, "text": "C++" }, { "code": null, "e": 26812, "s": 26807, "text": "Java" }, { "code": null, "e": 26820, "s": 26812, "text": "Python3" }, { "code": null, "e": 26823, "s": 26820, "text": "C#" }, { "code": null, "e": 26834, "s": 26823, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the number of attacking rooksint willAttack(vector<vector<int> >& arr, int k, int N){ int ans = 0; for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { if (i != j) { // Check if rooks are in same row // or same column if ((arr[i][0] == arr[j][0]) || (arr[i][1] == arr[j][1])) ans++; } } } return ans;} // Driver Codeint main(){ vector<vector<int> > arr = { { 2, 2 }, { 2, 3 } }; int K = 2, N = 8; cout << willAttack(arr, K, N); return 0;}", "e": 27530, "s": 26834, "text": null }, { "code": "import java.io.*;import java.util.*; class Solution { static int willAttack(int arr[][], int k, int N) { int ans = 0; for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { if (i != j) { // Check if rooks are in same row // or same column if ((arr[i][0] == arr[j][0]) || (arr[i][1] == arr[j][1])) ans++; } } } return ans; } // Driver code public static void main(String[] args) { int[][] arr = { { 2, 2 }, { 2, 3 } }; int K = 2, N = 8; System.out.println(willAttack(arr, K, N)); }} // This code is contributed by dwivediyash.", "e": 28171, "s": 27530, "text": null }, { "code": "# python program for the above approach # Function to count the number of attacking rooksdef willAttack(arr, k, N): ans = 0 for i in range(0, k): for j in range(0, k): if (i != j): # Check if rooks are in same row # or same column if ((arr[i][0] == arr[j][0]) or (arr[i][1] == arr[j][1])): ans += 1 return ans # Driver Codeif __name__ == \"__main__\": arr = [[2, 2], [2, 3]] K = 2 N = 8 print(willAttack(arr, K, N)) # This code is contributed by rakeshsahni", "e": 28763, "s": 28171, "text": null }, { "code": "using System;class Solution{ static int willAttack(int[,] arr, int k, int N) { int ans = 0; for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { if (i != j) { // Check if rooks are in same row // or same column if ((arr[i, 0] == arr[j, 0]) || (arr[i, 1] == arr[j, 1])) ans++; } } } return ans; } // Driver code public static void Main() { int[,] arr = { { 2, 2 }, { 2, 3 } }; int K = 2, N = 8; Console.WriteLine(willAttack(arr, K, N)); }} // This code is contributed by gfgking", "e": 29371, "s": 28763, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to count the number of attacking rooks function willAttack(arr, k, N) { let ans = 0; for (let i = 0; i < k; i++) { for (let j = 0; j < k; j++) { if (i != j) { // Check if rooks are in same row // or same column if ((arr[i][0] == arr[j][0]) || (arr[i][1] == arr[j][1])) ans++; } } } return ans; } // Driver Code let arr = [[2, 2], [2, 3]]; let K = 2, N = 8; document.write(willAttack(arr, K, N)); // This code is contributed by Potta Lokesh </script>", "e": 30140, "s": 29371, "text": null }, { "code": null, "e": 30142, "s": 30140, "text": "2" }, { "code": null, "e": 30187, "s": 30142, "text": "Time Complexity: O(K*K)Auxiliary Space: O(1)" }, { "code": null, "e": 30201, "s": 30187, "text": "lokeshpotta20" }, { "code": null, "e": 30213, "s": 30201, "text": "dwivediyash" }, { "code": null, "e": 30225, "s": 30213, "text": "rakeshsahni" }, { "code": null, "e": 30233, "s": 30225, "text": "gfgking" }, { "code": null, "e": 30248, "s": 30233, "text": "Algo-Geek 2021" }, { "code": null, "e": 30268, "s": 30248, "text": "chessboard-problems" }, { "code": null, "e": 30278, "s": 30268, "text": "Algo Geek" }, { "code": null, "e": 30285, "s": 30278, "text": "Greedy" }, { "code": null, "e": 30292, "s": 30285, "text": "Matrix" }, { "code": null, "e": 30299, "s": 30292, "text": "Greedy" }, { "code": null, "e": 30306, "s": 30299, "text": "Matrix" }, { "code": null, "e": 30404, "s": 30306, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30456, "s": 30404, "text": "Count of operation required to water all the plants" }, { "code": null, "e": 30547, "s": 30456, "text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form" }, { "code": null, "e": 30587, "s": 30547, "text": "Divide given number into two even parts" }, { "code": null, "e": 30643, "s": 30587, "text": "Check if an edge is a part of any Minimum Spanning Tree" }, { "code": null, "e": 30698, "s": 30643, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 30749, "s": 30698, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 30807, "s": 30749, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 30858, "s": 30807, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 30885, "s": 30858, "text": "Program for array rotation" } ]
How to get first N number of elements from an array using ReactJS? - GeeksforGeeks
18 Jan, 2021 We can use the slice() method to get the first N number of elements from an array. Syntax: array.slice(0, n); Example: var num = [1, 2, 3, 4, 5]; var myBest = num.slice(0, 3); Output: [1,2,3] Note: The slice function on arrays returns a shallow copy of the array, and does not modify the original array. And if N is larger than the size of the array then it won’t through any error and returns the whole array itself. Creating React Application: 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 Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import { React, Component } from "react";class App extends Component { render() { // Numbers list const list = [1, 2, 3, 4, 5, 6, 7] // Defining our N var n = 4; // Slice function call var items = list.slice(0, n).map(i => { return <button style={{ margin: 10 }} type="button" class="btn btn-primary">{i}</button> }) return ( <div>{items}</div> ) }} export default App Note: You can apply your own styling to the application. Here we have used bootstrap CSS, to include it in your project, just add the following <link> to our index.html file. <linkrel=”stylesheet”href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css”integrity=”sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk”crossorigin=”anonymous”/> Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Since the value of n is four, so four-button will be created. If increase the value of n the number of buttons will increase and vice-versa. Picked JavaScript ReactJS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to get selected value in dropdown list using JavaScript ? How to remove duplicate elements from JavaScript Array ? 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 ? ReactJS Functional Components How to pass data from one component to other component in ReactJS ?
[ { "code": null, "e": 25312, "s": 25284, "text": "\n18 Jan, 2021" }, { "code": null, "e": 25395, "s": 25312, "text": "We can use the slice() method to get the first N number of elements from an array." }, { "code": null, "e": 25403, "s": 25395, "text": "Syntax:" }, { "code": null, "e": 25422, "s": 25403, "text": "array.slice(0, n);" }, { "code": null, "e": 25431, "s": 25422, "text": "Example:" }, { "code": null, "e": 25488, "s": 25431, "text": "var num = [1, 2, 3, 4, 5];\nvar myBest = num.slice(0, 3);" }, { "code": null, "e": 25496, "s": 25488, "text": "Output:" }, { "code": null, "e": 25504, "s": 25496, "text": "[1,2,3]" }, { "code": null, "e": 25730, "s": 25504, "text": "Note: The slice function on arrays returns a shallow copy of the array, and does not modify the original array. And if N is larger than the size of the array then it won’t through any error and returns the whole array itself." }, { "code": null, "e": 25758, "s": 25730, "text": "Creating React Application:" }, { "code": null, "e": 25822, "s": 25758, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25854, "s": 25822, "text": "npx create-react-app foldername" }, { "code": null, "e": 25954, "s": 25854, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25968, "s": 25954, "text": "cd foldername" }, { "code": null, "e": 26020, "s": 25968, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26038, "s": 26020, "text": "Project Structure" }, { "code": null, "e": 26167, "s": 26038, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26178, "s": 26167, "text": "Javascript" }, { "code": "import { React, Component } from \"react\";class App extends Component { render() { // Numbers list const list = [1, 2, 3, 4, 5, 6, 7] // Defining our N var n = 4; // Slice function call var items = list.slice(0, n).map(i => { return <button style={{ margin: 10 }} type=\"button\" class=\"btn btn-primary\">{i}</button> }) return ( <div>{items}</div> ) }} export default App", "e": 26602, "s": 26178, "text": null }, { "code": null, "e": 26777, "s": 26602, "text": "Note: You can apply your own styling to the application. Here we have used bootstrap CSS, to include it in your project, just add the following <link> to our index.html file." }, { "code": null, "e": 26983, "s": 26777, "text": "<linkrel=”stylesheet”href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css”integrity=”sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk”crossorigin=”anonymous”/>" }, { "code": null, "e": 27096, "s": 26983, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27106, "s": 27096, "text": "npm start" }, { "code": null, "e": 27257, "s": 27106, "text": "Output: Since the value of n is four, so four-button will be created. If increase the value of n the number of buttons will increase and vice-versa. " }, { "code": null, "e": 27264, "s": 27257, "text": "Picked" }, { "code": null, "e": 27275, "s": 27264, "text": "JavaScript" }, { "code": null, "e": 27283, "s": 27275, "text": "ReactJS" }, { "code": null, "e": 27381, "s": 27283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27390, "s": 27381, "text": "Comments" }, { "code": null, "e": 27403, "s": 27390, "text": "Old Comments" }, { "code": null, "e": 27464, "s": 27403, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27505, "s": 27464, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27559, "s": 27505, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27621, "s": 27559, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27678, "s": 27621, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27721, "s": 27678, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27766, "s": 27721, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27831, "s": 27766, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27861, "s": 27831, "text": "ReactJS Functional Components" } ]
Smallest window in a string containing all the characters of another string | Practice | GeeksforGeeks
Given two strings S and P. Find the smallest window in the string S consisting of all the characters(including duplicates) of the string P. Return "-1" in case there is no such window present. In case there are multiple such windows of same length, return the one with the least starting index. Example 1: Input: S = "timetopractice" P = "toc" Output: toprac Explanation: "toprac" is the smallest substring in which "toc" can be found. Example 2: Input: S = "zoomlazapzo" P = "oza" Output: apzo Explanation: "apzo" is the smallest substring in which "oza" can be found. Your Task: You don't need to read input or print anything. Your task is to complete the function smallestWindow() which takes two string S and P as input paramters and returns the smallest window in string S having all the characters of the string P. In case there are multiple such windows of same length, return the one with the least starting index. Expected Time Complexity: O(|S|) Expected Auxiliary Space: O(1) Constraints: 1 ≤ |S|, |P| ≤ 105 0 tupesanket1999in 3 hours C++ SLIDING WINDOW Total Time Taken: 0.21/2.2 string smallestWindow (string s, string p){ if(s.size()<p.size())return "-1"; int req[26]={0}; int brr[26]={0}; for(int i=0;i<p.size();i++) req[p[i]-'a']++; int i=0,j=0; int useFull=0; int left=INT_MIN,right=INT_MAX; while(j<s.size()){ //aquire while(useFull<p.size() && j <s.size()){ if(req[s[j]-'a']>brr[s[j]-'a']){ brr[s[j]-'a']++; useFull++; }else{ brr[s[j]-'a']++; } j++; } if((long long)right-left > j-1-i && useFull==p.size()){ left =i; right=j-1; } //release while(useFull==p.size()){ if(req[s[i]-'a']<brr[s[i]-'a']){ brr[s[i]-'a']--; }else{ brr[s[i]-'a']--; useFull--; } i++; if(useFull==p.size()){ if((long long)right-left > j-1-i){ left =i; right=j-1; } } } } string st=""; if(left >=0){ for(int i=left;i<=right;i++) st+=s[i]; }else{ st="-1"; } return st; } 0 mahesh_phutane1 week ago Simple java solution using HashMap class Solution { public static String smallestWindow(String s, String p) { if(p.length() > s.length()) { return "-1"; } Map<Character,Integer> mp = new HashMap<>(); //for String p Map<Character,Integer> mp1 = new HashMap<>(); //for String s for(int i = 0; i < p.length(); ++i) { mp.put(p.charAt(i),mp.getOrDefault(p.charAt(i),0)+1); } String ans = "-1"; int maxlen = Integer.MAX_VALUE; // to get minimum length substring int i = 0,j = 0; int match = 0; // to store the count of matched char from string p while(j<s.length()){ //acquire characters in string s while(match<p.length()&& j<s.length()){ mp1.put(s.charAt(j),mp1.getOrDefault(s.charAt(j),0)+1); if(mp1.get(s.charAt(j))<=mp.getOrDefault(s.charAt(j),0)){ match+=1; } j++; } //release characters in string s to get shortest substring while(match==p.length() && i<s.length()){ if(match==p.length()){ String res = s.substring(i,j); if(res.length()<maxlen){ maxlen = res.length(); ans = res; // store ans } } mp1.put(s.charAt(i),mp1.get(s.charAt(i))-1); if(mp1.get(s.charAt(i))<mp.getOrDefault(s.charAt(i),Integer.MIN_VALUE)){ match-=1; } i+=1; } } return ans; } } 0 rohit250820002 weeks ago string smallestWindow (string s, string p) { if(p.length() > s.length()) { return "-1"; } unordered_map<char,int> hash; for(int i = 0; i < p.length(); ++i) { hash[p[i]]++; } int num_of_element = hash.size(); int i = 0; int j = 0; int min_length = s.length(); int start_index = 0; bool found = false; while(j < s.length()) { if(hash.find(s[j]) != hash.end()) { if(--hash[s[j]] == 0) { num_of_element--; } } while(num_of_element == 0) { found = true; if(min_length > j - i + 1) { min_length = j - i + 1; start_index = i; } if(hash.find(s[i]) != hash.end()) { if(++hash[s[i]] > 0) { num_of_element++; } } i++; } j++; } if(found) { return s.substr(start_index, min_length); } return "-1"; } +1 abhishekvishwakarma2872 weeks ago This is not a medium level question, it is a hard level question +1 aloksinghbais022 weeks ago C++ solution having time complexity as O(|S|) and space complexity as O(128) is as follows :- Execution Time :- 0.19 / 2.2 sec string smallestWindow (string s, string p){ int n = s.length(), m = p.length(); int freq1[128] = {0}; for(char x: p){ freq1[x]++; } int freq2[128] = {0}; int st = -1; int len = n; int cnt = 0; int i = 0, j = 0; while(j < n){ char ch = s[j]; if(freq2[ch] < freq1[ch]) cnt++; freq2[ch]++; while(cnt == m){ if(j-i+1 < len){ st = i; len = j-i+1; } if(freq1[s[i]]) freq2[s[i]]--; if(freq2[s[i]] < freq1[s[i]]) cnt--; i++; } j++; } if(st == -1) return ("-1"); return s.substr(st,len); } 0 roytanisha5722 weeks ago I'm getting TLE even though my solution is O(n) time, (n - length of txt) can someone point out to me what's going wrong. I'm suspecting some infinite computation or I'm missing some test cases. Idea for the algorithm: I've used sliding window technique where the window txt[i..j] is considered in every iteration and the window is extended when pattern chars are not contained in the window. and when it is contained, the window is shrunk by bringing i closer to j, all the while checking if the pattern chars are contained in the updated window. Please comment if anyone is able to find the error, appreciate all help. Thanks! //aux function to check if pattern is contained in the txt window. bool patContained(int ctxt[], int cpat[]){ for(int k=0; k<256; k++){ if(ctxt[k] < cpat[k]) return false; } return true; } string smallestWindow (string txt, string pat) { int n = txt.length(); int m = pat.length(); int res = INT_MAX; int cpat[256] = {0}; int ctxt[256] = {0}; for(int i=0; i<m; i++) cpat[pat[i]]++; int i=0, j=0; int strt = -1, end = -1; ctxt[txt[0]]++; while(j<n){ //extend the window(j++)until all chars of pat are included in the window bool isContained = patContained(ctxt, cpat); if(!isContained){ //extend the window j++; ctxt[txt[j]]++; } else{ //all chars of pat are contained, so we'll shrink the window(i++) //in attempt to get a smaller window conatined all chars of pat do{ if(res > (j-i+1)){ res = (j-i+1); strt = i; end = j; } ctxt[txt[i]]--; i++; } while(i<=j && patContained(ctxt, cpat)); } } if(res == INT_MAX) return "-1"; else return txt.substr(strt,end-strt+1); } +1 madhukartemba2 weeks ago JAVA SOLUTION: class Solution { private static boolean allPresent(HashMap<Character, Integer> map) { for(Map.Entry<Character, Integer> es : map.entrySet()) { if(es.getValue()>0) return false; } return true; } //Function to find the smallest window in the string s consisting //of all the characters of string p. public static String smallestWindow(String s, String p) { HashMap<Character, Integer> map = new HashMap<>(); for(char ch : p.toCharArray()) { map.put(ch, map.getOrDefault(ch, 0)+1); } int n = s.length(); int j=0; int ans_len = Integer.MAX_VALUE; int st=-1, en=-1; for(int i=0; i<n; i++) { char ch = s.charAt(i); if(map.containsKey(ch)) map.put(ch, map.get(ch)-1); if(allPresent(map)) { while(j<i) { char ch_rem = s.charAt(j); if(map.containsKey(ch_rem)==false) { j++; } else if(map.get(ch_rem)<0) { map.put(ch_rem, map.get(ch_rem)+1); j++; } else { break; } } int len = i-j; if(ans_len>len) { ans_len = len; st = j; en = i; } } } if(st==-1 || en==-1) return "-1"; return s.substring(st, en+1); } } +1 abhishektyagi12633 weeks ago //Please code it right string smallestWindow (string s, string p) { unordered_map<char,int> m; for(int i=0;i<p.size();i++){ m[p[i]]=-1; } int currlen=s.size()-1;int minlen=s.size()-1;int start,end,fs,fe,r; int poi=0; while(poi<s.size()){ // if we found a character and its a new one; auto f = m.find(s[poi]); if(f!=m.end() && m[s[poi]]>-1){ m[s[poi]]=poi; } if(f!=m.end() && m[s[poi]]==-1){ m[s[poi]]=poi; } r=INT_MAX; for(auto v:m){ if(v.second>=0){ r=min(v.second,r);} else(r=-1); } if(r!=-1){ start=r;end=poi; currlen=poi-r; if(currlen<minlen){minlen=currlen;fs=r;fe=poi;}} // } poi++; } // cout<<fs<<" "<<fe<<" "; for(auto r:m){ if(r.second==-1){return "-1";} // {cout<<r.first<<" "<<r.second;} } string aman=""; for(int i=fs;i<=fe;i++){ aman=aman+s[i]; } return aman; } 0 itachinamikaze2213 weeks ago JAVA public static String smallestWindow(String s, String p) { HashMap<Character, Integer> map2 =new HashMap<>(); for(int i=0; i<p.length();i++) { char ch= p.charAt(i); map2.put(ch, map2.getOrDefault(ch, 0)+1); } int matcount=0; int i=-1; int j=-1; int dmct=p.length(); HashMap<Character, Integer> map1 =new HashMap<>(); String ans=""; while(true) {//acquire boolean f1=false, f2=false; while(i<s.length()-1 && matcount<dmct) { i++; char ch=s.charAt(i); map1.put(ch, map1.getOrDefault(ch, 0)+1); if(map1.getOrDefault(ch, 0)<=map2.getOrDefault(ch, 0)) { matcount++; } f1= true; } //Collect while(j<i && matcount==dmct) { String pans= s.substring(j+1, i+1); if(ans.length()==0 || pans.length()< ans.length()) ans=pans; j++; char ch= s.charAt(j); if(map1.get(ch)==1) map1.remove(ch); else map1.put(ch, map1.get(ch)-1); if(map1.getOrDefault(ch, 0)<map2.getOrDefault(ch,0)) matcount--; f2=true; } if(f1==false && f2==false) break; } if(ans.length()==0) return"-1"; else return ans;} 0 manishmaheshwari81331 month ago pepcoding solution class Solution { //Function to find the smallest window in the string s consisting //of all the characters of string p. public static String smallestWindow(String s, String p) { if(p.length()==1)return String.valueOf(p.charAt(0)) ; String ans=""; int i=-1; int j=-1; HashMap<Character,Integer> map1=new HashMap<Character,Integer>(); HashMap<Character,Integer> map2=new HashMap<Character,Integer>(); for(int k=0;k<p.length();k++){ char chr=p.charAt(k); map2.put(chr,map2.getOrDefault(chr,0)+1); } int cnt=0; int dscnt=p.length(); while(true){ boolean f1=false; boolean f2=false; while(i<s.length() -1 && cnt<dscnt){ i++; char chr=s.charAt(i); map1.put(chr,map1.getOrDefault(chr,0)+1); if( map1.get(chr)<=map2.getOrDefault(chr,0)){ //System.out.println(chr+" "+map2.getOrDefault(chr,0)); cnt++; } f1=true; } while(j<i && cnt==dscnt ){ String pans=s.substring(j+1,i+1); //System.out.println(pans); if(ans.length()==0 || pans.length()<ans.length()){ ans=pans; } j++; char chr=s.charAt(j); if(map1.get(chr)==1)map1.remove(chr); else{ map1.put(chr, map1.get(chr)-1); } if( map1.getOrDefault(chr,0)<map2.getOrDefault(chr,0)) { cnt--; } f2=true; } if(f1==false && f2==false){ break; } } if ( ans.length()==0 )return "-1"; return ans; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 535, "s": 238, "text": "Given two strings S and P. Find the smallest window in the string S consisting of all the characters(including duplicates) of the string P. Return \"-1\" in case there is no such window present. In case there are multiple such windows of same length, return the one with the least starting index. " }, { "code": null, "e": 546, "s": 535, "text": "Example 1:" }, { "code": null, "e": 678, "s": 546, "text": "Input:\nS = \"timetopractice\"\nP = \"toc\"\nOutput: \ntoprac\nExplanation: \"toprac\" is the smallest\nsubstring in which \"toc\" can be found.\n" }, { "code": null, "e": 689, "s": 678, "text": "Example 2:" }, { "code": null, "e": 814, "s": 689, "text": "Input:\nS = \"zoomlazapzo\"\nP = \"oza\"\nOutput: \napzo\nExplanation: \"apzo\" is the smallest \nsubstring in which \"oza\" can be found." }, { "code": null, "e": 1168, "s": 814, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function smallestWindow() which takes two string S and P as input paramters and returns the smallest window in string S having all the characters of the string P. In case there are multiple such windows of same length, return the one with the least starting index. " }, { "code": null, "e": 1232, "s": 1168, "text": "Expected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1265, "s": 1232, "text": "Constraints: \n1 ≤ |S|, |P| ≤ 105" }, { "code": null, "e": 1267, "s": 1265, "text": "0" }, { "code": null, "e": 1292, "s": 1267, "text": "tupesanket1999in 3 hours" }, { "code": null, "e": 1311, "s": 1292, "text": "C++ SLIDING WINDOW" }, { "code": null, "e": 1338, "s": 1311, "text": "Total Time Taken: 0.21/2.2" }, { "code": null, "e": 2729, "s": 1338, "text": " string smallestWindow (string s, string p){\n if(s.size()<p.size())return \"-1\";\n int req[26]={0};\n int brr[26]={0};\n for(int i=0;i<p.size();i++)\n req[p[i]-'a']++;\n int i=0,j=0;\n int useFull=0;\n int left=INT_MIN,right=INT_MAX;\n while(j<s.size()){\n //aquire\n while(useFull<p.size() && j <s.size()){\n if(req[s[j]-'a']>brr[s[j]-'a']){\n brr[s[j]-'a']++;\n useFull++;\n }else{\n brr[s[j]-'a']++;\n }\n j++;\n }\n if((long long)right-left > j-1-i && useFull==p.size()){\n left =i;\n right=j-1;\n }\n //release\n while(useFull==p.size()){\n if(req[s[i]-'a']<brr[s[i]-'a']){\n brr[s[i]-'a']--;\n }else{\n brr[s[i]-'a']--;\n useFull--;\n }\n i++;\n if(useFull==p.size()){\n if((long long)right-left > j-1-i){\n left =i;\n right=j-1;\n }\n }\n }\n }\n string st=\"\";\n if(left >=0){\n for(int i=left;i<=right;i++)\n st+=s[i];\n }else{\n st=\"-1\";\n }\n return st;\n }" }, { "code": null, "e": 2731, "s": 2729, "text": "0" }, { "code": null, "e": 2756, "s": 2731, "text": "mahesh_phutane1 week ago" }, { "code": null, "e": 2791, "s": 2756, "text": "Simple java solution using HashMap" }, { "code": null, "e": 4609, "s": 2791, "text": "class Solution\n{\n public static String smallestWindow(String s, String p)\n {\n if(p.length() > s.length()) {\n return \"-1\"; \n }\n \n Map<Character,Integer> mp = new HashMap<>(); //for String p\n Map<Character,Integer> mp1 = new HashMap<>(); //for String s\n \n for(int i = 0; i < p.length(); ++i) {\n mp.put(p.charAt(i),mp.getOrDefault(p.charAt(i),0)+1);\n }\n \n String ans = \"-1\";\n int maxlen = Integer.MAX_VALUE; // to get minimum length substring\n int i = 0,j = 0;\n int match = 0; // to store the count of matched char from string p\n \n while(j<s.length()){\n \n //acquire characters in string s\n while(match<p.length()&& j<s.length()){\n \n mp1.put(s.charAt(j),mp1.getOrDefault(s.charAt(j),0)+1);\n \n if(mp1.get(s.charAt(j))<=mp.getOrDefault(s.charAt(j),0)){\n match+=1;\n }\n j++;\n }\n \n //release characters in string s to get shortest substring\n \n while(match==p.length() && i<s.length()){\n if(match==p.length()){\n String res = s.substring(i,j);\n if(res.length()<maxlen){\n maxlen = res.length();\n ans = res; // store ans\n }\n }\n \n mp1.put(s.charAt(i),mp1.get(s.charAt(i))-1);\n \n if(mp1.get(s.charAt(i))<mp.getOrDefault(s.charAt(i),Integer.MIN_VALUE)){\n match-=1;\n }\n \n i+=1;\n }\n }\n return ans;\n }\n}" }, { "code": null, "e": 4611, "s": 4609, "text": "0" }, { "code": null, "e": 4636, "s": 4611, "text": "rohit250820002 weeks ago" }, { "code": null, "e": 5919, "s": 4636, "text": " string smallestWindow (string s, string p)\n {\n if(p.length() > s.length()) {\n return \"-1\"; \n }\n \n unordered_map<char,int> hash; \n for(int i = 0; i < p.length(); ++i) {\n hash[p[i]]++;\n }\n int num_of_element = hash.size(); \n \n int i = 0; \n int j = 0; \n int min_length = s.length(); \n int start_index = 0; \n bool found = false; \n \n \n while(j < s.length()) {\n \n if(hash.find(s[j]) != hash.end()) {\n if(--hash[s[j]] == 0) {\n num_of_element--; \n } \n }\n \n while(num_of_element == 0) { \n found = true; \n if(min_length > j - i + 1) {\n min_length = j - i + 1; \n start_index = i; \n }\n if(hash.find(s[i]) != hash.end()) {\n if(++hash[s[i]] > 0) {\n num_of_element++; \n }\n }\n i++; \n }\n \n j++; \n }\n if(found) {\n return s.substr(start_index, min_length); \n }\n return \"-1\"; \n }" }, { "code": null, "e": 5922, "s": 5919, "text": "+1" }, { "code": null, "e": 5956, "s": 5922, "text": "abhishekvishwakarma2872 weeks ago" }, { "code": null, "e": 6021, "s": 5956, "text": "This is not a medium level question, it is a hard level question" }, { "code": null, "e": 6024, "s": 6021, "text": "+1" }, { "code": null, "e": 6051, "s": 6024, "text": "aloksinghbais022 weeks ago" }, { "code": null, "e": 6146, "s": 6051, "text": "C++ solution having time complexity as O(|S|) and space complexity as O(128) is as follows :- " }, { "code": null, "e": 6181, "s": 6148, "text": "Execution Time :- 0.19 / 2.2 sec" }, { "code": null, "e": 6978, "s": 6183, "text": "string smallestWindow (string s, string p){ int n = s.length(), m = p.length(); int freq1[128] = {0}; for(char x: p){ freq1[x]++; } int freq2[128] = {0}; int st = -1; int len = n; int cnt = 0; int i = 0, j = 0; while(j < n){ char ch = s[j]; if(freq2[ch] < freq1[ch]) cnt++; freq2[ch]++; while(cnt == m){ if(j-i+1 < len){ st = i; len = j-i+1; } if(freq1[s[i]]) freq2[s[i]]--; if(freq2[s[i]] < freq1[s[i]]) cnt--; i++; } j++; } if(st == -1) return (\"-1\"); return s.substr(st,len); }" }, { "code": null, "e": 6980, "s": 6978, "text": "0" }, { "code": null, "e": 7005, "s": 6980, "text": "roytanisha5722 weeks ago" }, { "code": null, "e": 7079, "s": 7005, "text": "I'm getting TLE even though my solution is O(n) time, (n - length of txt)" }, { "code": null, "e": 7201, "s": 7079, "text": "can someone point out to me what's going wrong. I'm suspecting some infinite computation or I'm missing some test cases. " }, { "code": null, "e": 7557, "s": 7203, "text": "Idea for the algorithm: I've used sliding window technique where the window txt[i..j] is considered in every iteration and the window is extended when pattern chars are not contained in the window. and when it is contained, the window is shrunk by bringing i closer to j, all the while checking if the pattern chars are contained in the updated window. " }, { "code": null, "e": 7639, "s": 7557, "text": "Please comment if anyone is able to find the error, appreciate all help. Thanks! " }, { "code": null, "e": 9317, "s": 7641, "text": "//aux function to check if pattern is contained in the txt window.\nbool patContained(int ctxt[], int cpat[]){\n \n for(int k=0; k<256; k++){\n if(ctxt[k] < cpat[k])\n return false;\n \n }\n \n return true;\n }\n\n\nstring smallestWindow (string txt, string pat)\n {\n int n = txt.length();\n int m = pat.length();\n \n int res = INT_MAX;\n \n int cpat[256] = {0};\n int ctxt[256] = {0};\n \n for(int i=0; i<m; i++)\n cpat[pat[i]]++;\n \n int i=0, j=0;\n int strt = -1, end = -1;\n \n ctxt[txt[0]]++;\n while(j<n){\n //extend the window(j++)until all chars of pat are included in the window\n \n bool isContained = patContained(ctxt, cpat);\n \n if(!isContained){\n //extend the window \n \n j++;\n ctxt[txt[j]]++;\n }\n else{\n //all chars of pat are contained, so we'll shrink the window(i++)\n //in attempt to get a smaller window conatined all chars of pat\n \n do{\n if(res > (j-i+1)){\n res = (j-i+1);\n strt = i;\n end = j;\n }\n ctxt[txt[i]]--;\n i++;\n } while(i<=j && patContained(ctxt, cpat));\n \n }\n }\n \n if(res == INT_MAX)\n return \"-1\";\n else\n return txt.substr(strt,end-strt+1);\n }" }, { "code": null, "e": 9320, "s": 9317, "text": "+1" }, { "code": null, "e": 9345, "s": 9320, "text": "madhukartemba2 weeks ago" }, { "code": null, "e": 9360, "s": 9345, "text": "JAVA SOLUTION:" }, { "code": null, "e": 11291, "s": 9360, "text": "class Solution\n{\n \n private static boolean allPresent(HashMap<Character, Integer> map)\n {\n for(Map.Entry<Character, Integer> es : map.entrySet())\n {\n if(es.getValue()>0) return false;\n }\n \n \n return true;\n }\n \n //Function to find the smallest window in the string s consisting\n //of all the characters of string p.\n public static String smallestWindow(String s, String p)\n {\n HashMap<Character, Integer> map = new HashMap<>();\n \n for(char ch : p.toCharArray())\n {\n map.put(ch, map.getOrDefault(ch, 0)+1);\n }\n int n = s.length();\n int j=0;\n \n int ans_len = Integer.MAX_VALUE;\n \n int st=-1, en=-1;\n \n for(int i=0; i<n; i++)\n {\n char ch = s.charAt(i);\n \n if(map.containsKey(ch)) map.put(ch, map.get(ch)-1);\n \n if(allPresent(map))\n {\n while(j<i)\n {\n char ch_rem = s.charAt(j);\n if(map.containsKey(ch_rem)==false)\n {\n j++;\n }\n else if(map.get(ch_rem)<0)\n {\n map.put(ch_rem, map.get(ch_rem)+1);\n j++;\n }\n else\n {\n break;\n }\n }\n \n int len = i-j;\n \n if(ans_len>len)\n {\n ans_len = len;\n st = j;\n en = i;\n }\n \n \n }\n \n }\n \n if(st==-1 || en==-1) return \"-1\";\n \n return s.substring(st, en+1);\n \n \n \n }\n}" }, { "code": null, "e": 11294, "s": 11291, "text": "+1" }, { "code": null, "e": 11323, "s": 11294, "text": "abhishektyagi12633 weeks ago" }, { "code": null, "e": 11347, "s": 11323, "text": "//Please code it right " }, { "code": null, "e": 12531, "s": 11347, "text": "string smallestWindow (string s, string p) { unordered_map<char,int> m; for(int i=0;i<p.size();i++){ m[p[i]]=-1; } int currlen=s.size()-1;int minlen=s.size()-1;int start,end,fs,fe,r; int poi=0; while(poi<s.size()){ // if we found a character and its a new one; auto f = m.find(s[poi]); if(f!=m.end() && m[s[poi]]>-1){ m[s[poi]]=poi; } if(f!=m.end() && m[s[poi]]==-1){ m[s[poi]]=poi; } r=INT_MAX; for(auto v:m){ if(v.second>=0){ r=min(v.second,r);} else(r=-1); } if(r!=-1){ start=r;end=poi; currlen=poi-r; if(currlen<minlen){minlen=currlen;fs=r;fe=poi;}} // } poi++; } // cout<<fs<<\" \"<<fe<<\" \"; for(auto r:m){ if(r.second==-1){return \"-1\";} // {cout<<r.first<<\" \"<<r.second;} } string aman=\"\"; for(int i=fs;i<=fe;i++){ aman=aman+s[i]; } return aman; }" }, { "code": null, "e": 12533, "s": 12531, "text": "0" }, { "code": null, "e": 12562, "s": 12533, "text": "itachinamikaze2213 weeks ago" }, { "code": null, "e": 12570, "s": 12562, "text": "JAVA " }, { "code": null, "e": 13824, "s": 12570, "text": "public static String smallestWindow(String s, String p) { HashMap<Character, Integer> map2 =new HashMap<>(); for(int i=0; i<p.length();i++) { char ch= p.charAt(i); map2.put(ch, map2.getOrDefault(ch, 0)+1); } int matcount=0; int i=-1; int j=-1; int dmct=p.length(); HashMap<Character, Integer> map1 =new HashMap<>(); String ans=\"\"; while(true) {//acquire boolean f1=false, f2=false; while(i<s.length()-1 && matcount<dmct) { i++; char ch=s.charAt(i); map1.put(ch, map1.getOrDefault(ch, 0)+1); if(map1.getOrDefault(ch, 0)<=map2.getOrDefault(ch, 0)) { matcount++; } f1= true; } //Collect while(j<i && matcount==dmct) { String pans= s.substring(j+1, i+1); if(ans.length()==0 || pans.length()< ans.length()) ans=pans; j++; char ch= s.charAt(j); if(map1.get(ch)==1) map1.remove(ch); else map1.put(ch, map1.get(ch)-1); if(map1.getOrDefault(ch, 0)<map2.getOrDefault(ch,0)) matcount--; f2=true; } if(f1==false && f2==false) break; } if(ans.length()==0) return\"-1\"; else return ans;}" }, { "code": null, "e": 13826, "s": 13824, "text": "0" }, { "code": null, "e": 13858, "s": 13826, "text": "manishmaheshwari81331 month ago" }, { "code": null, "e": 13877, "s": 13858, "text": "pepcoding solution" }, { "code": null, "e": 16268, "s": 13877, "text": "class Solution\n{\n //Function to find the smallest window in the string s consisting\n //of all the characters of string p.\n public static String smallestWindow(String s, String p)\n {\n \n if(p.length()==1)return String.valueOf(p.charAt(0)) ;\n \n String ans=\"\";\n\t int i=-1;\n\t int j=-1;\n\t HashMap<Character,Integer> map1=new HashMap<Character,Integer>();\n\t HashMap<Character,Integer> map2=new HashMap<Character,Integer>();\n\t \n\t for(int k=0;k<p.length();k++){\n\t char chr=p.charAt(k);\n\t map2.put(chr,map2.getOrDefault(chr,0)+1);\n\t }\n\n\t \n\t int cnt=0;\n\t int dscnt=p.length(); \n\t \n\t while(true){\n\t \tboolean f1=false;\n\t \t boolean f2=false;\n\t \n\t while(i<s.length() -1 && cnt<dscnt){\n\t i++;\n\t char chr=s.charAt(i);\n\t \n\t map1.put(chr,map1.getOrDefault(chr,0)+1);\n\t if( map1.get(chr)<=map2.getOrDefault(chr,0)){\n\t \t //System.out.println(chr+\" \"+map2.getOrDefault(chr,0));\n\t cnt++;\n\t }\n\t \n\t f1=true;\n\t }\n\t \n\t while(j<i && cnt==dscnt ){\n\t \t\n\t String pans=s.substring(j+1,i+1);\n\t //System.out.println(pans);\n\t if(ans.length()==0 || pans.length()<ans.length()){\n\t ans=pans; \n\t }\n\t j++;\n\t \n\t char chr=s.charAt(j);\n\t if(map1.get(chr)==1)map1.remove(chr);\n\t else{\n\t map1.put(chr, map1.get(chr)-1);\n\t }\n\t \n\t if( map1.getOrDefault(chr,0)<map2.getOrDefault(chr,0)) {\n\t \tcnt--;\t\n\t \t\n\t }\n\t \n\t f2=true;\n\t }\n\t \n\t if(f1==false && f2==false){\n\t break;\n\t }\t \n\t \n\t }\n\t \n\t if ( ans.length()==0 )return \"-1\";\n\t \n\t return ans; \n }\n}" }, { "code": null, "e": 16414, "s": 16268, "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": 16450, "s": 16414, "text": " Login to access your submissions. " }, { "code": null, "e": 16460, "s": 16450, "text": "\nProblem\n" }, { "code": null, "e": 16470, "s": 16460, "text": "\nContest\n" }, { "code": null, "e": 16533, "s": 16470, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 16681, "s": 16533, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 16889, "s": 16681, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 16995, "s": 16889, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Angular 2 - Quick Guide
Angular JS is an open source framework built over JavaScript. It was built by the developers at Google. This framework was used to overcome obstacles encountered while working with Single Page applications. Also, testing was considered as a key aspect while building the framework. It was ensured that the framework could be easily tested. The initial release of the framework was in October 2010. Following are the key features of Angular 2 − Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time. Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time. TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft. TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft. Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications. Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications. In addition, Angular 2 has better event-handling capabilities, powerful templates, and better support for mobile devices. Angular 2 has the following components − Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task. Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task. Component − This can be used to bring the modules together. Component − This can be used to bring the modules together. Templates − This is used to define the views of an Angular JS application. Templates − This is used to define the views of an Angular JS application. Metadata − This can be used to add more data to an Angular JS class. Metadata − This can be used to add more data to an Angular JS class. Service − This is used to create components which can be shared across the entire application. Service − This is used to create components which can be shared across the entire application. We will discuss all these components in detail in the subsequent chapters of this tutorial. The official site for Angular is https://angular.io/ The site has all information and documentation about Angular 2. To start working with Angular 2, you need to get the following key components installed. Npm − This is known as the node package manager that is used to work with the open source repositories. Angular JS as a framework has dependencies on other components. And npm can be used to download these dependencies and attach them to your project. Npm − This is known as the node package manager that is used to work with the open source repositories. Angular JS as a framework has dependencies on other components. And npm can be used to download these dependencies and attach them to your project. Git − This is the source code software that can be used to get the sample application from the github angular site. Git − This is the source code software that can be used to get the sample application from the github angular site. Editor − There are many editors that can be used for Angular JS development such as Visual Studio code and WebStorm. In our tutorial, we will use Visual Studio code which comes free of cost from Microsoft. Editor − There are many editors that can be used for Angular JS development such as Visual Studio code and WebStorm. In our tutorial, we will use Visual Studio code which comes free of cost from Microsoft. Let�s now look at the steps to get npm installed. The official site for npm is https://www.npmjs.com/ Step 1 − Go to the �get started with npm� section in the site. Step 2 − In the next screen, choose the installer to download, depending on the operating system. For the purpose of this exercise, download the Windows 64 bit version. Step 3 − Launch the installer. In the initial screen, click the Next button. Step 4 − In the next screen, Accept the license agreement and click the next button. Step 5 − In the next screen, choose the destination folder for the installation and click the Next button. Step 6 − Choose the components in the next screen and click the Next button. You can accept all the components for the default installation. Step 7 − In the next screen, click the Install button. Step 8 − Once the installation is complete, click the Finish button. Step 9 − To confirm the installation, in the command prompt you can issue the command npm version. You will get the version number of npm as shown in the following screenshot. Following are the features of Visual Studio Code − Light editor when compared to the actual version of Visual Studio. Light editor when compared to the actual version of Visual Studio. Can be used for coding languages such as Clojure, Java, Objective-C and many other languages. Can be used for coding languages such as Clojure, Java, Objective-C and many other languages. Built-in Git extension. Built-in Git extension. Built-in IntelliSense feature. Built-in IntelliSense feature. Many more extensions for development. Many more extensions for development. The official site for Visual Studio code is https://code.visualstudio.com/ Step 1 − After the download is complete, please follow the installation steps. In the initial screen, click the Next button. Step 2 − In the next screen, accept the license agreement and click the Next button. Step 3 − In the next screen, choose the destination location for the installation and click the next button. Step 4 − Choose the name of the program shortcut and click the Next button. Step 5 − Accept the default settings and click the Next button. Step 6 − Click the Install button in the next screen. Step 7 − In the final screen, click the Finish button to launch Visual Studio Code. Some of the key features of Git are − Easy branching and merging of code. Provision to use many techniques for the flow of code within Git. Git is very fast when compared with other SCM tools. Offers better data assurance. Free and open source. The official site for Git is https://git-scm.com/ Step 1 − After the download is complete, please follow the installation steps. In the initial screen, click the Next button. Step 2 − Choose the components which needs to be installed. You can accept the default components. Step 3 − In the next step, choose the program shortcut name and click the Next button. Step 4 − Accept the default SSH executable and click the Next button. Step 5 − Accept the default setting of �Checkout Windows style, commit Unix style endings� and click the Next button. Step 6 − Now, accept the default setting of the terminal emulator and click the Next button. Step 7 − Accept the default settings and click the Next button. Step 8 − You can skip the experimental options and click the Install button. Step 9 − In the final screen, click the Finish button to complete the installation. There are various ways to get started with your first Angular JS application. One way is to do everything from scratch which is the most difficult and not the preferred way. Due to the many dependencies, it becomes difficult to get this setup. One way is to do everything from scratch which is the most difficult and not the preferred way. Due to the many dependencies, it becomes difficult to get this setup. Another way is to use the quick start at Angular Github. This contains the necessary code to get started. This is normally what is opted by all developers and this is what we will show for the Hello World application. Another way is to use the quick start at Angular Github. This contains the necessary code to get started. This is normally what is opted by all developers and this is what we will show for the Hello World application. The final way is to use Angular CLI. We will discuss this in detail in a separate chapter. The final way is to use Angular CLI. We will discuss this in detail in a separate chapter. Following are the steps to get a sample application up and running via github. Step 1 − Go the github url - https://github.com/angular/quickstart Step 2 − Go to your command prompt, create a project directory. This can be an empty directory. In our example, we have created a directory called Project. Step 3 − Next, in the command prompt, go to this directory and issue the following command to clone the github repository on your local system. You can do this by issuing the following command − git clone https://github.com/angular/quickstart Demo This will create a sample Angular JS application on your local machine. Step 4 − Open the code in Visual Studio code. Step 5 − Go to the command prompt and in your project folder again and issue the following command − npm install This will install all the necessary packages which are required for the Angular JS application to work. Once done, you should see a tree structure with all dependencies installed. Step 6 − Go to the folder Demo → src → app → app.component.ts. Find the following lines of code − import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: `<h1>Hello {{name}}</h1>`, }) export class AppComponent { name = 'Angular'; } And replace the Angular keyword with World as shown below − import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: `<h1>Hello {{name}}</h1>`, }) export class AppComponent { name = 'World'; } There are other files that get created as part of the project creation for Angular 2 application. At the moment, you don�t need to bother about the other code files because these are all included as part of your Angular 2 application and don�t need to be changed for the Hello World application. We will be discussing these files in the subsequent chapters in detail. Note − Visual Studio Code will automatically compile all your files and create JavaScript files for all your typescript files. Step 7 − Now go to your command prompt and issue the command npm start. This will cause the Node package manager to start a lite web server and launch your Angular application. The Angular JS application will now launch in the browser and you will see �Hello World� in the browser as shown in the following screenshot. This topic focuses on the deployment of the above Hello world application. Since this is an Angular JS application, it can be deployed onto any platform. Your development can be on any platform. In this case, it will be on Windows using Visual Studio code. Now let�s look at two deployment options. Note that you can use any web server on any platform to host Angular JS applications. In this case, we will take the example of NGNIX which is a popular web server. Step 1 − Download the NGNIX web server from the following url http://nginx.org/en/download.html Step 2 − After extracting the downloaded zip file, run the nginx exe component which will make the web server run in the background. You will then be able to go to the home page in the url � http://localhost Step 3 − Go to Angular JS project folder in Windows explorer. Step 4 − Copy the Project → Demo → node-modules folder. Step 5 − Copy all the contents from the Project → Demo → src folder. Step 6 − Copy all contents to the nginx/html folder. Now go to the URL − http://localhost, you will actually see the hello world application as shown in the following screenshot. Now let�s see how to host the same hello world application onto an Ubuntu server. Step 1 − Issue the following commands on your Ubuntu server to install nginx. apt-get update The above command will ensure all the packages on the system are up to date. Once done, the system should be up to date. Step 2 − Now, install GIT on the Ubuntu server by issuing the following command. sudo apt-get install git Once done, GIT will be installed on the system. Step 3 − To check the git version, issue the following command. sudo git �version Step 4 − Install npm which is the node package manager on Ubuntu. To do this, issue the following command. sudo apt-get install npm Once done, npm will be installed on the system. Step 5 − To check the npm version, issue the following command. sudo npm -version Step 6 − Next, install nodejs. This can be done via the following command. sudo npm install nodejs Step 7 − To see the version of Node.js, just issue the following command. sudo nodejs �version Step 8 − Create a project folder and download the github starter project using the following git command. git clone https://github.com/angular/quickstart Demo This will download all the files on the local system. You can navigate through the folder to see the files have been successfully downloaded from github. Step 9 − Next issue the following command for npm. npm install This will install all the necessary packages which are required for Angular JS application to work. Once done, you will see all the dependencies installed on the system. Step 10 − Go to the folder Demo → src → app → app.component.ts. Use the vim editor if required. Find the following lines of code − import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: '<h1>Hello {{name}}</h1>'; }) export class AppComponent { name = 'Angular'; } And replace the Angular keyword with World as shown in the following code. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: '<h1>Hello {{name}}</h1>'; }) export class AppComponent { name = 'World'; } There are other files that get created as part of the project creation for Angular 2 application. At the moment, you don�t need to bother about the other code files because they are included as part of your Angular 2 application and don�t need to be changed for the Hello World application. We will be discussing these files in the subsequent chapters in detail. Step 11 − Next, install the lite server which can be used to run the Angular 2 application. You can do this by issuing the following command − sudo npm install �save-dev lite-server Once done, you will see the completion status. You don�t need to worry about the warnings. Step 12 − Create a symbolic link to the node folder via the following command. This helps in ensuring the node package manager can locate the nodejs installation. sudo ln -s /usr/bin/nodejs /usr/bin/node Step 13 − Now it�s time to start Angular 2 Application via the npm start command. This will first build the files and then launch the Angular app in the lite server which was installed in the earlier step. Issue the following command − sudo npm start Once done, you will be presented with the URL. If you go to the URL, you will now see the Angular 2 app loading the browser. Note − You can use any web server on any platform to host Angular JS applications. In this case, we will take the example of NGNIX which is a popular web server. Step 1 − Issue the following command on your Ubuntu server to install nginx as a web server. sudo apt-get update This command will ensure all the packages on the system are up to date. Once done, the system should be up to date. Step 2 − Now issue the following command to install nginx. apt-get install nginx Once done, nginx will be running in the background. Step 3 − Run the following command to confirm that the nginx services are running. ps �ef | grep nginx Now by default, the files for nginx are stored in /var/www/html folder. Hence, give the required permissions to copy your Hello World files to this location. Step 4 − Issue the following command. sudo chmod 777 /var/www/html Step 5 − Copy the files using any method to copy the project files to the /var/www/html folder. Now, if you browse to the URL − http://192.168.1.200/index.html you will find the Hello world Angular JS application. Modules are used in Angular JS to put logical boundaries in your application. Hence, instead of coding everything into one application, you can instead build everything into separate modules to separate the functionality of your application. Let�s inspect the code which gets added to the demo application. In Visual Studio code, go to the app.module.ts folder in your app folder. This is known as the root module class. The following code will be present in the app.module.ts file. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule ({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } Let�s go through each line of the code in detail. The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module. The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module. The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options. The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options. The BrowserModule is required by default for any web based angular application. The BrowserModule is required by default for any web based angular application. The bootstrap option tells Angular which Component to bootstrap in the application. The bootstrap option tells Angular which Component to bootstrap in the application. A module is made up of the following parts − Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application. Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application. Export array − This is used to export components, directives, and pipes which can then be used in other modules. Export array − This is used to export components, directives, and pipes which can then be used in other modules. Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules. Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules. The following screenshot shows the anatomy of an Angular 2 application. Each application consists of Components. Each component is a logical boundary of functionality for the application. You need to have layered services, which are used to share the functionality across components. Following is the anatomy of a Component. A component consists of − Class − This is like a C++ or Java class which consists of properties and methods. Class − This is like a C++ or Java class which consists of properties and methods. Metadata − This is used to decorate the class and extend the functionality of the class. Metadata − This is used to decorate the class and extend the functionality of the class. Template − This is used to define the HTML view which is displayed in the application. Template − This is used to define the HTML view which is displayed in the application. Following is an example of a component. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { appTitle: string = 'Welcome'; } Each application is made up of modules. Each Angular 2 application needs to have one Angular Root Module. Each Angular Root module can then have multiple components to separate the functionality. Following is an example of a root module. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule ({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } Each application is made up of feature modules where each module has a separate feature of the application. Each Angular feature module can then have multiple components to separate the functionality. Components are a logical piece of code for Angular JS application. A Component consists of the following − Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives. Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives. Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript. Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript. Metadata − This has the extra data defined for the Angular class. It is defined with a decorator. Metadata − This has the extra data defined for the Angular class. It is defined with a decorator. Let�s now go to the app.component.ts file and create our first Angular component. Let�s add the following code to the file and look at each aspect in detail. The class decorator. The class is defined in TypeScript. The class normally has the following syntax in TypeScript. class classname { Propertyname: PropertyType = Value } Classname − This is the name to be given to the class. Classname − This is the name to be given to the class. Propertyname − This is the name to be given to the property. Propertyname − This is the name to be given to the property. PropertyType − Since TypeScript is strongly typed, you need to give a type to the property. PropertyType − Since TypeScript is strongly typed, you need to give a type to the property. Value − This is the value to be given to the property. Value − This is the value to be given to the property. export class AppComponent { appTitle: string = 'Welcome'; } In the example, the following things need to be noted − We are defining a class called AppComponent. We are defining a class called AppComponent. The export keyword is used so that the component can be used in other modules in the Angular JS application. The export keyword is used so that the component can be used in other modules in the Angular JS application. appTitle is the name of the property. appTitle is the name of the property. The property is given the type of string. The property is given the type of string. The property is given a value of �Welcome�. The property is given a value of �Welcome�. This is the view which needs to be rendered in the application. Template: ' <HTML code> class properties ' HTML Code − This is the HTML code which needs to be rendered in the application. HTML Code − This is the HTML code which needs to be rendered in the application. Class properties − These are the properties of the class which can be referenced in the template. Class properties − These are the properties of the class which can be referenced in the template. template: ' <div> <h1>{{appTitle}}</h1> <div>To Tutorials Point</div> </div> ' In the example, the following things need to be noted − We are defining the HTML code which will be rendered in our application We are defining the HTML code which will be rendered in our application We are also referencing the appTitle property from our class. We are also referencing the appTitle property from our class. This is used to decorate Angular JS class with additional information. Let�s take a look at the completed code with our class, template, and metadata. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: ` <div> <h1>{{appTitle}}</h1> <div>To Tutorials Point</div> </div> `, }) export class AppComponent { appTitle: string = 'Welcome'; } In the above example, the following things need to be noted − We are using the import keyword to import the �Component� decorator from the angular/core module. We are using the import keyword to import the �Component� decorator from the angular/core module. We are then using the decorator to define a component. We are then using the decorator to define a component. The component has a selector called �my-app�. This is nothing but our custom html tag which can be used in our main html page. The component has a selector called �my-app�. This is nothing but our custom html tag which can be used in our main html page. Now, let�s go to our index.html file in our code. Let�s make sure that the body tag now contains a reference to our custom tag in the component. Thus in the above case, we need to make sure that the body tag contains the following code − <body> <my-app></my-app> </body> Now if we go to the browser and see the output, we will see that the output is rendered as it is in the component. In the chapter on Components, we have already seen an example of the following template. template: ' <div> <h1>{{appTitle}}</h1> <div>To Tutorials Point</div> </div> ' This is known as an inline template. There are other ways to define a template and that can be done via the templateURL command. The simplest way to use this in the component is as follows. templateURL: viewname.component.html viewname − This is the name of the app component module. viewname − This is the name of the app component module. After the viewname, the component needs to be added to the file name. Following are the steps to define an inline template. Step 1 − Create a file called app.component.html. This will contain the html code for the view. Step 2 − Add the following code in the above created file. <div>{{appTitle}} Tutorialspoint </div> This defines a simple div tag and references the appTitle property from the app.component class. Step 3 − In the app.component.ts file, add the following code. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { appTitle: string = 'Welcome'; } From the above code, the only change that can be noted is from the templateURL, which gives the link to the app.component.html file which is located in the app folder. Step 4 − Run the code in the browser, you will get the following output. From the output, it can be seen that the template file (app.component.html) file is being called accordingly. A directive is a custom HTML element that is used to extend the power of HTML. Angular 2 has the following directives that get called as part of the BrowserModule module. ngif ngFor If you view the app.module.ts file, you will see the following code and the BrowserModule module defined. By defining this module, you will have access to the 2 directives. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule ({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } Now let�s look at each directive in detail. The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code. *ngIf = 'expression' If the expression evaluates to true then the corresponding gets added, else the elements are not added. Let�s now take a look at an example of how we can use the *ngif directive. Step 1 − First add a property to the class named appStatus. This will be of type Boolean. Let�s keep this value as true. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { appTitle: string = 'Welcome'; appStatus: boolean = true; } Step 2 − Now in the app.component.html file, add the following code. <div *ngIf = 'appStatus'>{{appTitle}} Tutorialspoint </div> In the above code, we now have the *ngIf directive. In the directive we are evaluating the value of the appStatus property. Since the value of the property should evaluate to true, it means the div tag should be displayed in the browser. Once we add the above code, we will get the following output in the browser. The ngFor element is used to elements based on the condition of the For loop. *ngFor = 'let variable of variablelist' The variable is a temporary variable to display the values in the variablelist. Let�s now take a look at an example of how we can use the *ngFor directive. Step 1 − First add a property to the class named appList. This will be of the type which can be used to define any type of arrays. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { appTitle: string = 'Welcome'; appList: any[] = [ { "ID": "1", "Name" : "One" }, { "ID": "2", "Name" : "Two" } ]; } Hence, we are defining the appList as an array which has 2 elements. Each element has 2 sub properties as ID and Name. Step 2 − In the app.component.html, define the following code. <div *ngFor = 'let lst of appList'> <ul> <li>{{lst.ID}}</li> <li>{{lst.Name}}</li> </ul> </div> In the above code, we are now using the ngFor directive to iterate through the appList array. We then define a list where each list item is the ID and name parameter of the array. Once we add the above code, we will get the following output in the browser. Metadata is used to decorate a class so that it can configure the expected behavior of the class. Following are the different parts for metadata. Annotations − These are decorators at the class level. This is an array and an example having both the @Component and @Routes decorator. Following is a sample code, which is present in the app.component.ts file. @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) The component decorator is used to declare the class in the app.component.ts file as a component. Design:paramtypes − These are only used for the constructors and applied only to Typescript. Design:paramtypes − These are only used for the constructors and applied only to Typescript. propMetadata − This is the metadata which is applied to the properties of the class. propMetadata − This is the metadata which is applied to the properties of the class. Following is an example code. export class AppComponent { @Environment(�test�) appTitle: string = 'Welcome'; } Here, the @Environment is the metadata applied to the property appTitle and the value given is �test�. Parameters − This is set by the decorators at the constructor level. Following is an example code. export class AppComponent { constructor(@Environment(�test� private appTitle:string) { } } In the above example, metadata is applied to the parameters of the constructor. Two-way binding was a functionality in Angular JS, but has been removed from Angular 2.x onwards. But now, since the event of classes in Angular 2, we can bind to properties in AngularJS class. Suppose if you had a class with a class name, a property which had a type and value. export class className { property: propertytype = value; } You could then bind the property of an html tag to the property of the class. <html tag htmlproperty = 'property'> The value of the property would then be assigned to the htmlproperty of the html. Let�s look at an example of how we can achieve data binding. In our example, we will look at displaying images wherein the images source will come from the properties in our class. Following are the steps to achieve this. Step 1 − Download any 2 images. For this example, we will download some simple images shown below. Step 2 − Store these images in a folder called Images in the app directory. If the images folder is not present, please create it. Step 3 − Add the following content in app.component.ts as shown below. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { appTitle: string = 'Welcome'; appList: any[] = [ { "ID": "1", "url": 'app/Images/One.jpg' }, { "ID": "2", "url": 'app/Images/Two.jpg' } ]; } Step 4 − Add the following content in app.component.html as shown below. <div *ngFor = 'let lst of appList'> <ul> <li>{{lst.ID}}</li> <img [src] = 'lst.url'> </ul> </div> In the above app.component.html file, we are accessing the images from the properties in our class. The output of the above program should be like this − The basic CRUD operation we will look into this chapter is the reading of data from a web service using Angular 2. In this example, we are going to define a data source which is a simple json file of products. Next, we are going to define a service which will be used to read the data from the json file. And then next, we will use this service in our main app.component.ts file. Step 1 − First let�s define our product.json file in Visual Studio code. In the products.json file, enter the following text. This will be the data which will be taken from the Angular JS application. [{ "ProductID": 1, "ProductName": "ProductA" }, { "ProductID": 2, "ProductName": "ProductB" }] Step 2 − Define an interface which will be the class definition to store the information from our products.json file. Create a file called products.ts. Step 3 − Insert the following code in the file. export interface IProduct { ProductID: number; ProductName: string; } The above interface has the definition for the ProductID and ProductName as properties for the interface. Step 4 − In the app.module.ts file include the following code − import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HttpModule } from '@angular/http'; @NgModule ({ imports: [ BrowserModule,HttpModule], declarations: [ AppComponent], bootstrap: [ AppComponent ] }) export class AppModule { } Step 5 − Define a products.service.ts file in Visual Studio code Step 6 − Insert the following code in the file. import { Injectable } from '@angular/core'; import { Http , Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import { IProduct } from './product'; @Injectable() export class ProductService { private _producturl='app/products.json'; constructor(private _http: Http){} getproducts(): Observable<IProduct[]> { return this._http.get(this._producturl) .map((response: Response) => <IProduct[]> response.json()) .do(data => console.log(JSON.stringify(data))); } } Following points need to be noted about the above program. The import {Http, Response} from '@angular/http' statement is used to ensure that the http function can be used to get the data from the products.json file. The import {Http, Response} from '@angular/http' statement is used to ensure that the http function can be used to get the data from the products.json file. The following statements are used to make use of the Reactive framework which can be used to create an Observable variable. The Observable framework is used to detect any changes in the http response which can then be sent back to the main application. The following statements are used to make use of the Reactive framework which can be used to create an Observable variable. The Observable framework is used to detect any changes in the http response which can then be sent back to the main application. import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; The statement private _producturl = 'app/products.json' in the class is used to specify the location of our data source. It can also specify the location of web service if required. The statement private _producturl = 'app/products.json' in the class is used to specify the location of our data source. It can also specify the location of web service if required. Next, we define a variable of the type Http which will be used to get the response from the data source. Next, we define a variable of the type Http which will be used to get the response from the data source. Once we get the data from the data source, we then use the JSON.stringify(data) command to send the data to the console in the browser. Once we get the data from the data source, we then use the JSON.stringify(data) command to send the data to the console in the browser. Step 7 − Now in the app.component.ts file, place the following code. import { Component } from '@angular/core'; import { IProduct } from './product'; import { ProductService } from './products.service'; import { appService } from './app.service'; import { Http , Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Component ({ selector: 'my-app', template: '<div>Hello</div>', providers: [ProductService] }) export class AppComponent { iproducts: IProduct[]; constructor(private _product: ProductService) { } ngOnInit() : void { this._product.getproducts() .subscribe(iproducts => this.iproducts = iproducts); } } Here, the main thing in the code is the subscribe option which is used to listen to the Observable getproducts() function to listen for data from the data source. Now save all the codes and run the application using npm. Go to the browser, we will see the following output. In the Console, we will see the data being retrieved from products.json file. Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function. Let�s see the code required for error handling. This code can be added on top of the chapter for CRUD operations using http. In the product.service.ts file, enter the following code − import { Injectable } from '@angular/core'; import { Http , Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import { IProduct } from './product'; @Injectable() export class ProductService { private _producturl = 'app/products.json'; constructor(private _http: Http){} getproducts(): Observable<IProduct[]> { return this._http.get(this._producturl) .map((response: Response) => <IProduct[]> response.json()) .do(data => console.log(JSON.stringify(data))) .catch(this.handleError); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error()); } } The catch function contains a link to the Error Handler function. The catch function contains a link to the Error Handler function. In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue. In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue. Now, whenever you get an error it will be redirected to the error console of the browser. Routing helps in directing users to different pages based on the option they choose on the main page. Hence, based on the option they choose, the required Angular Component will be rendered to the user. Let�s see the necessary steps to see how we can implement routing in an Angular 2 application. Step 1 − Add the base reference tag in the index.html file. <!DOCTYPE html> <html> <head> <base href = "/"> <title>Angular QuickStart</title> <meta charset = "UTF-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <base href = "/"> <link rel = "stylesheet" href = "styles.css"> <!-- Polyfill(s) for older browsers --> <script src = "node_modules/core-js/client/shim.min.js"></script> <script src = "node_modules/zone.js/dist/zone.js"></script> <script src = "node_modules/systemjs/dist/system.src.js"></script> <script src = "systemjs.config.js"></script> <script> System.import('main.js').catch(function(err){ console.error(err); }); </script> </head> <body> <my-app></my-app> </body> </html> Step 2 − Create two routes for the application. For this, create 2 files called Inventory.component.ts and product.component.ts Step 3 − Place the following code in the product.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: 'Products', }) export class Appproduct { } Step 4 − Place the following code in the Inventory.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: 'Inventory', }) export class AppInventory { } Both of the components don�t do anything fancy, they just render the keywords based on the component. So for the Inventory component, it will display the Inventory keyword to the user. And for the products component, it will display the product keyword to the user. Step 5 − In the app.module.ts file, add the following code − import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { Appproduct } from './product.component'; import { AppInventory } from './Inventory.component'; import { RouterModule, Routes } from '@angular/router'; const appRoutes: Routes = [ { path: 'Product', component: Appproduct }, { path: 'Inventory', component: AppInventory }, ]; @NgModule ({ imports: [ BrowserModule, RouterModule.forRoot(appRoutes)], declarations: [ AppComponent,Appproduct,AppInventory], bootstrap: [ AppComponent ] }) export class AppModule { } The following points need to be noted about the above program − The appRoutes contain 2 routes, one is the Appproduct component and the other is the AppInventory component. The appRoutes contain 2 routes, one is the Appproduct component and the other is the AppInventory component. Ensure to declare both of the components. Ensure to declare both of the components. The RouterModule.forRoot ensures to add the routes to the application. The RouterModule.forRoot ensures to add the routes to the application. Step 6 − In the app.component.ts file, add the following code. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: ` <ul> <li><a [routerLink] = "['/Product']">Product</a></li> <li><a [routerLink] = "['/Inventory']">Inventory</a></li> </ul> <router-outlet></router-outlet>` }) export class AppComponent { } The following point needs to be noted about the above program − <router-outlet></router-outlet> is the placeholder to render the component based on which option the user chooses. <router-outlet></router-outlet> is the placeholder to render the component based on which option the user chooses. Now, save all the code and run the application using npm. Go to the browser, you will see the following output. Now if you click the Inventory link, you will get the following output. In Routing, one can also add an error route. This can happen if the user goes to a page which does not exist in the application. Let�s see how we can go about implementing this. Step 1 − Add a PageNotFound component as NotFound.component.ts as shown below − Step 2 − Add the following code to the new file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: 'Not Found', }) export class PageNotFoundComponent { } Step 3 − Add the following code to the app.module.ts file. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { Appproduct } from './product.component' import { AppInventory } from './Inventory.component' import { PageNotFoundComponent } from './NotFound.component' import { RouterModule, Routes } from '@angular/router'; const appRoutes: Routes = [ { path: 'Product', component: Appproduct }, { path: 'Inventory', component: AppInventory }, { path: '**', component: PageNotFoundComponent } ]; @NgModule ({ imports: [ BrowserModule, RouterModule.forRoot(appRoutes)], declarations: [ AppComponent,Appproduct,AppInventory,PageNotFoundComponent], bootstrap: [ AppComponent ] }) export class AppModule { } The following point needs to be noted about the above program − Now we have an extra route called path: '**', component: PageNotFoundComponent. Hence, ** is for any route which does not fit the default route. They will be directed to the PageNotFoundComponent component. Now we have an extra route called path: '**', component: PageNotFoundComponent. Hence, ** is for any route which does not fit the default route. They will be directed to the PageNotFoundComponent component. Now, save all the code and run the application using npm. Go to your browser, and you will see the following output. Now, when you go to any wrong link you will get the following output. In Angular 2, it is also possible to carry out manual navigation. Following are the steps. Step 1 − Add the following code to the Inventory.component.ts file. import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component ({ selector: 'my-app', template: 'Inventory <a class = "button" (click) = "onBack()">Back to Products</a>' }) export class AppInventory { constructor(private _router: Router){} onBack(): void { this._router.navigate(['/Product']); } } The following points need to be noted about the above program − Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page. Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page. In the onBack function, use the router.navigate to navigate to the required page. In the onBack function, use the router.navigate to navigate to the required page. Step 2 − Now, save all the code and run the application using npm. Go to the browser, you will see the following output. Step 3 − Click the Inventory link. Step 4 − Click the �Back to products� link, you will get the following output which takes you back to the Products page. Angular 2 can also design forms which can use two-way binding using the ngModel directive. Let�s see how we can achieve this. Step 1 − Create a model which is a products model. Create a file called products.ts file. Step 2 − Place the following code in the file. export class Product { constructor ( public productid: number, public productname: string ) { } } This is a simple class which has 2 properties, productid and productname. Step 3 − Create a product form component called product-form.component.ts component and add the following code − import { Component } from '@angular/core'; import { Product } from './products'; @Component ({ selector: 'product-form', templateUrl: './product-form.component.html' }) export class ProductFormComponent { model = new Product(1,'ProductA'); } The following points need to be noted about the above program. Create an object of the Product class and add values to the productid and productname. Create an object of the Product class and add values to the productid and productname. Use the templateUrl to specify the location of our product-form.component.html which will render the component. Use the templateUrl to specify the location of our product-form.component.html which will render the component. Step 4 − Create the actual form. Create a file called product-form.component.html and place the following code. <div class = "container"> <h1>Product Form</h1> <form> <div class = "form-group"> <label for = "productid">ID</label> <input type = "text" class = "form-control" id = "productid" required [(ngModel)] = "model.productid" name = "id"> </div> <div class = "form-group"> <label for = "name">Name</label> <input type = "text" class = "form-control" id = "name" [(ngModel)] = "model.productname" name = "name"> </div> </form> </div> The following point needs to be noted about the above program. The ngModel directive is used to bind the object of the product to the separate elements on the form. The ngModel directive is used to bind the object of the product to the separate elements on the form. Step 5 − Place the following code in the app.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: '<product-form></product-form>' }) export class AppComponent { } Step 6 − Place the below code in the app.module.ts file import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { FormsModule } from '@angular/forms'; import { ProductFormComponent } from './product-form.component'; @NgModule ({ imports: [ BrowserModule,FormsModule], declarations: [ AppComponent,ProductFormComponent], bootstrap: [ AppComponent ] }) export class AppModule { } Step 7 − Save all the code and run the application using npm. Go to your browser, you will see the following output. Command Line Interface (CLI) can be used to create our Angular JS application. It also helps in creating a unit and end-to-end tests for the application. The official site for Angular CLI is https://cli.angular.io/ If you click on the Get started option, you will be directed to the github repository for the CLI https://github.com/angular/angular-cli Let�s now look at some of the things we can do with Angular CLI. Note − Please ensure that Python is installed on the system. Python can be downloaded from the site https://www.python.org/ The first step is to install the CLI. We can do this with the following command − npm install �g angular-cli Now, create a new folder called angularCLI in any directory and issue the above command. Once done, the CLI will be installed. Angular JS project can be created using the following command. ng new Project_name Project_name − This is the name of the project which needs to be created. None. Let�s execute the following command to create a new project. ng new demo2 It will automatically create the files and start downloading the necessary npm packages. Now in Visual Studio code, we can open the newly created project. To run the project, you need to issue the following command − ng server The default port number for the running application is 4200. You can browse to the port and see the application running. Dependency injection is the ability to add the functionality of components at runtime. Let�s take a look at an example and the steps used to implement dependency injection. Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module. @Injectable() export class classname { } Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator. @Component ({ providers : [classname] }) Let�s look at an example on how to achieve this. Step 1 − Create a ts file for the service called app.service.ts. Step 2 − Place the following code in the file created above. import { Injectable } from '@angular/core'; @Injectable() export class appService { getApp(): string { return "Hello world"; } } The following points need to be noted about the above program. The Injectable decorator is imported from the angular/core module. The Injectable decorator is imported from the angular/core module. We are creating a class called appService that is decorated with the Injectable decorator. We are creating a class called appService that is decorated with the Injectable decorator. We are creating a simple function called getApp which returns a simple string called �Hello world�. We are creating a simple function called getApp which returns a simple string called �Hello world�. Step 3 − In the app.component.ts file place the following code. import { Component } from '@angular/core'; import { appService } from './app.service'; @Component({ selector: 'my-app', template: '<div>{{value}}</div>', providers: [appService] }) export class AppComponent { value: string = ""; constructor(private _appService: appService) { } ngOnInit(): void { this.value = this._appService.getApp(); } } The following points need to be noted about the above program. First, we are importing our appService module in the appComponent module. First, we are importing our appService module in the appComponent module. Then, we are registering the service as a provider in this module. Then, we are registering the service as a provider in this module. In the constructor, we define a variable called _appService of the type appService so that it can be called anywhere in the appComponent module. In the constructor, we define a variable called _appService of the type appService so that it can be called anywhere in the appComponent module. As an example, in the ngOnInit lifecyclehook, we called the getApp function of the service and assigned the output to the value property of the AppComponent class. As an example, in the ngOnInit lifecyclehook, we called the getApp function of the service and assigned the output to the value property of the AppComponent class. Save all the code changes and refresh the browser, you will get the following output. In this chapter, we will look at the other configuration files which are part of Angular 2 project. This file is used to give the options about TypeScript used for the Angular JS project. { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": [ "es2015", "dom" ], "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true } } Following are some key points to note about the above code. The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript. The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript. The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true. The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true. The "emitDecoratorMetadata": true and "experimentalDecorators": true is required for Angular JS decorators. If not in place, Angular JS application will not compile. The "emitDecoratorMetadata": true and "experimentalDecorators": true is required for Angular JS decorators. If not in place, Angular JS application will not compile. This file contains information about Angular 2 project. Following are the typical settings in the file. { "name": "angular-quickstart", "version": "1.0.0", "description": "QuickStart package.json from the documentation, supplemented with testing support", "scripts": { "build": "tsc -p src/", "build:watch": "tsc -p src/ -w", "build:e2e": "tsc -p e2e/", "serve": "lite-server -c=bs-config.json", "serve:e2e": "lite-server -c=bs-config.e2e.json", "prestart": "npm run build", "start": "concurrently \"npm run build:watch\" \"npm run serve\"", "pree2e": "npm run build:e2e", "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --killothers --success first", "preprotractor": "webdriver-manager update", "protractor": "protractor protractor.config.js", "pretest": "npm run build", "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"", "pretest:once": "npm run build", "test:once": "karma start karma.conf.js --single-run", "lint": "tslint ./src/**/*.ts -t verbose" }, "keywords": [], "author": "", "license": "MIT", "dependencies": { "@angular/common": "~2.4.0", "@angular/compiler": "~2.4.0", "@angular/core": "~2.4.0", "@angular/forms": "~2.4.0", "@angular/http": "~2.4.0", "@angular/platform-browser": "~2.4.0", "@angular/platform-browser-dynamic": "~2.4.0", "@angular/router": "~3.4.0", "angular-in-memory-web-api": "~0.2.4", "systemjs": "0.19.40", "core-js": "^2.4.1", "rxjs": "5.0.1", "zone.js": "^0.7.4" }, "devDependencies": { "concurrently": "^3.2.0", "lite-server": "^2.2.2", "typescript": "~2.0.10", "canonical-path": "0.0.2", "tslint": "^3.15.1", "lodash": "^4.16.4", "jasmine-core": "~2.4.1", "karma": "^1.3.0", "karma-chrome-launcher": "^2.0.0", "karma-cli": "^1.0.1", "karma-jasmine": "^1.0.2", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~4.0.14", "rimraf": "^2.5.4", "@types/node": "^6.0.46", "@types/jasmine": "2.5.36" }, "repository": {} } Some key points to note about the above code − There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application. There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application. The "build:watch": "tsc -p src/ -w" command is used to compile the typescript in the background by looking for changes in the typescript files. The "build:watch": "tsc -p src/ -w" command is used to compile the typescript in the background by looking for changes in the typescript files. This file contains the system files required for Angular JS application. This loads all the necessary script files without the need to add a script tag to the html pages. The typical files will have the following code. /** * System configuration for Angular samples * Adjust as necessary for your application needs. */ (function (global) { System.config ({ paths: { // paths serve as alias 'npm:': 'node_modules/' }, // map tells the System loader where to look for things map: { // our app is within the app folder app: 'app', // angular bundles '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platformbrowser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browserdynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', // other libraries 'rxjs': 'npm:rxjs', 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/inmemory-web-api.umd.js' }, // packages tells the System loader how to load when no filename and/or no extension packages: { app: { defaultExtension: 'js' }, rxjs: { defaultExtension: 'js' } } }); })(this); Some key points to note about the above code − 'npm:': 'node_modules/' tells the location in our project where all the npm modules are located. 'npm:': 'node_modules/' tells the location in our project where all the npm modules are located. The mapping of app: 'app' tells the folder where all our applications files are loaded. The mapping of app: 'app' tells the folder where all our applications files are loaded. Angular 2 allows you to work with any third party controls. Once you decide on the control to implement, you need to perform the following steps − Step 1 − Install the component using the npm command. For example, we will install the ng2-pagination third party control via the following command. npm install ng2-pagination --save Once done, you will see that the component is successfully installed. Step 2 − Include the component in the app.module.ts file. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import {Ng2PaginationModule} from 'ng2-pagination'; @NgModule ({ imports: [ BrowserModule,Ng2PaginationModule], declarations: [ AppComponent], bootstrap: [ AppComponent ] }) export class AppModule { } Step 3 − Finally, implement the component in your app.component.ts file. import { Component } from '@angular/core'; import {PaginatePipe, PaginationService} from 'ng2-pagination'; @Component ({ selector: 'my-app', template: ' <ul> <li *ngFor = "let item of collection | paginate: { itemsPerPage: 5, currentPage: p }"> ... </li> </ul> <pagination-controls (pageChange) = "p = $event"></pagination-controls> ' }) export class AppComponent { } Step 4 − Save all the code changes and refresh the browser, you will get the following output. In the above picture, you can see that the images have been stored as One.jpg and two.jpg in the Images folder. Step 5 − Change the code of the app.component.ts file to the following. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { appTitle: string = 'Welcome'; appList: any[] = [{ "ID": "1", "Name": "One", "url": 'app/Images/One.jpg' }, { "ID": "2", "Name": "Two", "url": 'app/Images/two.jpg' } ]; } Following points need to be noted about the above code. We are defining an array called appList which is of the type any. This is so that it can store any type of element. We are defining an array called appList which is of the type any. This is so that it can store any type of element. We are defining 2 elements. Each element has 3 properties, ID, Name and url. We are defining 2 elements. Each element has 3 properties, ID, Name and url. The URL for each element is the relative path to the 2 images. The URL for each element is the relative path to the 2 images. Step 6 − Make the following changes to the app/app.component.html file which is your template file. <div *ngFor = 'let lst of appList'> <ul> <li>{{lst.ID}}</li> <li>{{lst.Name}}</li> <img [src] = 'lst.url'> </ul> </div> Following points need to be noted about the above program − The ngFor directive is used to iterate through all the elements of the appList property. The ngFor directive is used to iterate through all the elements of the appList property. For each property, it is using the list element to display an image. For each property, it is using the list element to display an image. The src property of the img tag is then bounded to the url property of appList in our class. The src property of the img tag is then bounded to the url property of appList in our class. Step 7 − Save all the code changes and refresh the browser, you will get the following output. From the output, you can clearly see that the images have been picked up and shown in the output. In Angular JS, it very easy to display the value of the properties of the class in the HTML form. Let�s take an example and understand more about Data Display. In our example, we will look at displaying the values of the various properties in our class in an HTML page. Step 1 − Change the code of the app.component.ts file to the following. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { TutorialName: string = 'Angular JS2'; appList: string[] = ["Binding", "Display", "Services"]; } Following points need to be noted about the above code. We are defining an array called appList which of the type string. We are defining an array called appList which of the type string. We are defining 3 string elements as part of the array which is Binding, Display, and Services. We are defining 3 string elements as part of the array which is Binding, Display, and Services. We have also defined a property called TutorialName which has a value of Angular 2. We have also defined a property called TutorialName which has a value of Angular 2. Step 2 − Make the following changes to the app/app.component.html file which is your template file. <div> The name of this Tutorial is {{TutorialName}}<br> The first Topic is {{appList[0]}}<br> The second Topic is {{appList[1]}}<br> The third Topic is {{appList[2]}}<br> </div> Following points need to be noted about the above code. We are referencing the TutorialName property to tell �what is the name of the tutorial in our HTML page�. We are referencing the TutorialName property to tell �what is the name of the tutorial in our HTML page�. We are using the index value for the array to display each of the 3 topics in our array. We are using the index value for the array to display each of the 3 topics in our array. Step 3 − Save all the code changes and refresh the browser, you will get the below output. From the output, you can clearly see that the data is displayed as per the values of the properties in the class. Another simple example, which is binding on the fly is the use of the input html tag. It just displays the data as the data is being typed in the html tag. Make the following changes to the app/app.component.html file which is your template file. <div> <input [value] = "name" (input) = "name = $event.target.value"> {{name}} </div> Following points need to be noted about the above code. [value] = �username� − This is used to bind the expression username to the input element�s value property. [value] = �username� − This is used to bind the expression username to the input element�s value property. (input) = �expression� − This a declarative way of binding an expression to the input element�s input event. (input) = �expression� − This a declarative way of binding an expression to the input element�s input event. username = $event.target.value − The expression that gets executed when the input event is fired. username = $event.target.value − The expression that gets executed when the input event is fired. $event − An expression exposed in event bindings by Angular, which has the value of the event�s payload. $event − An expression exposed in event bindings by Angular, which has the value of the event�s payload. When you save all the code changes and refresh the browser, you will get the following output. Now, type something in the Input box such as �Tutorialspoint�. The output will change accordingly. In Angular 2, events such as button click or any other sort of events can also be handled very easily. The events get triggered from the html page and are sent across to Angular JS class for further processing. Let�s look at an example of how we can achieve event handling. In our example, we will look at displaying a click button and a status property. Initially, the status property will be true. When the button is clicked, the status property will then become false. Step 1 − Change the code of the app.component.ts file to the following. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { Status: boolean = true; clicked(event) { this.Status = false; } } Following points need to be noted about the above code. We are defining a variable called status of the type Boolean which is initially true. We are defining a variable called status of the type Boolean which is initially true. Next, we are defining the clicked function which will be called whenever our button is clicked on our html page. In the function, we change the value of the Status property from true to false. Next, we are defining the clicked function which will be called whenever our button is clicked on our html page. In the function, we change the value of the Status property from true to false. Step 2 − Make the following changes to the app/app.component.html file, which is the template file. <div> {{Status}} <button (click) = "clicked()">Click</button> </div> Following points need to be noted about the above code. We are first just displaying the value of the Status property of our class. We are first just displaying the value of the Status property of our class. Then are defining the button html tag with the value of Click. We then ensure that the click event of the button gets triggered to the clicked event in our class. Then are defining the button html tag with the value of Click. We then ensure that the click event of the button gets triggered to the clicked event in our class. Step 3 − Save all the code changes and refresh the browser, you will get the following output. Step 4 − Click the Click button, you will get the following output. Angular 2 has a lot of filters and pipes that can be used to transform data. This is used to convert the input to all lowercase. Propertyvalue | lowercase None The property value will be converted to lowercase. First ensure the following code is present in the app.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { TutorialName: string = 'Angular JS2'; appList: string[] = ["Binding", "Display", "Services"]; } Next, ensure the following code is present in the app/app.component.html file. <div> The name of this Tutorial is {{TutorialName}}<br> The first Topic is {{appList[0] | lowercase}}<br> The second Topic is {{appList[1] | lowercase}}<br> The third Topic is {{appList[2]| lowercase}}<br> </div> Once you save all the code changes and refresh the browser, you will get the following output. This is used to convert the input to all uppercase. Propertyvalue | uppercase None. The property value will be converted to uppercase. First ensure the following code is present in the app.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { TutorialName: string = 'Angular JS2'; appList: string[] = ["Binding", "Display", "Services"]; } Next, ensure the following code is present in the app/app.component.html file. <div> The name of this Tutorial is {{TutorialName}}<br> The first Topic is {{appList[0] | uppercase }}<br> The second Topic is {{appList[1] | uppercase }}<br> The third Topic is {{appList[2]| uppercase }}<br> </div> Once you save all the code changes and refresh the browser, you will get the following output. This is used to slice a piece of data from the input string. Propertyvalue | slice:start:end start − This is the starting position from where the slice should start. start − This is the starting position from where the slice should start. end − This is the starting position from where the slice should end. end − This is the starting position from where the slice should end. The property value will be sliced based on the start and end positions. First ensure the following code is present in the app.component.ts file import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { TutorialName: string = 'Angular JS2'; appList: string[] = ["Binding", "Display", "Services"]; } Next, ensure the following code is present in the app/app.component.html file. <div> The name of this Tutorial is {{TutorialName}}<br> The first Topic is {{appList[0] | slice:1:2}}<br> The second Topic is {{appList[1] | slice:1:3}}<br> The third Topic is {{appList[2]| slice:2:3}}<br> </div> Once you save all the code changes and refresh the browser, you will get the following output. This is used to convert the input string to date format. Propertyvalue | date:�dateformat� dateformat − This is the date format the input string should be converted to. The property value will be converted to date format. First ensure the following code is present in the app.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { newdate = new Date(2016, 3, 15); } Next, ensure the following code is present in the app/app.component.html file. <div> The date of this Tutorial is {{newdate | date:"MM/dd/yy"}}<br> </div> Once you save all the code changes and refresh the browser, you will get the following output. This is used to convert the input string to currency format. Propertyvalue | currency None. The property value will be converted to currency format. First ensure the following code is present in the app.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { newValue: number = 123; } Next, ensure the following code is present in the app/app.component.html file. <div> The currency of this Tutorial is {{newValue | currency}}<br> </div> Once you save all the code changes and refresh the browser, you will get the following output. This is used to convert the input string to percentage format. Propertyvalue | percent None The property value will be converted to percentage format. First ensure the following code is present in the app.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { newValue: number = 30; } Next, ensure the following code is present in the app/app.component.html file. <div> The percentage is {{newValue | percent}}<br> </div> Once you save all the code changes and refresh the browser, you will get the following output. There is another variation of the percent pipe as follows. Propertyvalue | percent: �{minIntegerDigits}.{minFractionDigits}{maxFractionDigits}� minIntegerDigits − This is the minimum number of Integer digits. minIntegerDigits − This is the minimum number of Integer digits. minFractionDigits − This is the minimum number of fraction digits. minFractionDigits − This is the minimum number of fraction digits. maxFractionDigits − This is the maximum number of fraction digits. maxFractionDigits − This is the maximum number of fraction digits. The property value will be converted to percentage format First ensure the following code is present in the app.component.ts file. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', templateUrl: 'app/app.component.html' }) export class AppComponent { newValue: number = 0.3; } Next, ensure the following code is present in the app/app.component.html file. <div> The percentage is {{newValue | percent:'2.2-5'}}<br> </div> Once you save all the code changes and refresh the browser, you will get the following output. Angular 2 also has the facility to create custom pipes. The general way to define a custom pipe is as follows. import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'Pipename'}) export class Pipeclass implements PipeTransform { transform(parameters): returntype { } } Where, 'Pipename' − This is the name of the pipe. 'Pipename' − This is the name of the pipe. Pipeclass − This is name of the class assigned to the custom pipe. Pipeclass − This is name of the class assigned to the custom pipe. Transform − This is the function to work with the pipe. Transform − This is the function to work with the pipe. Parameters − This are the parameters which are passed to the pipe. Parameters − This are the parameters which are passed to the pipe. Returntype − This is the return type of the pipe. Returntype − This is the return type of the pipe. Let�s create a custom pipe that multiplies 2 numbers. We will then use that pipe in our component class. Step 1 − First, create a file called multiplier.pipe.ts. Step 2 − Place the following code in the above created file. import { Pipe, PipeTransform } from '@angular/core'; @Pipe ({ name: 'Multiplier' }) export class MultiplierPipe implements PipeTransform { transform(value: number, multiply: string): number { let mul = parseFloat(multiply); return mul * value } } Following points need to be noted about the above code. We are first importing the Pipe and PipeTransform modules. We are first importing the Pipe and PipeTransform modules. Then, we are creating a Pipe with the name 'Multiplier'. Then, we are creating a Pipe with the name 'Multiplier'. Creating a class called MultiplierPipe that implements the PipeTransform module. Creating a class called MultiplierPipe that implements the PipeTransform module. The transform function will then take in the value and multiple parameter and output the multiplication of both numbers. The transform function will then take in the value and multiple parameter and output the multiplication of both numbers. Step 3 − In the app.component.ts file, place the following code. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: '<p>Multiplier: {{2 | Multiplier: 10}}</p>' }) export class AppComponent { } Note − In our template, we use our new custom pipe. Step 4 − Ensure the following code is placed in the app.module.ts file. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { MultiplierPipe } from './multiplier.pipe' @NgModule ({ imports: [BrowserModule], declarations: [AppComponent, MultiplierPipe], bootstrap: [AppComponent] }) export class AppModule {} Following things need to be noted about the above code. We need to ensure to include our MultiplierPipe module. We need to ensure to include our MultiplierPipe module. We also need to ensure it is included in the declarations section. We also need to ensure it is included in the declarations section. Once you save all the code changes and refresh the browser, you will get the following output. In Angular 2, you can make the use of DOM element structure of HTML to change the values of the elements at run time. Let�s look at some in detail. In the app.component.ts file place the following code. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: ' <div> <input [value] = "name" (input) = "name = $event.target.value"> {{name}} </div> ' }) export class AppComponent { } Following things need to be noted about the above code. [value] = �username� − This is used to bind the expression username to the input element�s value property. [value] = �username� − This is used to bind the expression username to the input element�s value property. (input) = �expression� − This a declarative way of binding an expression to the input element�s input event. (input) = �expression� − This a declarative way of binding an expression to the input element�s input event. username = $event.target.value − The expression that gets executed when the input event is fired. username = $event.target.value − The expression that gets executed when the input event is fired. $event − Is an expression exposed in event bindings by Angular, which has the value of the event�s payload. $event − Is an expression exposed in event bindings by Angular, which has the value of the event�s payload. Once you save all the code changes and refresh the browser, you will get the following output. You can now type anything and the same input will reflect in the text next to the Input control. In the app.component.ts file place the following code. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: '<button (click) = "onClickMe()"> Click Me </button> {{clickMessage}}' }) export class AppComponent { clickMessage = 'Hello'; onClickMe() { this.clickMessage = 'This tutorial!'; } } Once you save all the code changes and refresh the browser, you will get the following output. When you hit the Click Me button, you will get the following output. Angular 2 application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application. The following diagram shows the entire processes in the lifecycle of the Angular 2 application. Following is a description of each lifecycle hook. ngOnChanges − When the value of a data bound property changes, then this method is called. ngOnChanges − When the value of a data bound property changes, then this method is called. ngOnInit − This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens. ngOnInit − This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens. ngDoCheck − This is for the detection and to act on changes that Angular can't or won't detect on its own. ngDoCheck − This is for the detection and to act on changes that Angular can't or won't detect on its own. ngAfterContentInit − This is called in response after Angular projects external content into the component's view. ngAfterContentInit − This is called in response after Angular projects external content into the component's view. ngAfterContentChecked − This is called in response after Angular checks the content projected into the component. ngAfterContentChecked − This is called in response after Angular checks the content projected into the component. ngAfterViewInit − This is called in response after Angular initializes the component's views and child views. ngAfterViewInit − This is called in response after Angular initializes the component's views and child views. ngAfterViewChecked − This is called in response after Angular checks the component's views and child views. ngAfterViewChecked − This is called in response after Angular checks the component's views and child views. ngOnDestroy − This is the cleanup phase just before Angular destroys the directive/component. ngOnDestroy − This is the cleanup phase just before Angular destroys the directive/component. Following is an example of implementing one lifecycle hook. In the app.component.ts file, place the following code. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: '<div> {{values}} </div> ' }) export class AppComponent { values = ''; ngOnInit() { this.values = "Hello"; } } In the above program, we are calling the ngOnInit lifecycle hook to specifically mention that the value of the this.values parameter should be set to �Hello�. Once you save all the code changes and refresh the browser, you will get the following output. In Angular JS, it is possible to nest containers inside each other. The outside container is known as the parent container and the inner one is known as the child container. Let�s look at an example on how to achieve this. Following are the steps. Step 1 − Create a ts file for the child container called child.component.ts. Step 2 − In the file created in the above step, place the following code. import { Component } from '@angular/core'; @Component ({ selector: 'child-app', template: '<div> {{values}} </div> ' }) export class ChildComponent { values = ''; ngOnInit() { this.values = "Hello"; } } The above code sets the value of the parameter this.values to �Hello�. Step 3 − In the app.component.ts file, place the following code. import { Component } from '@angular/core'; import { ChildComponent } from './child.component'; @Component ({ selector: 'my-app', template: '<child-app></child-app> ' }) export class AppComponent { } In the above code, notice that we are now calling the import statement to import the child.component module. Also we are calling the <child-app> selector from the child component to our main component. Step 4 − Next, we need to ensure the child component is also included in the app.module.ts file. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { MultiplierPipe } from './multiplier.pipe' import { ChildComponent } from './child.component'; @NgModule ({ imports: [BrowserModule], declarations: [AppComponent, MultiplierPipe, ChildComponent], bootstrap: [AppComponent] }) export class AppModule {} Once you save all the code changes and refresh the browser, you will get the following output. A service is used when a common functionality needs to be provided to various modules. For example, we could have a database functionality that could be reused among various modules. And hence you could create a service that could have the database functionality. The following key steps need to be carried out when creating a service. Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module. @Injectable() export class classname { } Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator. @Component ({ providers : [classname] }) Let�s look at an example on how to achieve this. Following are the steps involved. Step 1 − Create a ts file for the service called app.service.ts. Step 2 − Place the following code in the file created above. import { Injectable } from '@angular/core'; @Injectable() export class appService { getApp(): string { return "Hello world"; } } Following points need to be noted about the above program. The Injectable decorator is imported from the angular/core module. The Injectable decorator is imported from the angular/core module. We are creating a class called appService that is decorated with the Injectable decorator. We are creating a class called appService that is decorated with the Injectable decorator. We are creating a simple function called getApp, which returns a simple string called �Hello world�. We are creating a simple function called getApp, which returns a simple string called �Hello world�. Step 3 − In the app.component.ts file, place the following code. import { Component } from '@angular/core'; import { appService } from './app.service'; @Component ({ selector: 'demo-app', template: '<div>{{value}}</div>', providers: [appService] }) export class AppComponent { value: string = ""; constructor(private _appService: appService) { } ngOnInit(): void { this.value = this._appService.getApp(); } } Following points need to be noted about the above program. First, we import our appService module in the appComponent module. First, we import our appService module in the appComponent module. Then, we register the service as a provider in this module. Then, we register the service as a provider in this module. In the constructor, we define a variable called _appService of the type appService so that it can be called anywhere in the appComponent module. In the constructor, we define a variable called _appService of the type appService so that it can be called anywhere in the appComponent module. As an example, in the ngOnInit lifecyclehook, we called the getApp function of the service and assign the output to the value property of the AppComponent class. As an example, in the ngOnInit lifecyclehook, we called the getApp function of the service and assign the output to the value property of the AppComponent class. Once you save all the code changes and refresh the browser, you will get the following output. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2695, "s": 2297, "text": "Angular JS is an open source framework built over JavaScript. It was built by the developers at Google. This framework was used to overcome obstacles encountered while working with Single Page applications. Also, testing was considered as a key aspect while building the framework. It was ensured that the framework could be easily tested. The initial release of the framework was in October 2010." }, { "code": null, "e": 2741, "s": 2695, "text": "Following are the key features of Angular 2 −" }, { "code": null, "e": 3014, "s": 2741, "text": "Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time." }, { "code": null, "e": 3287, "s": 3014, "text": "Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time." }, { "code": null, "e": 3418, "s": 3287, "text": "TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft." }, { "code": null, "e": 3549, "s": 3418, "text": "TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft." }, { "code": null, "e": 3813, "s": 3549, "text": "Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications." }, { "code": null, "e": 4077, "s": 3813, "text": "Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications." }, { "code": null, "e": 4199, "s": 4077, "text": "In addition, Angular 2 has better event-handling capabilities, powerful templates, and better support for mobile devices." }, { "code": null, "e": 4240, "s": 4199, "text": "Angular 2 has the following components −" }, { "code": null, "e": 4387, "s": 4240, "text": "Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task." }, { "code": null, "e": 4534, "s": 4387, "text": "Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task." }, { "code": null, "e": 4594, "s": 4534, "text": "Component − This can be used to bring the modules together." }, { "code": null, "e": 4654, "s": 4594, "text": "Component − This can be used to bring the modules together." }, { "code": null, "e": 4729, "s": 4654, "text": "Templates − This is used to define the views of an Angular JS application." }, { "code": null, "e": 4804, "s": 4729, "text": "Templates − This is used to define the views of an Angular JS application." }, { "code": null, "e": 4873, "s": 4804, "text": "Metadata − This can be used to add more data to an Angular JS class." }, { "code": null, "e": 4942, "s": 4873, "text": "Metadata − This can be used to add more data to an Angular JS class." }, { "code": null, "e": 5037, "s": 4942, "text": "Service − This is used to create components which can be shared across the entire application." }, { "code": null, "e": 5132, "s": 5037, "text": "Service − This is used to create components which can be shared across the entire application." }, { "code": null, "e": 5224, "s": 5132, "text": "We will discuss all these components in detail in the subsequent chapters of this tutorial." }, { "code": null, "e": 5341, "s": 5224, "text": "The official site for Angular is https://angular.io/ The site has all information and documentation about Angular 2." }, { "code": null, "e": 5430, "s": 5341, "text": "To start working with Angular 2, you need to get the following key components installed." }, { "code": null, "e": 5682, "s": 5430, "text": "Npm − This is known as the node package manager that is used to work with the open source repositories. Angular JS as a framework has dependencies on other components. And npm can be used to download these dependencies and attach them to your project." }, { "code": null, "e": 5934, "s": 5682, "text": "Npm − This is known as the node package manager that is used to work with the open source repositories. Angular JS as a framework has dependencies on other components. And npm can be used to download these dependencies and attach them to your project." }, { "code": null, "e": 6050, "s": 5934, "text": "Git − This is the source code software that can be used to get the sample application from the github angular site." }, { "code": null, "e": 6166, "s": 6050, "text": "Git − This is the source code software that can be used to get the sample application from the github angular site." }, { "code": null, "e": 6372, "s": 6166, "text": "Editor − There are many editors that can be used for Angular JS development such as Visual Studio code and WebStorm. In our tutorial, we will use Visual Studio code which comes free of cost from Microsoft." }, { "code": null, "e": 6578, "s": 6372, "text": "Editor − There are many editors that can be used for Angular JS development such as Visual Studio code and WebStorm. In our tutorial, we will use Visual Studio code which comes free of cost from Microsoft." }, { "code": null, "e": 6680, "s": 6578, "text": "Let�s now look at the steps to get npm installed. The official site for npm is https://www.npmjs.com/" }, { "code": null, "e": 6743, "s": 6680, "text": "Step 1 − Go to the �get started with npm� section in the site." }, { "code": null, "e": 6912, "s": 6743, "text": "Step 2 − In the next screen, choose the installer to download, depending on the operating system. For the purpose of this exercise, download the Windows 64 bit version." }, { "code": null, "e": 6989, "s": 6912, "text": "Step 3 − Launch the installer. In the initial screen, click the Next button." }, { "code": null, "e": 7074, "s": 6989, "text": "Step 4 − In the next screen, Accept the license agreement and click the next button." }, { "code": null, "e": 7181, "s": 7074, "text": "Step 5 − In the next screen, choose the destination folder for the installation and click the Next button." }, { "code": null, "e": 7322, "s": 7181, "text": "Step 6 − Choose the components in the next screen and click the Next button. You can accept all the components for the default installation." }, { "code": null, "e": 7377, "s": 7322, "text": "Step 7 − In the next screen, click the Install button." }, { "code": null, "e": 7446, "s": 7377, "text": "Step 8 − Once the installation is complete, click the Finish button." }, { "code": null, "e": 7622, "s": 7446, "text": "Step 9 − To confirm the installation, in the command prompt you can issue the command npm version. You will get the version number of npm as shown in the following screenshot." }, { "code": null, "e": 7673, "s": 7622, "text": "Following are the features of Visual Studio Code −" }, { "code": null, "e": 7740, "s": 7673, "text": "Light editor when compared to the actual version of Visual Studio." }, { "code": null, "e": 7807, "s": 7740, "text": "Light editor when compared to the actual version of Visual Studio." }, { "code": null, "e": 7901, "s": 7807, "text": "Can be used for coding languages such as Clojure, Java, Objective-C and many other languages." }, { "code": null, "e": 7995, "s": 7901, "text": "Can be used for coding languages such as Clojure, Java, Objective-C and many other languages." }, { "code": null, "e": 8019, "s": 7995, "text": "Built-in Git extension." }, { "code": null, "e": 8043, "s": 8019, "text": "Built-in Git extension." }, { "code": null, "e": 8074, "s": 8043, "text": "Built-in IntelliSense feature." }, { "code": null, "e": 8105, "s": 8074, "text": "Built-in IntelliSense feature." }, { "code": null, "e": 8143, "s": 8105, "text": "Many more extensions for development." }, { "code": null, "e": 8181, "s": 8143, "text": "Many more extensions for development." }, { "code": null, "e": 8256, "s": 8181, "text": "The official site for Visual Studio code is https://code.visualstudio.com/" }, { "code": null, "e": 8381, "s": 8256, "text": "Step 1 − After the download is complete, please follow the installation steps. In the initial screen, click the Next button." }, { "code": null, "e": 8466, "s": 8381, "text": "Step 2 − In the next screen, accept the license agreement and click the Next button." }, { "code": null, "e": 8575, "s": 8466, "text": "Step 3 − In the next screen, choose the destination location for the installation and click the next button." }, { "code": null, "e": 8651, "s": 8575, "text": "Step 4 − Choose the name of the program shortcut and click the Next button." }, { "code": null, "e": 8715, "s": 8651, "text": "Step 5 − Accept the default settings and click the Next button." }, { "code": null, "e": 8769, "s": 8715, "text": "Step 6 − Click the Install button in the next screen." }, { "code": null, "e": 8853, "s": 8769, "text": "Step 7 − In the final screen, click the Finish button to launch Visual Studio Code." }, { "code": null, "e": 8891, "s": 8853, "text": "Some of the key features of Git are −" }, { "code": null, "e": 8927, "s": 8891, "text": "Easy branching and merging of code." }, { "code": null, "e": 8993, "s": 8927, "text": "Provision to use many techniques for the flow of code within Git." }, { "code": null, "e": 9046, "s": 8993, "text": "Git is very fast when compared with other SCM tools." }, { "code": null, "e": 9076, "s": 9046, "text": "Offers better data assurance." }, { "code": null, "e": 9098, "s": 9076, "text": "Free and open source." }, { "code": null, "e": 9148, "s": 9098, "text": "The official site for Git is https://git-scm.com/" }, { "code": null, "e": 9273, "s": 9148, "text": "Step 1 − After the download is complete, please follow the installation steps. In the initial screen, click the Next button." }, { "code": null, "e": 9372, "s": 9273, "text": "Step 2 − Choose the components which needs to be installed. You can accept the default components." }, { "code": null, "e": 9459, "s": 9372, "text": "Step 3 − In the next step, choose the program shortcut name and click the Next button." }, { "code": null, "e": 9529, "s": 9459, "text": "Step 4 − Accept the default SSH executable and click the Next button." }, { "code": null, "e": 9647, "s": 9529, "text": "Step 5 − Accept the default setting of �Checkout Windows style, commit Unix style endings� and click the Next button." }, { "code": null, "e": 9740, "s": 9647, "text": "Step 6 − Now, accept the default setting of the terminal emulator and click the Next button." }, { "code": null, "e": 9804, "s": 9740, "text": "Step 7 − Accept the default settings and click the Next button." }, { "code": null, "e": 9881, "s": 9804, "text": "Step 8 − You can skip the experimental options and click the Install button." }, { "code": null, "e": 9965, "s": 9881, "text": "Step 9 − In the final screen, click the Finish button to complete the installation." }, { "code": null, "e": 10043, "s": 9965, "text": "There are various ways to get started with your first Angular JS application." }, { "code": null, "e": 10209, "s": 10043, "text": "One way is to do everything from scratch which is the most difficult and not the preferred way. Due to the many dependencies, it becomes difficult to get this setup." }, { "code": null, "e": 10375, "s": 10209, "text": "One way is to do everything from scratch which is the most difficult and not the preferred way. Due to the many dependencies, it becomes difficult to get this setup." }, { "code": null, "e": 10593, "s": 10375, "text": "Another way is to use the quick start at Angular Github. This contains the necessary code to get started. This is normally what is opted by all developers and this is what we will show for the Hello World application." }, { "code": null, "e": 10811, "s": 10593, "text": "Another way is to use the quick start at Angular Github. This contains the necessary code to get started. This is normally what is opted by all developers and this is what we will show for the Hello World application." }, { "code": null, "e": 10902, "s": 10811, "text": "The final way is to use Angular CLI. We will discuss this in detail in a separate chapter." }, { "code": null, "e": 10993, "s": 10902, "text": "The final way is to use Angular CLI. We will discuss this in detail in a separate chapter." }, { "code": null, "e": 11072, "s": 10993, "text": "Following are the steps to get a sample application up and running via github." }, { "code": null, "e": 11139, "s": 11072, "text": "Step 1 − Go the github url - https://github.com/angular/quickstart" }, { "code": null, "e": 11295, "s": 11139, "text": "Step 2 − Go to your command prompt, create a project directory. This can be an empty directory. In our example, we have created a directory called Project." }, { "code": null, "e": 11490, "s": 11295, "text": "Step 3 − Next, in the command prompt, go to this directory and issue the following command to clone the github repository on your local system. You can do this by issuing the following command −" }, { "code": null, "e": 11545, "s": 11490, "text": "git clone https://github.com/angular/quickstart Demo \n" }, { "code": null, "e": 11617, "s": 11545, "text": "This will create a sample Angular JS application on your local machine." }, { "code": null, "e": 11663, "s": 11617, "text": "Step 4 − Open the code in Visual Studio code." }, { "code": null, "e": 11764, "s": 11663, "text": "Step 5 − Go to the command prompt and in your project folder again and issue the following command −" }, { "code": null, "e": 11778, "s": 11764, "text": "npm install \n" }, { "code": null, "e": 11882, "s": 11778, "text": "This will install all the necessary packages which are required for the Angular JS application to work." }, { "code": null, "e": 11958, "s": 11882, "text": "Once done, you should see a tree structure with all dependencies installed." }, { "code": null, "e": 12056, "s": 11958, "text": "Step 6 − Go to the folder Demo → src → app → app.component.ts. Find the following lines of code −" }, { "code": null, "e": 12229, "s": 12056, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: `<h1>Hello {{name}}</h1>`,\n})\nexport class AppComponent { name = 'Angular'; }" }, { "code": null, "e": 12289, "s": 12229, "text": "And replace the Angular keyword with World as shown below −" }, { "code": null, "e": 12461, "s": 12289, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: `<h1>Hello {{name}}</h1>`,\n})\nexport class AppComponent { name = 'World'; }\n" }, { "code": null, "e": 12757, "s": 12461, "text": "There are other files that get created as part of the project creation for Angular 2 application. At the moment, you don�t need to bother about the other code files because these are all included as part of your Angular 2 application and don�t need to be changed for the Hello World application." }, { "code": null, "e": 12829, "s": 12757, "text": "We will be discussing these files in the subsequent chapters in detail." }, { "code": null, "e": 12956, "s": 12829, "text": "Note − Visual Studio Code will automatically compile all your files and create JavaScript files for all your typescript files." }, { "code": null, "e": 13133, "s": 12956, "text": "Step 7 − Now go to your command prompt and issue the command npm start. This will cause the Node package manager to start a lite web server and launch your Angular application." }, { "code": null, "e": 13275, "s": 13133, "text": "The Angular JS application will now launch in the browser and you will see �Hello World� in the browser as shown in the following screenshot." }, { "code": null, "e": 13470, "s": 13275, "text": "This topic focuses on the deployment of the above Hello world application. Since this is an Angular JS application, it can be deployed onto any platform. Your development can be on any platform." }, { "code": null, "e": 13575, "s": 13470, "text": "In this case, it will be on Windows using Visual Studio code. Now let�s look at two deployment options." }, { "code": null, "e": 13740, "s": 13575, "text": "Note that you can use any web server on any platform to host Angular JS applications. In this case, we will take the example of NGNIX which is a popular web server." }, { "code": null, "e": 13836, "s": 13740, "text": "Step 1 − Download the NGNIX web server from the following url http://nginx.org/en/download.html" }, { "code": null, "e": 14044, "s": 13836, "text": "Step 2 − After extracting the downloaded zip file, run the nginx exe component which will make the web server run in the background. You will then be able to go to the home page in the url � http://localhost" }, { "code": null, "e": 14106, "s": 14044, "text": "Step 3 − Go to Angular JS project folder in Windows explorer." }, { "code": null, "e": 14162, "s": 14106, "text": "Step 4 − Copy the Project → Demo → node-modules folder." }, { "code": null, "e": 14231, "s": 14162, "text": "Step 5 − Copy all the contents from the Project → Demo → src folder." }, { "code": null, "e": 14284, "s": 14231, "text": "Step 6 − Copy all contents to the nginx/html folder." }, { "code": null, "e": 14410, "s": 14284, "text": "Now go to the URL − http://localhost, you will actually see the hello world application as shown in the following screenshot." }, { "code": null, "e": 14492, "s": 14410, "text": "Now let�s see how to host the same hello world application onto an Ubuntu server." }, { "code": null, "e": 14570, "s": 14492, "text": "Step 1 − Issue the following commands on your Ubuntu server to install nginx." }, { "code": null, "e": 14586, "s": 14570, "text": "apt-get update\n" }, { "code": null, "e": 14663, "s": 14586, "text": "The above command will ensure all the packages on the system are up to date." }, { "code": null, "e": 14707, "s": 14663, "text": "Once done, the system should be up to date." }, { "code": null, "e": 14788, "s": 14707, "text": "Step 2 − Now, install GIT on the Ubuntu server by issuing the following command." }, { "code": null, "e": 14814, "s": 14788, "text": "sudo apt-get install git\n" }, { "code": null, "e": 14862, "s": 14814, "text": "Once done, GIT will be installed on the system." }, { "code": null, "e": 14926, "s": 14862, "text": "Step 3 − To check the git version, issue the following command." }, { "code": null, "e": 14945, "s": 14926, "text": "sudo git �version\n" }, { "code": null, "e": 15052, "s": 14945, "text": "Step 4 − Install npm which is the node package manager on Ubuntu. To do this, issue the following command." }, { "code": null, "e": 15078, "s": 15052, "text": "sudo apt-get install npm\n" }, { "code": null, "e": 15126, "s": 15078, "text": "Once done, npm will be installed on the system." }, { "code": null, "e": 15190, "s": 15126, "text": "Step 5 − To check the npm version, issue the following command." }, { "code": null, "e": 15209, "s": 15190, "text": "sudo npm -version\n" }, { "code": null, "e": 15284, "s": 15209, "text": "Step 6 − Next, install nodejs. This can be done via the following command." }, { "code": null, "e": 15309, "s": 15284, "text": "sudo npm install nodejs\n" }, { "code": null, "e": 15383, "s": 15309, "text": "Step 7 − To see the version of Node.js, just issue the following command." }, { "code": null, "e": 15405, "s": 15383, "text": "sudo nodejs �version\n" }, { "code": null, "e": 15511, "s": 15405, "text": "Step 8 − Create a project folder and download the github starter project using the following git command." }, { "code": null, "e": 15565, "s": 15511, "text": "git clone https://github.com/angular/quickstart Demo\n" }, { "code": null, "e": 15619, "s": 15565, "text": "This will download all the files on the local system." }, { "code": null, "e": 15719, "s": 15619, "text": "You can navigate through the folder to see the files have been successfully downloaded from github." }, { "code": null, "e": 15770, "s": 15719, "text": "Step 9 − Next issue the following command for npm." }, { "code": null, "e": 15783, "s": 15770, "text": "npm install\n" }, { "code": null, "e": 15883, "s": 15783, "text": "This will install all the necessary packages which are required for Angular JS application to work." }, { "code": null, "e": 15953, "s": 15883, "text": "Once done, you will see all the dependencies installed on the system." }, { "code": null, "e": 16084, "s": 15953, "text": "Step 10 − Go to the folder Demo → src → app → app.component.ts. Use the vim editor if required. Find the following lines of code −" }, { "code": null, "e": 16263, "s": 16084, "text": "import { Component } from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n template: '<h1>Hello {{name}}</h1>'; \n}) \nexport class AppComponent { name = 'Angular'; } " }, { "code": null, "e": 16338, "s": 16263, "text": "And replace the Angular keyword with World as shown in the following code." }, { "code": null, "e": 16515, "s": 16338, "text": "import { Component } from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n template: '<h1>Hello {{name}}</h1>'; \n}) \nexport class AppComponent { name = 'World'; } " }, { "code": null, "e": 16806, "s": 16515, "text": "There are other files that get created as part of the project creation for Angular 2 application. At the moment, you don�t need to bother about the other code files because they are included as part of your Angular 2 application and don�t need to be changed for the Hello World application." }, { "code": null, "e": 16878, "s": 16806, "text": "We will be discussing these files in the subsequent chapters in detail." }, { "code": null, "e": 17021, "s": 16878, "text": "Step 11 − Next, install the lite server which can be used to run the Angular 2 application. You can do this by issuing the following command −" }, { "code": null, "e": 17061, "s": 17021, "text": "sudo npm install �save-dev lite-server\n" }, { "code": null, "e": 17152, "s": 17061, "text": "Once done, you will see the completion status. You don�t need to worry about the warnings." }, { "code": null, "e": 17315, "s": 17152, "text": "Step 12 − Create a symbolic link to the node folder via the following command. This helps in ensuring the node package manager can locate the nodejs installation." }, { "code": null, "e": 17357, "s": 17315, "text": "sudo ln -s /usr/bin/nodejs /usr/bin/node\n" }, { "code": null, "e": 17563, "s": 17357, "text": "Step 13 − Now it�s time to start Angular 2 Application via the npm start command. This will first build the files and then launch the Angular app in the lite server which was installed in the earlier step." }, { "code": null, "e": 17593, "s": 17563, "text": "Issue the following command −" }, { "code": null, "e": 17609, "s": 17593, "text": "sudo npm start\n" }, { "code": null, "e": 17656, "s": 17609, "text": "Once done, you will be presented with the URL." }, { "code": null, "e": 17734, "s": 17656, "text": "If you go to the URL, you will now see the Angular 2 app loading the browser." }, { "code": null, "e": 17896, "s": 17734, "text": "Note − You can use any web server on any platform to host Angular JS applications. In this case, we will take the example of NGNIX which is a popular web server." }, { "code": null, "e": 17989, "s": 17896, "text": "Step 1 − Issue the following command on your Ubuntu server to install nginx as a web server." }, { "code": null, "e": 18010, "s": 17989, "text": "sudo apt-get update\n" }, { "code": null, "e": 18082, "s": 18010, "text": "This command will ensure all the packages on the system are up to date." }, { "code": null, "e": 18126, "s": 18082, "text": "Once done, the system should be up to date." }, { "code": null, "e": 18185, "s": 18126, "text": "Step 2 − Now issue the following command to install nginx." }, { "code": null, "e": 18208, "s": 18185, "text": "apt-get install nginx\n" }, { "code": null, "e": 18260, "s": 18208, "text": "Once done, nginx will be running in the background." }, { "code": null, "e": 18343, "s": 18260, "text": "Step 3 − Run the following command to confirm that the nginx services are running." }, { "code": null, "e": 18364, "s": 18343, "text": "ps �ef | grep nginx\n" }, { "code": null, "e": 18522, "s": 18364, "text": "Now by default, the files for nginx are stored in /var/www/html folder. Hence, give the required permissions to copy your Hello World files to this location." }, { "code": null, "e": 18560, "s": 18522, "text": "Step 4 − Issue the following command." }, { "code": null, "e": 18590, "s": 18560, "text": "sudo chmod 777 /var/www/html\n" }, { "code": null, "e": 18686, "s": 18590, "text": "Step 5 − Copy the files using any method to copy the project files to the /var/www/html folder." }, { "code": null, "e": 18804, "s": 18686, "text": "Now, if you browse to the URL − http://192.168.1.200/index.html you will find the Hello world Angular JS application." }, { "code": null, "e": 19111, "s": 18804, "text": "Modules are used in Angular JS to put logical boundaries in your application. Hence, instead of coding everything into one application, you can instead build everything into separate modules to separate the functionality of your application. Let�s inspect the code which gets added to the demo application." }, { "code": null, "e": 19225, "s": 19111, "text": "In Visual Studio code, go to the app.module.ts folder in your app folder. This is known as the root module class." }, { "code": null, "e": 19287, "s": 19225, "text": "The following code will be present in the app.module.ts file." }, { "code": null, "e": 19602, "s": 19287, "text": "import { NgModule } from '@angular/core'; \nimport { BrowserModule } from '@angular/platform-browser'; \nimport { AppComponent } from './app.component'; \n\n@NgModule ({ \n imports: [ BrowserModule ], \n declarations: [ AppComponent ], \n bootstrap: [ AppComponent ] \n}) \nexport class AppModule { } " }, { "code": null, "e": 19652, "s": 19602, "text": "Let�s go through each line of the code in detail." }, { "code": null, "e": 19851, "s": 19652, "text": "The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module." }, { "code": null, "e": 20050, "s": 19851, "text": "The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module." }, { "code": null, "e": 20154, "s": 20050, "text": "The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options." }, { "code": null, "e": 20258, "s": 20154, "text": "The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options." }, { "code": null, "e": 20338, "s": 20258, "text": "The BrowserModule is required by default for any web based angular application." }, { "code": null, "e": 20418, "s": 20338, "text": "The BrowserModule is required by default for any web based angular application." }, { "code": null, "e": 20502, "s": 20418, "text": "The bootstrap option tells Angular which Component to bootstrap in the application." }, { "code": null, "e": 20586, "s": 20502, "text": "The bootstrap option tells Angular which Component to bootstrap in the application." }, { "code": null, "e": 20631, "s": 20586, "text": "A module is made up of the following parts −" }, { "code": null, "e": 20938, "s": 20631, "text": "Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application." }, { "code": null, "e": 21245, "s": 20938, "text": "Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application." }, { "code": null, "e": 21358, "s": 21245, "text": "Export array − This is used to export components, directives, and pipes which can then be used in other modules." }, { "code": null, "e": 21471, "s": 21358, "text": "Export array − This is used to export components, directives, and pipes which can then be used in other modules." }, { "code": null, "e": 21602, "s": 21471, "text": "Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules." }, { "code": null, "e": 21733, "s": 21602, "text": "Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules." }, { "code": null, "e": 22017, "s": 21733, "text": "The following screenshot shows the anatomy of an Angular 2 application. Each application consists of Components. Each component is a logical boundary of functionality for the application. You need to have layered services, which are used to share the functionality across components." }, { "code": null, "e": 22084, "s": 22017, "text": "Following is the anatomy of a Component. A component consists of −" }, { "code": null, "e": 22167, "s": 22084, "text": "Class − This is like a C++ or Java class which consists of properties and methods." }, { "code": null, "e": 22250, "s": 22167, "text": "Class − This is like a C++ or Java class which consists of properties and methods." }, { "code": null, "e": 22339, "s": 22250, "text": "Metadata − This is used to decorate the class and extend the functionality of the class." }, { "code": null, "e": 22428, "s": 22339, "text": "Metadata − This is used to decorate the class and extend the functionality of the class." }, { "code": null, "e": 22515, "s": 22428, "text": "Template − This is used to define the HTML view which is displayed in the application." }, { "code": null, "e": 22602, "s": 22515, "text": "Template − This is used to define the HTML view which is displayed in the application." }, { "code": null, "e": 22642, "s": 22602, "text": "Following is an example of a component." }, { "code": null, "e": 22837, "s": 22642, "text": "import { Component } from '@angular/core';\n\n@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) \n\nexport class AppComponent { \n appTitle: string = 'Welcome';\n} " }, { "code": null, "e": 23033, "s": 22837, "text": "Each application is made up of modules. Each Angular 2 application needs to have one Angular Root Module. Each Angular Root module can then have multiple components to separate the functionality." }, { "code": null, "e": 23075, "s": 23033, "text": "Following is an example of a root module." }, { "code": null, "e": 23389, "s": 23075, "text": "import { NgModule } from '@angular/core'; \nimport { BrowserModule } from '@angular/platform-browser'; \nimport { AppComponent } from './app.component'; \n\n@NgModule ({ \n imports: [ BrowserModule ], \n declarations: [ AppComponent ], \n bootstrap: [ AppComponent ] \n}) \nexport class AppModule { } " }, { "code": null, "e": 23590, "s": 23389, "text": "Each application is made up of feature modules where each module has a separate feature of the application. Each Angular feature module can then have multiple components to separate the functionality." }, { "code": null, "e": 23697, "s": 23590, "text": "Components are a logical piece of code for Angular JS application. A Component consists of the following −" }, { "code": null, "e": 23882, "s": 23697, "text": "Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives." }, { "code": null, "e": 24067, "s": 23882, "text": "Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives." }, { "code": null, "e": 24251, "s": 24067, "text": "Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript." }, { "code": null, "e": 24435, "s": 24251, "text": "Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript." }, { "code": null, "e": 24533, "s": 24435, "text": "Metadata − This has the extra data defined for the Angular class. It is defined with a decorator." }, { "code": null, "e": 24631, "s": 24533, "text": "Metadata − This has the extra data defined for the Angular class. It is defined with a decorator." }, { "code": null, "e": 24713, "s": 24631, "text": "Let�s now go to the app.component.ts file and create our first Angular component." }, { "code": null, "e": 24789, "s": 24713, "text": "Let�s add the following code to the file and look at each aspect in detail." }, { "code": null, "e": 24905, "s": 24789, "text": "The class decorator. The class is defined in TypeScript. The class normally has the following syntax in TypeScript." }, { "code": null, "e": 24964, "s": 24905, "text": "class classname {\n Propertyname: PropertyType = Value\n}\n" }, { "code": null, "e": 25019, "s": 24964, "text": "Classname − This is the name to be given to the class." }, { "code": null, "e": 25074, "s": 25019, "text": "Classname − This is the name to be given to the class." }, { "code": null, "e": 25135, "s": 25074, "text": "Propertyname − This is the name to be given to the property." }, { "code": null, "e": 25196, "s": 25135, "text": "Propertyname − This is the name to be given to the property." }, { "code": null, "e": 25288, "s": 25196, "text": "PropertyType − Since TypeScript is strongly typed, you need to give a type to the property." }, { "code": null, "e": 25380, "s": 25288, "text": "PropertyType − Since TypeScript is strongly typed, you need to give a type to the property." }, { "code": null, "e": 25435, "s": 25380, "text": "Value − This is the value to be given to the property." }, { "code": null, "e": 25490, "s": 25435, "text": "Value − This is the value to be given to the property." }, { "code": null, "e": 25553, "s": 25490, "text": "export class AppComponent {\n appTitle: string = 'Welcome';\n}" }, { "code": null, "e": 25609, "s": 25553, "text": "In the example, the following things need to be noted −" }, { "code": null, "e": 25654, "s": 25609, "text": "We are defining a class called AppComponent." }, { "code": null, "e": 25699, "s": 25654, "text": "We are defining a class called AppComponent." }, { "code": null, "e": 25808, "s": 25699, "text": "The export keyword is used so that the component can be used in other modules in the Angular JS application." }, { "code": null, "e": 25917, "s": 25808, "text": "The export keyword is used so that the component can be used in other modules in the Angular JS application." }, { "code": null, "e": 25955, "s": 25917, "text": "appTitle is the name of the property." }, { "code": null, "e": 25993, "s": 25955, "text": "appTitle is the name of the property." }, { "code": null, "e": 26035, "s": 25993, "text": "The property is given the type of string." }, { "code": null, "e": 26077, "s": 26035, "text": "The property is given the type of string." }, { "code": null, "e": 26121, "s": 26077, "text": "The property is given a value of �Welcome�." }, { "code": null, "e": 26165, "s": 26121, "text": "The property is given a value of �Welcome�." }, { "code": null, "e": 26229, "s": 26165, "text": "This is the view which needs to be rendered in the application." }, { "code": null, "e": 26279, "s": 26229, "text": "Template: '\n <HTML code>\n class properties\n'\n" }, { "code": null, "e": 26360, "s": 26279, "text": "HTML Code − This is the HTML code which needs to be rendered in the application." }, { "code": null, "e": 26441, "s": 26360, "text": "HTML Code − This is the HTML code which needs to be rendered in the application." }, { "code": null, "e": 26539, "s": 26441, "text": "Class properties − These are the properties of the class which can be referenced in the template." }, { "code": null, "e": 26637, "s": 26539, "text": "Class properties − These are the properties of the class which can be referenced in the template." }, { "code": null, "e": 26734, "s": 26637, "text": "template: '\n <div>\n <h1>{{appTitle}}</h1>\n <div>To Tutorials Point</div>\n </div>\n'" }, { "code": null, "e": 26790, "s": 26734, "text": "In the example, the following things need to be noted −" }, { "code": null, "e": 26862, "s": 26790, "text": "We are defining the HTML code which will be rendered in our application" }, { "code": null, "e": 26934, "s": 26862, "text": "We are defining the HTML code which will be rendered in our application" }, { "code": null, "e": 26996, "s": 26934, "text": "We are also referencing the appTitle property from our class." }, { "code": null, "e": 27058, "s": 26996, "text": "We are also referencing the appTitle property from our class." }, { "code": null, "e": 27129, "s": 27058, "text": "This is used to decorate Angular JS class with additional information." }, { "code": null, "e": 27209, "s": 27129, "text": "Let�s take a look at the completed code with our class, template, and metadata." }, { "code": null, "e": 27455, "s": 27209, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: ` <div>\n <h1>{{appTitle}}</h1>\n <div>To Tutorials Point</div>\n </div> `,\n})\n\nexport class AppComponent {\n appTitle: string = 'Welcome';\n}" }, { "code": null, "e": 27517, "s": 27455, "text": "In the above example, the following things need to be noted −" }, { "code": null, "e": 27615, "s": 27517, "text": "We are using the import keyword to import the �Component� decorator from the angular/core module." }, { "code": null, "e": 27713, "s": 27615, "text": "We are using the import keyword to import the �Component� decorator from the angular/core module." }, { "code": null, "e": 27768, "s": 27713, "text": "We are then using the decorator to define a component." }, { "code": null, "e": 27823, "s": 27768, "text": "We are then using the decorator to define a component." }, { "code": null, "e": 27950, "s": 27823, "text": "The component has a selector called �my-app�. This is nothing but our custom html tag which can be used in our main html page." }, { "code": null, "e": 28077, "s": 27950, "text": "The component has a selector called �my-app�. This is nothing but our custom html tag which can be used in our main html page." }, { "code": null, "e": 28127, "s": 28077, "text": "Now, let�s go to our index.html file in our code." }, { "code": null, "e": 28315, "s": 28127, "text": "Let�s make sure that the body tag now contains a reference to our custom tag in the component. Thus in the above case, we need to make sure that the body tag contains the following code −" }, { "code": null, "e": 28352, "s": 28315, "text": "<body>\n <my-app></my-app>\n</body>\n" }, { "code": null, "e": 28467, "s": 28352, "text": "Now if we go to the browser and see the output, we will see that the output is rendered as it is in the component." }, { "code": null, "e": 28556, "s": 28467, "text": "In the chapter on Components, we have already seen an example of the following template." }, { "code": null, "e": 28653, "s": 28556, "text": "template: '\n <div>\n <h1>{{appTitle}}</h1>\n <div>To Tutorials Point</div>\n </div>\n'" }, { "code": null, "e": 28843, "s": 28653, "text": "This is known as an inline template. There are other ways to define a template and that can be done via the templateURL command. The simplest way to use this in the component is as follows." }, { "code": null, "e": 28881, "s": 28843, "text": "templateURL:\nviewname.component.html\n" }, { "code": null, "e": 28938, "s": 28881, "text": "viewname − This is the name of the app component module." }, { "code": null, "e": 28995, "s": 28938, "text": "viewname − This is the name of the app component module." }, { "code": null, "e": 29065, "s": 28995, "text": "After the viewname, the component needs to be added to the file name." }, { "code": null, "e": 29119, "s": 29065, "text": "Following are the steps to define an inline template." }, { "code": null, "e": 29215, "s": 29119, "text": "Step 1 − Create a file called app.component.html. This will contain the html code for the view." }, { "code": null, "e": 29274, "s": 29215, "text": "Step 2 − Add the following code in the above created file." }, { "code": null, "e": 29315, "s": 29274, "text": "<div>{{appTitle}} Tutorialspoint </div>\n" }, { "code": null, "e": 29412, "s": 29315, "text": "This defines a simple div tag and references the appTitle property from the app.component class." }, { "code": null, "e": 29475, "s": 29412, "text": "Step 3 − In the app.component.ts file, add the following code." }, { "code": null, "e": 29666, "s": 29475, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n templateUrl: 'app/app.component.html' \n})\n\nexport class AppComponent {\n appTitle: string = 'Welcome';\n}" }, { "code": null, "e": 29834, "s": 29666, "text": "From the above code, the only change that can be noted is from the templateURL, which gives the link to the app.component.html file which is located in the app folder." }, { "code": null, "e": 29907, "s": 29834, "text": "Step 4 − Run the code in the browser, you will get the following output." }, { "code": null, "e": 30017, "s": 29907, "text": "From the output, it can be seen that the template file (app.component.html) file is being called accordingly." }, { "code": null, "e": 30188, "s": 30017, "text": "A directive is a custom HTML element that is used to extend the power of HTML. Angular 2 has the following directives that get called as part of the BrowserModule module." }, { "code": null, "e": 30193, "s": 30188, "text": "ngif" }, { "code": null, "e": 30199, "s": 30193, "text": "ngFor" }, { "code": null, "e": 30372, "s": 30199, "text": "If you view the app.module.ts file, you will see the following code and the BrowserModule module defined. By defining this module, you will have access to the 2 directives." }, { "code": null, "e": 30676, "s": 30372, "text": "import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { AppComponent } from './app.component';\n\n@NgModule ({\n imports: [ BrowserModule ],\n declarations: [ AppComponent ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }" }, { "code": null, "e": 30720, "s": 30676, "text": "Now let�s look at each directive in detail." }, { "code": null, "e": 30855, "s": 30720, "text": "The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code." }, { "code": null, "e": 30877, "s": 30855, "text": "*ngIf = 'expression'\n" }, { "code": null, "e": 30981, "s": 30877, "text": "If the expression evaluates to true then the corresponding gets added, else the elements are not added." }, { "code": null, "e": 31056, "s": 30981, "text": "Let�s now take a look at an example of how we can use the *ngif directive." }, { "code": null, "e": 31177, "s": 31056, "text": "Step 1 − First add a property to the class named appStatus. This will be of type Boolean. Let�s keep this value as true." }, { "code": null, "e": 31398, "s": 31177, "text": "import { Component } from '@angular/core'; \n\n@Component ({\n selector: 'my-app',\n templateUrl: 'app/app.component.html'\n})\n\nexport class AppComponent {\n appTitle: string = 'Welcome';\n appStatus: boolean = true;\n}" }, { "code": null, "e": 31467, "s": 31398, "text": "Step 2 − Now in the app.component.html file, add the following code." }, { "code": null, "e": 31529, "s": 31467, "text": "<div *ngIf = 'appStatus'>{{appTitle}} Tutorialspoint </div> \n" }, { "code": null, "e": 31767, "s": 31529, "text": "In the above code, we now have the *ngIf directive. In the directive we are evaluating the value of the appStatus property. Since the value of the property should evaluate to true, it means the div tag should be displayed in the browser." }, { "code": null, "e": 31844, "s": 31767, "text": "Once we add the above code, we will get the following output in the browser." }, { "code": null, "e": 31922, "s": 31844, "text": "The ngFor element is used to elements based on the condition of the For loop." }, { "code": null, "e": 31963, "s": 31922, "text": "*ngFor = 'let variable of variablelist'\n" }, { "code": null, "e": 32043, "s": 31963, "text": "The variable is a temporary variable to display the values in the variablelist." }, { "code": null, "e": 32119, "s": 32043, "text": "Let�s now take a look at an example of how we can use the *ngFor directive." }, { "code": null, "e": 32250, "s": 32119, "text": "Step 1 − First add a property to the class named appList. This will be of the type which can be used to define any type of arrays." }, { "code": null, "e": 32560, "s": 32250, "text": "import { Component } from '@angular/core';\n \n@Component ({\n selector: 'my-app',\n templateUrl: 'app/app.component.html'\n})\n\nexport class AppComponent {\n appTitle: string = 'Welcome';\n appList: any[] = [ {\n \"ID\": \"1\",\n \"Name\" : \"One\"\n },\n\n {\n \"ID\": \"2\",\n \"Name\" : \"Two\"\n } ];\n}" }, { "code": null, "e": 32679, "s": 32560, "text": "Hence, we are defining the appList as an array which has 2 elements. Each element has 2 sub properties as ID and Name." }, { "code": null, "e": 32742, "s": 32679, "text": "Step 2 − In the app.component.html, define the following code." }, { "code": null, "e": 32862, "s": 32742, "text": "<div *ngFor = 'let lst of appList'> \n <ul> \n <li>{{lst.ID}}</li> \n <li>{{lst.Name}}</li> \n </ul> \n</div> " }, { "code": null, "e": 33042, "s": 32862, "text": "In the above code, we are now using the ngFor directive to iterate through the appList array. We then define a list where each list item is the ID and name parameter of the array." }, { "code": null, "e": 33119, "s": 33042, "text": "Once we add the above code, we will get the following output in the browser." }, { "code": null, "e": 33265, "s": 33119, "text": "Metadata is used to decorate a class so that it can configure the expected behavior of the class. Following are the different parts for metadata." }, { "code": null, "e": 33402, "s": 33265, "text": "Annotations − These are decorators at the class level. This is an array and an example having both the @Component and @Routes decorator." }, { "code": null, "e": 33477, "s": 33402, "text": "Following is a sample code, which is present in the app.component.ts file." }, { "code": null, "e": 33562, "s": 33477, "text": "@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) " }, { "code": null, "e": 33660, "s": 33562, "text": "The component decorator is used to declare the class in the app.component.ts file as a component." }, { "code": null, "e": 33753, "s": 33660, "text": "Design:paramtypes − These are only used for the constructors and applied only to Typescript." }, { "code": null, "e": 33846, "s": 33753, "text": "Design:paramtypes − These are only used for the constructors and applied only to Typescript." }, { "code": null, "e": 33931, "s": 33846, "text": "propMetadata − This is the metadata which is applied to the properties of the class." }, { "code": null, "e": 34016, "s": 33931, "text": "propMetadata − This is the metadata which is applied to the properties of the class." }, { "code": null, "e": 34046, "s": 34016, "text": "Following is an example code." }, { "code": null, "e": 34133, "s": 34046, "text": "export class AppComponent {\n @Environment(�test�)\n appTitle: string = 'Welcome';\n}" }, { "code": null, "e": 34236, "s": 34133, "text": "Here, the @Environment is the metadata applied to the property appTitle and the value given is �test�." }, { "code": null, "e": 34305, "s": 34236, "text": "Parameters − This is set by the decorators at the constructor level." }, { "code": null, "e": 34335, "s": 34305, "text": "Following is an example code." }, { "code": null, "e": 34429, "s": 34335, "text": "export class AppComponent {\n constructor(@Environment(�test� private appTitle:string) { }\n}" }, { "code": null, "e": 34509, "s": 34429, "text": "In the above example, metadata is applied to the parameters of the constructor." }, { "code": null, "e": 34703, "s": 34509, "text": "Two-way binding was a functionality in Angular JS, but has been removed from Angular 2.x onwards. But now, since the event of classes in Angular 2, we can bind to properties in AngularJS class." }, { "code": null, "e": 34788, "s": 34703, "text": "Suppose if you had a class with a class name, a property which had a type and value." }, { "code": null, "e": 34850, "s": 34788, "text": "export class className {\n property: propertytype = value;\n}" }, { "code": null, "e": 34928, "s": 34850, "text": "You could then bind the property of an html tag to the property of the class." }, { "code": null, "e": 34966, "s": 34928, "text": "<html tag htmlproperty = 'property'>\n" }, { "code": null, "e": 35048, "s": 34966, "text": "The value of the property would then be assigned to the htmlproperty of the html." }, { "code": null, "e": 35270, "s": 35048, "text": "Let�s look at an example of how we can achieve data binding. In our example, we will look at displaying images wherein the images source will come from the properties in our class. Following are the steps to achieve this." }, { "code": null, "e": 35369, "s": 35270, "text": "Step 1 − Download any 2 images. For this example, we will download some simple images shown below." }, { "code": null, "e": 35500, "s": 35369, "text": "Step 2 − Store these images in a folder called Images in the app directory. If the images folder is not present, please create it." }, { "code": null, "e": 35571, "s": 35500, "text": "Step 3 − Add the following content in app.component.ts as shown below." }, { "code": null, "e": 35906, "s": 35571, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n templateUrl: 'app/app.component.html'\n})\n\nexport class AppComponent {\n appTitle: string = 'Welcome';\n appList: any[] = [ {\n \"ID\": \"1\",\n \"url\": 'app/Images/One.jpg'\n },\n\n {\n \"ID\": \"2\",\n \"url\": 'app/Images/Two.jpg'\n } ];\n}" }, { "code": null, "e": 35979, "s": 35906, "text": "Step 4 − Add the following content in app.component.html as shown below." }, { "code": null, "e": 36095, "s": 35979, "text": "<div *ngFor = 'let lst of appList'>\n <ul>\n <li>{{lst.ID}}</li>\n <img [src] = 'lst.url'>\n </ul>\n</div>" }, { "code": null, "e": 36195, "s": 36095, "text": "In the above app.component.html file, we are accessing the images from the properties in our class." }, { "code": null, "e": 36249, "s": 36195, "text": "The output of the above program should be like this −" }, { "code": null, "e": 36364, "s": 36249, "text": "The basic CRUD operation we will look into this chapter is the reading of data from a web service using Angular 2." }, { "code": null, "e": 36629, "s": 36364, "text": "In this example, we are going to define a data source which is a simple json file of products. Next, we are going to define a service which will be used to read the data from the json file. And then next, we will use this service in our main app.component.ts file." }, { "code": null, "e": 36702, "s": 36629, "text": "Step 1 − First let�s define our product.json file in Visual Studio code." }, { "code": null, "e": 36830, "s": 36702, "text": "In the products.json file, enter the following text. This will be the data which will be taken from the Angular JS application." }, { "code": null, "e": 36938, "s": 36830, "text": "[{\n \"ProductID\": 1,\n \"ProductName\": \"ProductA\"\n},\n\n{\n \"ProductID\": 2,\n \"ProductName\": \"ProductB\"\n}]" }, { "code": null, "e": 37090, "s": 36938, "text": "Step 2 − Define an interface which will be the class definition to store the information from our products.json file. Create a file called products.ts." }, { "code": null, "e": 37138, "s": 37090, "text": "Step 3 − Insert the following code in the file." }, { "code": null, "e": 37214, "s": 37138, "text": "export interface IProduct {\n ProductID: number;\n ProductName: string;\n}" }, { "code": null, "e": 37320, "s": 37214, "text": "The above interface has the definition for the ProductID and ProductName as properties for the interface." }, { "code": null, "e": 37384, "s": 37320, "text": "Step 4 − In the app.module.ts file include the following code −" }, { "code": null, "e": 37741, "s": 37384, "text": "import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { AppComponent } from './app.component';\nimport { HttpModule } from '@angular/http';\n\n@NgModule ({\n imports: [ BrowserModule,HttpModule],\n declarations: [ AppComponent],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }" }, { "code": null, "e": 37806, "s": 37741, "text": "Step 5 − Define a products.service.ts file in Visual Studio code" }, { "code": null, "e": 37854, "s": 37806, "text": "Step 6 − Insert the following code in the file." }, { "code": null, "e": 38440, "s": 37854, "text": "import { Injectable } from '@angular/core';\nimport { Http , Response } from '@angular/http';\nimport { Observable } from 'rxjs/Observable';\nimport 'rxjs/add/operator/map';\nimport 'rxjs/add/operator/do';\nimport { IProduct } from './product';\n\n@Injectable()\nexport class ProductService {\n private _producturl='app/products.json';\n constructor(private _http: Http){}\n \n getproducts(): Observable<IProduct[]> {\n return this._http.get(this._producturl)\n .map((response: Response) => <IProduct[]> response.json())\n .do(data => console.log(JSON.stringify(data)));\n }\n}" }, { "code": null, "e": 38499, "s": 38440, "text": "Following points need to be noted about the above program." }, { "code": null, "e": 38656, "s": 38499, "text": "The import {Http, Response} from '@angular/http' statement is used to ensure that the http function can be used to get the data from the products.json file." }, { "code": null, "e": 38813, "s": 38656, "text": "The import {Http, Response} from '@angular/http' statement is used to ensure that the http function can be used to get the data from the products.json file." }, { "code": null, "e": 39066, "s": 38813, "text": "The following statements are used to make use of the Reactive framework which can be used to create an Observable variable. The Observable framework is used to detect any changes in the http response which can then be sent back to the main application." }, { "code": null, "e": 39319, "s": 39066, "text": "The following statements are used to make use of the Reactive framework which can be used to create an Observable variable. The Observable framework is used to detect any changes in the http response which can then be sent back to the main application." }, { "code": null, "e": 39429, "s": 39319, "text": "import { Observable } from 'rxjs/Observable';\nimport 'rxjs/add/operator/map';\nimport 'rxjs/add/operator/do';\n" }, { "code": null, "e": 39611, "s": 39429, "text": "The statement private _producturl = 'app/products.json' in the class is used to specify the location of our data source. It can also specify the location of web service if required." }, { "code": null, "e": 39793, "s": 39611, "text": "The statement private _producturl = 'app/products.json' in the class is used to specify the location of our data source. It can also specify the location of web service if required." }, { "code": null, "e": 39898, "s": 39793, "text": "Next, we define a variable of the type Http which will be used to get the response from the data source." }, { "code": null, "e": 40003, "s": 39898, "text": "Next, we define a variable of the type Http which will be used to get the response from the data source." }, { "code": null, "e": 40139, "s": 40003, "text": "Once we get the data from the data source, we then use the JSON.stringify(data) command to send the data to the console in the browser." }, { "code": null, "e": 40275, "s": 40139, "text": "Once we get the data from the data source, we then use the JSON.stringify(data) command to send the data to the console in the browser." }, { "code": null, "e": 40344, "s": 40275, "text": "Step 7 − Now in the app.component.ts file, place the following code." }, { "code": null, "e": 40997, "s": 40344, "text": "import { Component } from '@angular/core';\nimport { IProduct } from './product';\nimport { ProductService } from './products.service';\nimport { appService } from './app.service';\nimport { Http , Response } from '@angular/http';\nimport { Observable } from 'rxjs/Observable';\nimport 'rxjs/add/operator/map';\n\n@Component ({\n selector: 'my-app',\n template: '<div>Hello</div>',\n providers: [ProductService]\n})\n\nexport class AppComponent {\n iproducts: IProduct[];\n constructor(private _product: ProductService) {\n }\n \n ngOnInit() : void {\n this._product.getproducts()\n .subscribe(iproducts => this.iproducts = iproducts);\n }\n}" }, { "code": null, "e": 41160, "s": 40997, "text": "Here, the main thing in the code is the subscribe option which is used to listen to the Observable getproducts() function to listen for data from the data source." }, { "code": null, "e": 41271, "s": 41160, "text": "Now save all the codes and run the application using npm. Go to the browser, we will see the following output." }, { "code": null, "e": 41349, "s": 41271, "text": "In the Console, we will see the data being retrieved from products.json file." }, { "code": null, "e": 41494, "s": 41349, "text": "Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function." }, { "code": null, "e": 41619, "s": 41494, "text": "Let�s see the code required for error handling. This code can be added on top of the chapter for CRUD operations using http." }, { "code": null, "e": 41678, "s": 41619, "text": "In the product.service.ts file, enter the following code −" }, { "code": null, "e": 42485, "s": 41678, "text": "import { Injectable } from '@angular/core'; \nimport { Http , Response } from '@angular/http'; \nimport { Observable } from 'rxjs/Observable'; \n\nimport 'rxjs/add/operator/map'; \nimport 'rxjs/add/operator/do'; \nimport 'rxjs/add/operator/catch'; \nimport { IProduct } from './product'; \n\n@Injectable() \nexport class ProductService { \n private _producturl = 'app/products.json'; \n constructor(private _http: Http){} \n\n getproducts(): Observable<IProduct[]> { \n return this._http.get(this._producturl) \n .map((response: Response) => <IProduct[]> response.json()) \n .do(data => console.log(JSON.stringify(data))) \n .catch(this.handleError); \n } \n \n private handleError(error: Response) { \n console.error(error); \n return Observable.throw(error.json().error()); \n } \n}" }, { "code": null, "e": 42551, "s": 42485, "text": "The catch function contains a link to the Error Handler function." }, { "code": null, "e": 42617, "s": 42551, "text": "The catch function contains a link to the Error Handler function." }, { "code": null, "e": 42767, "s": 42617, "text": "In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue." }, { "code": null, "e": 42917, "s": 42767, "text": "In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue." }, { "code": null, "e": 43007, "s": 42917, "text": "Now, whenever you get an error it will be redirected to the error console of the browser." }, { "code": null, "e": 43210, "s": 43007, "text": "Routing helps in directing users to different pages based on the option they choose on the main page. Hence, based on the option they choose, the required Angular Component will be rendered to the user." }, { "code": null, "e": 43305, "s": 43210, "text": "Let�s see the necessary steps to see how we can implement routing in an Angular 2 application." }, { "code": null, "e": 43365, "s": 43305, "text": "Step 1 − Add the base reference tag in the index.html file." }, { "code": null, "e": 44144, "s": 43365, "text": "<!DOCTYPE html>\n<html>\n <head>\n <base href = \"/\">\n <title>Angular QuickStart</title>\n <meta charset = \"UTF-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n \n <base href = \"/\">\n <link rel = \"stylesheet\" href = \"styles.css\">\n\n <!-- Polyfill(s) for older browsers -->\n <script src = \"node_modules/core-js/client/shim.min.js\"></script>\n <script src = \"node_modules/zone.js/dist/zone.js\"></script>\n <script src = \"node_modules/systemjs/dist/system.src.js\"></script>\n <script src = \"systemjs.config.js\"></script>\n\n <script>\n System.import('main.js').catch(function(err){ console.error(err); });\n </script>\n </head>\n\n <body>\n <my-app></my-app>\n </body>\n</html>" }, { "code": null, "e": 44272, "s": 44144, "text": "Step 2 − Create two routes for the application. For this, create 2 files called Inventory.component.ts and product.component.ts" }, { "code": null, "e": 44340, "s": 44272, "text": "Step 3 − Place the following code in the product.component.ts file." }, { "code": null, "e": 44482, "s": 44340, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: 'Products',\n})\nexport class Appproduct {\n}" }, { "code": null, "e": 44552, "s": 44482, "text": "Step 4 − Place the following code in the Inventory.component.ts file." }, { "code": null, "e": 44693, "s": 44552, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: 'Inventory',\n})\nexport class AppInventory {\n}" }, { "code": null, "e": 44959, "s": 44693, "text": "Both of the components don�t do anything fancy, they just render the keywords based on the component. So for the Inventory component, it will display the Inventory keyword to the user. And for the products component, it will display the product keyword to the user." }, { "code": null, "e": 45020, "s": 44959, "text": "Step 5 − In the app.module.ts file, add the following code −" }, { "code": null, "e": 45659, "s": 45020, "text": "import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { AppComponent } from './app.component';\nimport { Appproduct } from './product.component';\nimport { AppInventory } from './Inventory.component';\nimport { RouterModule, Routes } from '@angular/router';\n\nconst appRoutes: Routes = [\n { path: 'Product', component: Appproduct },\n { path: 'Inventory', component: AppInventory },\n];\n\n@NgModule ({\n imports: [ BrowserModule,\n RouterModule.forRoot(appRoutes)],\n declarations: [ AppComponent,Appproduct,AppInventory],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }" }, { "code": null, "e": 45723, "s": 45659, "text": "The following points need to be noted about the above program −" }, { "code": null, "e": 45832, "s": 45723, "text": "The appRoutes contain 2 routes, one is the Appproduct component and the other is the AppInventory component." }, { "code": null, "e": 45941, "s": 45832, "text": "The appRoutes contain 2 routes, one is the Appproduct component and the other is the AppInventory component." }, { "code": null, "e": 45983, "s": 45941, "text": "Ensure to declare both of the components." }, { "code": null, "e": 46025, "s": 45983, "text": "Ensure to declare both of the components." }, { "code": null, "e": 46096, "s": 46025, "text": "The RouterModule.forRoot ensures to add the routes to the application." }, { "code": null, "e": 46167, "s": 46096, "text": "The RouterModule.forRoot ensures to add the routes to the application." }, { "code": null, "e": 46230, "s": 46167, "text": "Step 6 − In the app.component.ts file, add the following code." }, { "code": null, "e": 46537, "s": 46230, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: `\n <ul>\n <li><a [routerLink] = \"['/Product']\">Product</a></li>\n <li><a [routerLink] = \"['/Inventory']\">Inventory</a></li>\n </ul>\n <router-outlet></router-outlet>`\n})\nexport class AppComponent { }" }, { "code": null, "e": 46601, "s": 46537, "text": "The following point needs to be noted about the above program −" }, { "code": null, "e": 46716, "s": 46601, "text": "<router-outlet></router-outlet> is the placeholder to render the component based on which option the user chooses." }, { "code": null, "e": 46831, "s": 46716, "text": "<router-outlet></router-outlet> is the placeholder to render the component based on which option the user chooses." }, { "code": null, "e": 46943, "s": 46831, "text": "Now, save all the code and run the application using npm. Go to the browser, you will see the following output." }, { "code": null, "e": 47015, "s": 46943, "text": "Now if you click the Inventory link, you will get the following output." }, { "code": null, "e": 47144, "s": 47015, "text": "In Routing, one can also add an error route. This can happen if the user goes to a page which does not exist in the application." }, { "code": null, "e": 47193, "s": 47144, "text": "Let�s see how we can go about implementing this." }, { "code": null, "e": 47273, "s": 47193, "text": "Step 1 − Add a PageNotFound component as NotFound.component.ts as shown below −" }, { "code": null, "e": 47322, "s": 47273, "text": "Step 2 − Add the following code to the new file." }, { "code": null, "e": 47481, "s": 47322, "text": "import { Component } from '@angular/core';\n\n@Component ({ \n selector: 'my-app', \n template: 'Not Found', \n}) \nexport class PageNotFoundComponent { \n} " }, { "code": null, "e": 47540, "s": 47481, "text": "Step 3 − Add the following code to the app.module.ts file." }, { "code": null, "e": 48335, "s": 47540, "text": "import { NgModule } from '@angular/core'; \nimport { BrowserModule } from '@angular/platform-browser'; \nimport { AppComponent } from './app.component'; \nimport { Appproduct } from './product.component' \nimport { AppInventory } from './Inventory.component' \nimport { PageNotFoundComponent } from './NotFound.component' \nimport { RouterModule, Routes } from '@angular/router'; \n\nconst appRoutes: Routes = [ \n { path: 'Product', component: Appproduct }, \n { path: 'Inventory', component: AppInventory }, \n { path: '**', component: PageNotFoundComponent } \n]; \n\n@NgModule ({ \n imports: [ BrowserModule, \n RouterModule.forRoot(appRoutes)], \n declarations: [ AppComponent,Appproduct,AppInventory,PageNotFoundComponent], \n bootstrap: [ AppComponent ] \n}) \n\nexport class AppModule {\n} " }, { "code": null, "e": 48399, "s": 48335, "text": "The following point needs to be noted about the above program −" }, { "code": null, "e": 48606, "s": 48399, "text": "Now we have an extra route called path: '**', component: PageNotFoundComponent. Hence, ** is for any route which does not fit the default route. They will be directed to the PageNotFoundComponent component." }, { "code": null, "e": 48813, "s": 48606, "text": "Now we have an extra route called path: '**', component: PageNotFoundComponent. Hence, ** is for any route which does not fit the default route. They will be directed to the PageNotFoundComponent component." }, { "code": null, "e": 49000, "s": 48813, "text": "Now, save all the code and run the application using npm. Go to your browser, and you will see the following output. Now, when you go to any wrong link you will get the following output." }, { "code": null, "e": 49091, "s": 49000, "text": "In Angular 2, it is also possible to carry out manual navigation. Following are the steps." }, { "code": null, "e": 49159, "s": 49091, "text": "Step 1 − Add the following code to the Inventory.component.ts file." }, { "code": null, "e": 49535, "s": 49159, "text": "import { Component } from '@angular/core'; \nimport { Router } from '@angular/router'; \n\n@Component ({ \n selector: 'my-app', \n template: 'Inventory \n <a class = \"button\" (click) = \"onBack()\">Back to Products</a>' \n}) \n\nexport class AppInventory { \n constructor(private _router: Router){} \n\n onBack(): void { \n this._router.navigate(['/Product']); \n } \n}" }, { "code": null, "e": 49599, "s": 49535, "text": "The following points need to be noted about the above program −" }, { "code": null, "e": 49755, "s": 49599, "text": "Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page." }, { "code": null, "e": 49911, "s": 49755, "text": "Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page." }, { "code": null, "e": 49993, "s": 49911, "text": "In the onBack function, use the router.navigate to navigate to the required page." }, { "code": null, "e": 50075, "s": 49993, "text": "In the onBack function, use the router.navigate to navigate to the required page." }, { "code": null, "e": 50196, "s": 50075, "text": "Step 2 − Now, save all the code and run the application using npm. Go to the browser, you will see the following output." }, { "code": null, "e": 50231, "s": 50196, "text": "Step 3 − Click the Inventory link." }, { "code": null, "e": 50352, "s": 50231, "text": "Step 4 − Click the �Back to products� link, you will get the following output which takes you back to the Products page." }, { "code": null, "e": 50478, "s": 50352, "text": "Angular 2 can also design forms which can use two-way binding using the ngModel directive. Let�s see how we can achieve this." }, { "code": null, "e": 50568, "s": 50478, "text": "Step 1 − Create a model which is a products model. Create a file called products.ts file." }, { "code": null, "e": 50615, "s": 50568, "text": "Step 2 − Place the following code in the file." }, { "code": null, "e": 50737, "s": 50615, "text": "export class Product { \n constructor ( \n public productid: number, \n public productname: string \n ) { } \n}" }, { "code": null, "e": 50811, "s": 50737, "text": "This is a simple class which has 2 properties, productid and productname." }, { "code": null, "e": 50924, "s": 50811, "text": "Step 3 − Create a product form component called product-form.component.ts component and add the following code −" }, { "code": null, "e": 51177, "s": 50924, "text": "import { Component } from '@angular/core';\nimport { Product } from './products';\n\n@Component ({\n selector: 'product-form',\n templateUrl: './product-form.component.html'\n})\n\nexport class ProductFormComponent {\n model = new Product(1,'ProductA');\n}" }, { "code": null, "e": 51240, "s": 51177, "text": "The following points need to be noted about the above program." }, { "code": null, "e": 51327, "s": 51240, "text": "Create an object of the Product class and add values to the productid and productname." }, { "code": null, "e": 51414, "s": 51327, "text": "Create an object of the Product class and add values to the productid and productname." }, { "code": null, "e": 51526, "s": 51414, "text": "Use the templateUrl to specify the location of our product-form.component.html which will render the component." }, { "code": null, "e": 51638, "s": 51526, "text": "Use the templateUrl to specify the location of our product-form.component.html which will render the component." }, { "code": null, "e": 51750, "s": 51638, "text": "Step 4 − Create the actual form. Create a file called product-form.component.html and place the following code." }, { "code": null, "e": 52277, "s": 51750, "text": "<div class = \"container\">\n <h1>Product Form</h1>\n <form>\n <div class = \"form-group\">\n <label for = \"productid\">ID</label>\n <input type = \"text\" class = \"form-control\" id = \"productid\" required\n [(ngModel)] = \"model.productid\" name = \"id\">\n </div>\n \n <div class = \"form-group\">\n <label for = \"name\">Name</label>\n <input type = \"text\" class = \"form-control\" id = \"name\"\n [(ngModel)] = \"model.productname\" name = \"name\">\n </div>\n </form>\n</div>" }, { "code": null, "e": 52340, "s": 52277, "text": "The following point needs to be noted about the above program." }, { "code": null, "e": 52442, "s": 52340, "text": "The ngModel directive is used to bind the object of the product to the separate elements on the form." }, { "code": null, "e": 52544, "s": 52442, "text": "The ngModel directive is used to bind the object of the product to the separate elements on the form." }, { "code": null, "e": 52608, "s": 52544, "text": "Step 5 − Place the following code in the app.component.ts file." }, { "code": null, "e": 52767, "s": 52608, "text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: '<product-form></product-form>'\n})\nexport class AppComponent { }" }, { "code": null, "e": 52823, "s": 52767, "text": "Step 6 − Place the below code in the app.module.ts file" }, { "code": null, "e": 53255, "s": 52823, "text": "import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { AppComponent } from './app.component';\nimport { FormsModule } from '@angular/forms';\nimport { ProductFormComponent } from './product-form.component';\n\n@NgModule ({\n imports: [ BrowserModule,FormsModule],\n declarations: [ AppComponent,ProductFormComponent],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }" }, { "code": null, "e": 53372, "s": 53255, "text": "Step 7 − Save all the code and run the application using npm. Go to your browser, you will see the following output." }, { "code": null, "e": 53526, "s": 53372, "text": "Command Line Interface (CLI) can be used to create our Angular JS application. It also helps in creating a unit and end-to-end tests for the application." }, { "code": null, "e": 53587, "s": 53526, "text": "The official site for Angular CLI is https://cli.angular.io/" }, { "code": null, "e": 53724, "s": 53587, "text": "If you click on the Get started option, you will be directed to the github repository for the CLI https://github.com/angular/angular-cli" }, { "code": null, "e": 53789, "s": 53724, "text": "Let�s now look at some of the things we can do with Angular CLI." }, { "code": null, "e": 53913, "s": 53789, "text": "Note − Please ensure that Python is installed on the system. Python can be downloaded from the site https://www.python.org/" }, { "code": null, "e": 53995, "s": 53913, "text": "The first step is to install the CLI. We can do this with the following command −" }, { "code": null, "e": 54023, "s": 53995, "text": "npm install �g angular-cli\n" }, { "code": null, "e": 54112, "s": 54023, "text": "Now, create a new folder called angularCLI in any directory and issue the above command." }, { "code": null, "e": 54150, "s": 54112, "text": "Once done, the CLI will be installed." }, { "code": null, "e": 54213, "s": 54150, "text": "Angular JS project can be created using the following command." }, { "code": null, "e": 54234, "s": 54213, "text": "ng new Project_name\n" }, { "code": null, "e": 54308, "s": 54234, "text": "Project_name − This is the name of the project which needs to be created." }, { "code": null, "e": 54314, "s": 54308, "text": "None." }, { "code": null, "e": 54375, "s": 54314, "text": "Let�s execute the following command to create a new project." }, { "code": null, "e": 54389, "s": 54375, "text": "ng new demo2\n" }, { "code": null, "e": 54478, "s": 54389, "text": "It will automatically create the files and start downloading the necessary npm packages." }, { "code": null, "e": 54544, "s": 54478, "text": "Now in Visual Studio code, we can open the newly created project." }, { "code": null, "e": 54606, "s": 54544, "text": "To run the project, you need to issue the following command −" }, { "code": null, "e": 54617, "s": 54606, "text": "ng server\n" }, { "code": null, "e": 54738, "s": 54617, "text": "The default port number for the running application is 4200. You can browse to the port and see the application running." }, { "code": null, "e": 54911, "s": 54738, "text": "Dependency injection is the ability to add the functionality of components at runtime. Let�s take a look at an example and the steps used to implement dependency injection." }, { "code": null, "e": 55094, "s": 54911, "text": "Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module." }, { "code": null, "e": 55141, "s": 55094, "text": "@Injectable() \n export class classname { \n}" }, { "code": null, "e": 55300, "s": 55141, "text": "Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator." }, { "code": null, "e": 55347, "s": 55300, "text": "@Component ({ \n providers : [classname] \n})" }, { "code": null, "e": 55396, "s": 55347, "text": "Let�s look at an example on how to achieve this." }, { "code": null, "e": 55461, "s": 55396, "text": "Step 1 − Create a ts file for the service called app.service.ts." }, { "code": null, "e": 55522, "s": 55461, "text": "Step 2 − Place the following code in the file created above." }, { "code": null, "e": 55676, "s": 55522, "text": "import { \n Injectable \n} from '@angular/core'; \n\n@Injectable() \nexport class appService { \n getApp(): string { \n return \"Hello world\"; \n } \n}" }, { "code": null, "e": 55739, "s": 55676, "text": "The following points need to be noted about the above program." }, { "code": null, "e": 55806, "s": 55739, "text": "The Injectable decorator is imported from the angular/core module." }, { "code": null, "e": 55873, "s": 55806, "text": "The Injectable decorator is imported from the angular/core module." }, { "code": null, "e": 55964, "s": 55873, "text": "We are creating a class called appService that is decorated with the Injectable decorator." }, { "code": null, "e": 56055, "s": 55964, "text": "We are creating a class called appService that is decorated with the Injectable decorator." }, { "code": null, "e": 56155, "s": 56055, "text": "We are creating a simple function called getApp which returns a simple string called �Hello world�." }, { "code": null, "e": 56255, "s": 56155, "text": "We are creating a simple function called getApp which returns a simple string called �Hello world�." }, { "code": null, "e": 56319, "s": 56255, "text": "Step 3 − In the app.component.ts file place the following code." }, { "code": null, "e": 56718, "s": 56319, "text": "import { \n Component \n} from '@angular/core'; \n\nimport { \n appService \n} from './app.service'; \n\n@Component({ \n selector: 'my-app', \n template: '<div>{{value}}</div>', \n providers: [appService] \n}) \n\nexport class AppComponent { \n value: string = \"\"; \n constructor(private _appService: appService) { } \n ngOnInit(): void { \n this.value = this._appService.getApp(); \n } \n}" }, { "code": null, "e": 56781, "s": 56718, "text": "The following points need to be noted about the above program." }, { "code": null, "e": 56855, "s": 56781, "text": "First, we are importing our appService module in the appComponent module." }, { "code": null, "e": 56929, "s": 56855, "text": "First, we are importing our appService module in the appComponent module." }, { "code": null, "e": 56996, "s": 56929, "text": "Then, we are registering the service as a provider in this module." }, { "code": null, "e": 57063, "s": 56996, "text": "Then, we are registering the service as a provider in this module." }, { "code": null, "e": 57208, "s": 57063, "text": "In the constructor, we define a variable called _appService of the type appService so that it can be called anywhere in the appComponent module." }, { "code": null, "e": 57353, "s": 57208, "text": "In the constructor, we define a variable called _appService of the type appService so that it can be called anywhere in the appComponent module." }, { "code": null, "e": 57517, "s": 57353, "text": "As an example, in the ngOnInit lifecyclehook, we called the getApp function of the service and assigned the output to the value property of the AppComponent class." }, { "code": null, "e": 57681, "s": 57517, "text": "As an example, in the ngOnInit lifecyclehook, we called the getApp function of the service and assigned the output to the value property of the AppComponent class." }, { "code": null, "e": 57767, "s": 57681, "text": "Save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 57867, "s": 57767, "text": "In this chapter, we will look at the other configuration files which are part of Angular 2 project." }, { "code": null, "e": 57955, "s": 57867, "text": "This file is used to give the options about TypeScript used for the Angular JS project." }, { "code": null, "e": 58282, "s": 57955, "text": "{ \n \"compilerOptions\": {\n \"target\": \"es5\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"sourceMap\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"lib\": [ \"es2015\", \"dom\" ],\n \"noImplicitAny\": true,\n \"suppressImplicitAnyIndexErrors\": true\n }\n}" }, { "code": null, "e": 58342, "s": 58282, "text": "Following are some key points to note about the above code." }, { "code": null, "e": 58450, "s": 58342, "text": "The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript." }, { "code": null, "e": 58558, "s": 58450, "text": "The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript." }, { "code": null, "e": 58709, "s": 58558, "text": "The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true." }, { "code": null, "e": 58860, "s": 58709, "text": "The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true." }, { "code": null, "e": 59026, "s": 58860, "text": "The \"emitDecoratorMetadata\": true and \"experimentalDecorators\": true is required for Angular JS decorators. If not in place, Angular JS application will not compile." }, { "code": null, "e": 59192, "s": 59026, "text": "The \"emitDecoratorMetadata\": true and \"experimentalDecorators\": true is required for Angular JS decorators. If not in place, Angular JS application will not compile." }, { "code": null, "e": 59296, "s": 59192, "text": "This file contains information about Angular 2 project. Following are the typical settings in the file." }, { "code": null, "e": 61429, "s": 59296, "text": "{\n \"name\": \"angular-quickstart\",\n \"version\": \"1.0.0\",\n \"description\": \"QuickStart package.json from the documentation,\n supplemented with testing support\",\n \n \"scripts\": {\n \"build\": \"tsc -p src/\",\n \"build:watch\": \"tsc -p src/ -w\",\n \"build:e2e\": \"tsc -p e2e/\",\n \"serve\": \"lite-server -c=bs-config.json\",\n \"serve:e2e\": \"lite-server -c=bs-config.e2e.json\",\n \"prestart\": \"npm run build\",\n \"start\": \"concurrently \\\"npm run build:watch\\\" \\\"npm run serve\\\"\",\n \"pree2e\": \"npm run build:e2e\",\n \"e2e\": \"concurrently \\\"npm run serve:e2e\\\" \\\"npm run protractor\\\" \n --killothers --success first\",\n \"preprotractor\": \"webdriver-manager update\",\n \"protractor\": \"protractor protractor.config.js\",\n \"pretest\": \"npm run build\",\n \"test\": \"concurrently \\\"npm run build:watch\\\" \\\"karma start karma.conf.js\\\"\",\n \"pretest:once\": \"npm run build\",\n \"test:once\": \"karma start karma.conf.js --single-run\",\n \"lint\": \"tslint ./src/**/*.ts -t verbose\"\n },\n\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@angular/common\": \"~2.4.0\",\n \"@angular/compiler\": \"~2.4.0\",\n \"@angular/core\": \"~2.4.0\",\n \"@angular/forms\": \"~2.4.0\",\n \"@angular/http\": \"~2.4.0\",\n \"@angular/platform-browser\": \"~2.4.0\",\n \"@angular/platform-browser-dynamic\": \"~2.4.0\",\n \"@angular/router\": \"~3.4.0\",\n \"angular-in-memory-web-api\": \"~0.2.4\",\n \"systemjs\": \"0.19.40\",\n \"core-js\": \"^2.4.1\",\n \"rxjs\": \"5.0.1\",\n \"zone.js\": \"^0.7.4\"\n },\n\n \"devDependencies\": {\n \"concurrently\": \"^3.2.0\",\n \"lite-server\": \"^2.2.2\",\n \"typescript\": \"~2.0.10\",\n \"canonical-path\": \"0.0.2\",\n \"tslint\": \"^3.15.1\",\n \"lodash\": \"^4.16.4\",\n \"jasmine-core\": \"~2.4.1\",\n \"karma\": \"^1.3.0\",\n \"karma-chrome-launcher\": \"^2.0.0\",\n \"karma-cli\": \"^1.0.1\",\n \"karma-jasmine\": \"^1.0.2\",\n \"karma-jasmine-html-reporter\": \"^0.2.2\",\n \"protractor\": \"~4.0.14\",\n \"rimraf\": \"^2.5.4\",\n \"@types/node\": \"^6.0.46\",\n \"@types/jasmine\": \"2.5.36\"\n },\n \"repository\": {}\n}" }, { "code": null, "e": 61476, "s": 61429, "text": "Some key points to note about the above code −" }, { "code": null, "e": 61683, "s": 61476, "text": "There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application." }, { "code": null, "e": 61890, "s": 61683, "text": "There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application." }, { "code": null, "e": 62034, "s": 61890, "text": "The \"build:watch\": \"tsc -p src/ -w\" command is used to compile the typescript in the background by looking for changes in the typescript files." }, { "code": null, "e": 62178, "s": 62034, "text": "The \"build:watch\": \"tsc -p src/ -w\" command is used to compile the typescript in the background by looking for changes in the typescript files." }, { "code": null, "e": 62397, "s": 62178, "text": "This file contains the system files required for Angular JS application. This loads all the necessary script files without the need to add a script tag to the html pages. The typical files will have the following code." }, { "code": null, "e": 64008, "s": 62397, "text": "/** \n * System configuration for Angular samples \n * Adjust as necessary for your application needs. \n*/ \n(function (global) { \n System.config ({ \n paths: { \n // paths serve as alias \n 'npm:': 'node_modules/' \n }, \n \n // map tells the System loader where to look for things \n map: { \n // our app is within the app folder \n app: 'app', \n \n // angular bundles \n '@angular/core': 'npm:@angular/core/bundles/core.umd.js', \n '@angular/common': 'npm:@angular/common/bundles/common.umd.js', \n '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', \n '@angular/platform-browser': 'npm:@angular/platformbrowser/bundles/platform-browser.umd.js', \n '@angular/platform-browser-dynamic': \n 'npm:@angular/platform-browserdynamic/bundles/platform-browser-dynamic.umd.js', \n '@angular/http': 'npm:@angular/http/bundles/http.umd.js', \n '@angular/router': 'npm:@angular/router/bundles/router.umd.js', \n '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', \n \n // other libraries \n 'rxjs': 'npm:rxjs', \n 'angular-in-memory-web-api': \n 'npm:angular-in-memory-web-api/bundles/inmemory-web-api.umd.js' \n }, \n \n // packages tells the System loader how to load when no filename \n and/or no extension \n packages: { \n app: { \n defaultExtension: 'js' \n }, \n \n rxjs: { \n defaultExtension: 'js' \n } \n } \n \n }); \n})(this); " }, { "code": null, "e": 64055, "s": 64008, "text": "Some key points to note about the above code −" }, { "code": null, "e": 64152, "s": 64055, "text": "'npm:': 'node_modules/' tells the location in our project where all the npm modules are located." }, { "code": null, "e": 64249, "s": 64152, "text": "'npm:': 'node_modules/' tells the location in our project where all the npm modules are located." }, { "code": null, "e": 64337, "s": 64249, "text": "The mapping of app: 'app' tells the folder where all our applications files are loaded." }, { "code": null, "e": 64425, "s": 64337, "text": "The mapping of app: 'app' tells the folder where all our applications files are loaded." }, { "code": null, "e": 64572, "s": 64425, "text": "Angular 2 allows you to work with any third party controls. Once you decide on the control to implement, you need to perform the following steps −" }, { "code": null, "e": 64626, "s": 64572, "text": "Step 1 − Install the component using the npm command." }, { "code": null, "e": 64721, "s": 64626, "text": "For example, we will install the ng2-pagination third party control via the following command." }, { "code": null, "e": 64756, "s": 64721, "text": "npm install ng2-pagination --save\n" }, { "code": null, "e": 64826, "s": 64756, "text": "Once done, you will see that the component is successfully installed." }, { "code": null, "e": 64884, "s": 64826, "text": "Step 2 − Include the component in the app.module.ts file." }, { "code": null, "e": 65258, "s": 64884, "text": "import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { AppComponent } from './app.component';\nimport {Ng2PaginationModule} from 'ng2-pagination';\n\n@NgModule ({\n imports: [ BrowserModule,Ng2PaginationModule],\n declarations: [ AppComponent],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }" }, { "code": null, "e": 65331, "s": 65258, "text": "Step 3 − Finally, implement the component in your app.component.ts file." }, { "code": null, "e": 65748, "s": 65331, "text": "import { Component } from '@angular/core';\nimport {PaginatePipe, PaginationService} from 'ng2-pagination';\n\n@Component ({\n selector: 'my-app',\n template: '\n <ul>\n <li *ngFor = \"let item of collection | paginate: {\n itemsPerPage: 5, currentPage: p }\"> ... </li>\n </ul>\n <pagination-controls (pageChange) = \"p = $event\"></pagination-controls>\n '\n})\nexport class AppComponent { }" }, { "code": null, "e": 65843, "s": 65748, "text": "Step 4 − Save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 65955, "s": 65843, "text": "In the above picture, you can see that the images have been stored as One.jpg and two.jpg in the Images folder." }, { "code": null, "e": 66027, "s": 65955, "text": "Step 5 − Change the code of the app.component.ts file to the following." }, { "code": null, "e": 66409, "s": 66027, "text": "import {\n Component\n} from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n templateUrl: 'app/app.component.html'\n})\n\nexport class AppComponent {\n appTitle: string = 'Welcome';\n \n appList: any[] = [{\n \"ID\": \"1\",\n \"Name\": \"One\",\n \"url\": 'app/Images/One.jpg'\n },\n {\n \"ID\": \"2\",\n \"Name\": \"Two\",\n \"url\": 'app/Images/two.jpg'\n } ];\n}" }, { "code": null, "e": 66465, "s": 66409, "text": "Following points need to be noted about the above code." }, { "code": null, "e": 66581, "s": 66465, "text": "We are defining an array called appList which is of the type any. This is so that it can store any type of element." }, { "code": null, "e": 66697, "s": 66581, "text": "We are defining an array called appList which is of the type any. This is so that it can store any type of element." }, { "code": null, "e": 66774, "s": 66697, "text": "We are defining 2 elements. Each element has 3 properties, ID, Name and url." }, { "code": null, "e": 66851, "s": 66774, "text": "We are defining 2 elements. Each element has 3 properties, ID, Name and url." }, { "code": null, "e": 66914, "s": 66851, "text": "The URL for each element is the relative path to the 2 images." }, { "code": null, "e": 66977, "s": 66914, "text": "The URL for each element is the relative path to the 2 images." }, { "code": null, "e": 67077, "s": 66977, "text": "Step 6 − Make the following changes to the app/app.component.html file which is your template file." }, { "code": null, "e": 67228, "s": 67077, "text": "<div *ngFor = 'let lst of appList'> \n <ul> \n <li>{{lst.ID}}</li> \n <li>{{lst.Name}}</li> \n <img [src] = 'lst.url'> \n </ul> \n</div> " }, { "code": null, "e": 67288, "s": 67228, "text": "Following points need to be noted about the above program −" }, { "code": null, "e": 67377, "s": 67288, "text": "The ngFor directive is used to iterate through all the elements of the appList property." }, { "code": null, "e": 67466, "s": 67377, "text": "The ngFor directive is used to iterate through all the elements of the appList property." }, { "code": null, "e": 67535, "s": 67466, "text": "For each property, it is using the list element to display an image." }, { "code": null, "e": 67604, "s": 67535, "text": "For each property, it is using the list element to display an image." }, { "code": null, "e": 67697, "s": 67604, "text": "The src property of the img tag is then bounded to the url property of appList in our class." }, { "code": null, "e": 67790, "s": 67697, "text": "The src property of the img tag is then bounded to the url property of appList in our class." }, { "code": null, "e": 67983, "s": 67790, "text": "Step 7 − Save all the code changes and refresh the browser, you will get the following output. From the output, you can clearly see that the images have been picked up and shown in the output." }, { "code": null, "e": 68081, "s": 67983, "text": "In Angular JS, it very easy to display the value of the properties of the class in the HTML form." }, { "code": null, "e": 68253, "s": 68081, "text": "Let�s take an example and understand more about Data Display. In our example, we will look at displaying the values of the various properties in our class in an HTML page." }, { "code": null, "e": 68325, "s": 68253, "text": "Step 1 − Change the code of the app.component.ts file to the following." }, { "code": null, "e": 68584, "s": 68325, "text": "import {\n Component\n} from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n templateUrl: 'app/app.component.html'\n})\n\nexport class AppComponent {\n TutorialName: string = 'Angular JS2';\n appList: string[] = [\"Binding\", \"Display\", \"Services\"];\n}" }, { "code": null, "e": 68640, "s": 68584, "text": "Following points need to be noted about the above code." }, { "code": null, "e": 68706, "s": 68640, "text": "We are defining an array called appList which of the type string." }, { "code": null, "e": 68772, "s": 68706, "text": "We are defining an array called appList which of the type string." }, { "code": null, "e": 68868, "s": 68772, "text": "We are defining 3 string elements as part of the array which is Binding, Display, and Services." }, { "code": null, "e": 68964, "s": 68868, "text": "We are defining 3 string elements as part of the array which is Binding, Display, and Services." }, { "code": null, "e": 69048, "s": 68964, "text": "We have also defined a property called TutorialName which has a value of Angular 2." }, { "code": null, "e": 69132, "s": 69048, "text": "We have also defined a property called TutorialName which has a value of Angular 2." }, { "code": null, "e": 69232, "s": 69132, "text": "Step 2 − Make the following changes to the app/app.component.html file which is your template file." }, { "code": null, "e": 69422, "s": 69232, "text": "<div>\n The name of this Tutorial is {{TutorialName}}<br>\n The first Topic is {{appList[0]}}<br>\n The second Topic is {{appList[1]}}<br>\n The third Topic is {{appList[2]}}<br>\n</div>" }, { "code": null, "e": 69478, "s": 69422, "text": "Following points need to be noted about the above code." }, { "code": null, "e": 69584, "s": 69478, "text": "We are referencing the TutorialName property to tell �what is the name of the tutorial in our HTML page�." }, { "code": null, "e": 69690, "s": 69584, "text": "We are referencing the TutorialName property to tell �what is the name of the tutorial in our HTML page�." }, { "code": null, "e": 69779, "s": 69690, "text": "We are using the index value for the array to display each of the 3 topics in our array." }, { "code": null, "e": 69868, "s": 69779, "text": "We are using the index value for the array to display each of the 3 topics in our array." }, { "code": null, "e": 70073, "s": 69868, "text": "Step 3 − Save all the code changes and refresh the browser, you will get the below output. From the output, you can clearly see that the data is displayed as per the values of the properties in the class." }, { "code": null, "e": 70229, "s": 70073, "text": "Another simple example, which is binding on the fly is the use of the input html tag. It just displays the data as the data is being typed in the html tag." }, { "code": null, "e": 70320, "s": 70229, "text": "Make the following changes to the app/app.component.html file which is your template file." }, { "code": null, "e": 70412, "s": 70320, "text": "<div>\n <input [value] = \"name\" (input) = \"name = $event.target.value\">\n {{name}}\n</div>" }, { "code": null, "e": 70468, "s": 70412, "text": "Following points need to be noted about the above code." }, { "code": null, "e": 70575, "s": 70468, "text": "[value] = �username� − This is used to bind the expression username to the input element�s value property." }, { "code": null, "e": 70682, "s": 70575, "text": "[value] = �username� − This is used to bind the expression username to the input element�s value property." }, { "code": null, "e": 70791, "s": 70682, "text": "(input) = �expression� − This a declarative way of binding an expression to the input element�s input event." }, { "code": null, "e": 70900, "s": 70791, "text": "(input) = �expression� − This a declarative way of binding an expression to the input element�s input event." }, { "code": null, "e": 70998, "s": 70900, "text": "username = $event.target.value − The expression that gets executed when the input event is fired." }, { "code": null, "e": 71096, "s": 70998, "text": "username = $event.target.value − The expression that gets executed when the input event is fired." }, { "code": null, "e": 71201, "s": 71096, "text": "$event − An expression exposed in event bindings by Angular, which has the value of the event�s payload." }, { "code": null, "e": 71306, "s": 71201, "text": "$event − An expression exposed in event bindings by Angular, which has the value of the event�s payload." }, { "code": null, "e": 71401, "s": 71306, "text": "When you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 71500, "s": 71401, "text": "Now, type something in the Input box such as �Tutorialspoint�. The output will change accordingly." }, { "code": null, "e": 71711, "s": 71500, "text": "In Angular 2, events such as button click or any other sort of events can also be handled very easily. The events get triggered from the html page and are sent across to Angular JS class for further processing." }, { "code": null, "e": 71972, "s": 71711, "text": "Let�s look at an example of how we can achieve event handling. In our example, we will look at displaying a click button and a status property. Initially, the status property will be true. When the button is clicked, the status property will then become false." }, { "code": null, "e": 72044, "s": 71972, "text": "Step 1 − Change the code of the app.component.ts file to the following." }, { "code": null, "e": 72295, "s": 72044, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) \n\nexport class AppComponent { \n Status: boolean = true; \n clicked(event) { \n this.Status = false; \n } \n}" }, { "code": null, "e": 72351, "s": 72295, "text": "Following points need to be noted about the above code." }, { "code": null, "e": 72437, "s": 72351, "text": "We are defining a variable called status of the type Boolean which is initially true." }, { "code": null, "e": 72523, "s": 72437, "text": "We are defining a variable called status of the type Boolean which is initially true." }, { "code": null, "e": 72716, "s": 72523, "text": "Next, we are defining the clicked function which will be called whenever our button is clicked on our html page. In the function, we change the value of the Status property from true to false." }, { "code": null, "e": 72909, "s": 72716, "text": "Next, we are defining the clicked function which will be called whenever our button is clicked on our html page. In the function, we change the value of the Status property from true to false." }, { "code": null, "e": 73009, "s": 72909, "text": "Step 2 − Make the following changes to the app/app.component.html file, which is the template file." }, { "code": null, "e": 73088, "s": 73009, "text": "<div> \n {{Status}} \n <button (click) = \"clicked()\">Click</button> \n</div> " }, { "code": null, "e": 73144, "s": 73088, "text": "Following points need to be noted about the above code." }, { "code": null, "e": 73220, "s": 73144, "text": "We are first just displaying the value of the Status property of our class." }, { "code": null, "e": 73296, "s": 73220, "text": "We are first just displaying the value of the Status property of our class." }, { "code": null, "e": 73459, "s": 73296, "text": "Then are defining the button html tag with the value of Click. We then ensure that the click event of the button gets triggered to the clicked event in our class." }, { "code": null, "e": 73622, "s": 73459, "text": "Then are defining the button html tag with the value of Click. We then ensure that the click event of the button gets triggered to the clicked event in our class." }, { "code": null, "e": 73717, "s": 73622, "text": "Step 3 − Save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 73785, "s": 73717, "text": "Step 4 − Click the Click button, you will get the following output." }, { "code": null, "e": 73862, "s": 73785, "text": "Angular 2 has a lot of filters and pipes that can be used to transform data." }, { "code": null, "e": 73914, "s": 73862, "text": "This is used to convert the input to all lowercase." }, { "code": null, "e": 73942, "s": 73914, "text": "Propertyvalue | lowercase \n" }, { "code": null, "e": 73947, "s": 73942, "text": "None" }, { "code": null, "e": 73998, "s": 73947, "text": "The property value will be converted to lowercase." }, { "code": null, "e": 74071, "s": 73998, "text": "First ensure the following code is present in the app.component.ts file." }, { "code": null, "e": 74340, "s": 74071, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) \n\nexport class AppComponent { \n TutorialName: string = 'Angular JS2'; \n appList: string[] = [\"Binding\", \"Display\", \"Services\"]; \n}" }, { "code": null, "e": 74419, "s": 74340, "text": "Next, ensure the following code is present in the app/app.component.html file." }, { "code": null, "e": 74651, "s": 74419, "text": "<div> \n The name of this Tutorial is {{TutorialName}}<br> \n The first Topic is {{appList[0] | lowercase}}<br> \n The second Topic is {{appList[1] | lowercase}}<br> \n The third Topic is {{appList[2]| lowercase}}<br> \n</div> " }, { "code": null, "e": 74746, "s": 74651, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 74798, "s": 74746, "text": "This is used to convert the input to all uppercase." }, { "code": null, "e": 74826, "s": 74798, "text": "Propertyvalue | uppercase \n" }, { "code": null, "e": 74832, "s": 74826, "text": "None." }, { "code": null, "e": 74883, "s": 74832, "text": "The property value will be converted to uppercase." }, { "code": null, "e": 74956, "s": 74883, "text": "First ensure the following code is present in the app.component.ts file." }, { "code": null, "e": 75225, "s": 74956, "text": "import { \n Component \n} from '@angular/core';\n\n@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) \n\nexport class AppComponent { \n TutorialName: string = 'Angular JS2'; \n appList: string[] = [\"Binding\", \"Display\", \"Services\"]; \n} " }, { "code": null, "e": 75304, "s": 75225, "text": "Next, ensure the following code is present in the app/app.component.html file." }, { "code": null, "e": 75538, "s": 75304, "text": "<div> \n The name of this Tutorial is {{TutorialName}}<br> \n The first Topic is {{appList[0] | uppercase }}<br> \n The second Topic is {{appList[1] | uppercase }}<br> \n The third Topic is {{appList[2]| uppercase }}<br> \n</div>" }, { "code": null, "e": 75633, "s": 75538, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 75694, "s": 75633, "text": "This is used to slice a piece of data from the input string." }, { "code": null, "e": 75728, "s": 75694, "text": "Propertyvalue | slice:start:end \n" }, { "code": null, "e": 75801, "s": 75728, "text": "start − This is the starting position from where the slice should start." }, { "code": null, "e": 75874, "s": 75801, "text": "start − This is the starting position from where the slice should start." }, { "code": null, "e": 75943, "s": 75874, "text": "end − This is the starting position from where the slice should end." }, { "code": null, "e": 76012, "s": 75943, "text": "end − This is the starting position from where the slice should end." }, { "code": null, "e": 76084, "s": 76012, "text": "The property value will be sliced based on the start and end positions." }, { "code": null, "e": 76156, "s": 76084, "text": "First ensure the following code is present in the app.component.ts file" }, { "code": null, "e": 76415, "s": 76156, "text": "import {\n Component\n} from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n templateUrl: 'app/app.component.html'\n})\n\nexport class AppComponent {\n TutorialName: string = 'Angular JS2';\n appList: string[] = [\"Binding\", \"Display\", \"Services\"];\n}" }, { "code": null, "e": 76494, "s": 76415, "text": "Next, ensure the following code is present in the app/app.component.html file." }, { "code": null, "e": 76726, "s": 76494, "text": "<div> \n The name of this Tutorial is {{TutorialName}}<br> \n The first Topic is {{appList[0] | slice:1:2}}<br> \n The second Topic is {{appList[1] | slice:1:3}}<br> \n The third Topic is {{appList[2]| slice:2:3}}<br> \n</div> " }, { "code": null, "e": 76821, "s": 76726, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 76878, "s": 76821, "text": "This is used to convert the input string to date format." }, { "code": null, "e": 76914, "s": 76878, "text": "Propertyvalue | date:�dateformat� \n" }, { "code": null, "e": 76992, "s": 76914, "text": "dateformat − This is the date format the input string should be converted to." }, { "code": null, "e": 77045, "s": 76992, "text": "The property value will be converted to date format." }, { "code": null, "e": 77118, "s": 77045, "text": "First ensure the following code is present in the app.component.ts file." }, { "code": null, "e": 77322, "s": 77118, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) \n\nexport class AppComponent { \n newdate = new Date(2016, 3, 15);\n}" }, { "code": null, "e": 77401, "s": 77322, "text": "Next, ensure the following code is present in the app/app.component.html file." }, { "code": null, "e": 77483, "s": 77401, "text": "<div> \n The date of this Tutorial is {{newdate | date:\"MM/dd/yy\"}}<br> \n</div>" }, { "code": null, "e": 77578, "s": 77483, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 77639, "s": 77578, "text": "This is used to convert the input string to currency format." }, { "code": null, "e": 77666, "s": 77639, "text": "Propertyvalue | currency \n" }, { "code": null, "e": 77672, "s": 77666, "text": "None." }, { "code": null, "e": 77729, "s": 77672, "text": "The property value will be converted to currency format." }, { "code": null, "e": 77802, "s": 77729, "text": "First ensure the following code is present in the app.component.ts file." }, { "code": null, "e": 77999, "s": 77802, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) \n\nexport class AppComponent { \n newValue: number = 123; \n} " }, { "code": null, "e": 78078, "s": 77999, "text": "Next, ensure the following code is present in the app/app.component.html file." }, { "code": null, "e": 78162, "s": 78078, "text": "<div> \n The currency of this Tutorial is {{newValue | currency}}<br> \n</div>" }, { "code": null, "e": 78257, "s": 78162, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 78320, "s": 78257, "text": "This is used to convert the input string to percentage format." }, { "code": null, "e": 78346, "s": 78320, "text": "Propertyvalue | percent \n" }, { "code": null, "e": 78351, "s": 78346, "text": "None" }, { "code": null, "e": 78410, "s": 78351, "text": "The property value will be converted to percentage format." }, { "code": null, "e": 78483, "s": 78410, "text": "First ensure the following code is present in the app.component.ts file." }, { "code": null, "e": 78679, "s": 78483, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) \n\nexport class AppComponent { \n newValue: number = 30; \n} " }, { "code": null, "e": 78758, "s": 78679, "text": "Next, ensure the following code is present in the app/app.component.html file." }, { "code": null, "e": 78820, "s": 78758, "text": "<div>\n The percentage is {{newValue | percent}}<br> \n</div>" }, { "code": null, "e": 78915, "s": 78820, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 78974, "s": 78915, "text": "There is another variation of the percent pipe as follows." }, { "code": null, "e": 79060, "s": 78974, "text": "Propertyvalue | percent: �{minIntegerDigits}.{minFractionDigits}{maxFractionDigits}�\n" }, { "code": null, "e": 79125, "s": 79060, "text": "minIntegerDigits − This is the minimum number of Integer digits." }, { "code": null, "e": 79190, "s": 79125, "text": "minIntegerDigits − This is the minimum number of Integer digits." }, { "code": null, "e": 79257, "s": 79190, "text": "minFractionDigits − This is the minimum number of fraction digits." }, { "code": null, "e": 79324, "s": 79257, "text": "minFractionDigits − This is the minimum number of fraction digits." }, { "code": null, "e": 79391, "s": 79324, "text": "maxFractionDigits − This is the maximum number of fraction digits." }, { "code": null, "e": 79458, "s": 79391, "text": "maxFractionDigits − This is the maximum number of fraction digits." }, { "code": null, "e": 79516, "s": 79458, "text": "The property value will be converted to percentage format" }, { "code": null, "e": 79589, "s": 79516, "text": "First ensure the following code is present in the app.component.ts file." }, { "code": null, "e": 79785, "s": 79589, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) \n\nexport class AppComponent { \n newValue: number = 0.3; \n}" }, { "code": null, "e": 79864, "s": 79785, "text": "Next, ensure the following code is present in the app/app.component.html file." }, { "code": null, "e": 79937, "s": 79864, "text": "<div> \n The percentage is {{newValue | percent:'2.2-5'}}<br> \n</div> " }, { "code": null, "e": 80032, "s": 79937, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 80143, "s": 80032, "text": "Angular 2 also has the facility to create custom pipes. The general way to define a custom pipe is as follows." }, { "code": null, "e": 80322, "s": 80143, "text": "import { Pipe, PipeTransform } from '@angular/core'; \n@Pipe({name: 'Pipename'}) \n\nexport class Pipeclass implements PipeTransform { \n transform(parameters): returntype { } \n} " }, { "code": null, "e": 80329, "s": 80322, "text": "Where," }, { "code": null, "e": 80372, "s": 80329, "text": "'Pipename' − This is the name of the pipe." }, { "code": null, "e": 80415, "s": 80372, "text": "'Pipename' − This is the name of the pipe." }, { "code": null, "e": 80482, "s": 80415, "text": "Pipeclass − This is name of the class assigned to the custom pipe." }, { "code": null, "e": 80549, "s": 80482, "text": "Pipeclass − This is name of the class assigned to the custom pipe." }, { "code": null, "e": 80605, "s": 80549, "text": "Transform − This is the function to work with the pipe." }, { "code": null, "e": 80661, "s": 80605, "text": "Transform − This is the function to work with the pipe." }, { "code": null, "e": 80728, "s": 80661, "text": "Parameters − This are the parameters which are passed to the pipe." }, { "code": null, "e": 80795, "s": 80728, "text": "Parameters − This are the parameters which are passed to the pipe." }, { "code": null, "e": 80845, "s": 80795, "text": "Returntype − This is the return type of the pipe." }, { "code": null, "e": 80895, "s": 80845, "text": "Returntype − This is the return type of the pipe." }, { "code": null, "e": 81000, "s": 80895, "text": "Let�s create a custom pipe that multiplies 2 numbers. We will then use that pipe in our component class." }, { "code": null, "e": 81057, "s": 81000, "text": "Step 1 − First, create a file called multiplier.pipe.ts." }, { "code": null, "e": 81118, "s": 81057, "text": "Step 2 − Place the following code in the above created file." }, { "code": null, "e": 81408, "s": 81118, "text": "import { \n Pipe, \n PipeTransform \n} from '@angular/core'; \n\n@Pipe ({ \n name: 'Multiplier' \n}) \n\nexport class MultiplierPipe implements PipeTransform { \n transform(value: number, multiply: string): number { \n let mul = parseFloat(multiply); \n return mul * value \n } \n} " }, { "code": null, "e": 81464, "s": 81408, "text": "Following points need to be noted about the above code." }, { "code": null, "e": 81523, "s": 81464, "text": "We are first importing the Pipe and PipeTransform modules." }, { "code": null, "e": 81582, "s": 81523, "text": "We are first importing the Pipe and PipeTransform modules." }, { "code": null, "e": 81639, "s": 81582, "text": "Then, we are creating a Pipe with the name 'Multiplier'." }, { "code": null, "e": 81696, "s": 81639, "text": "Then, we are creating a Pipe with the name 'Multiplier'." }, { "code": null, "e": 81778, "s": 81696, "text": "Creating a class called MultiplierPipe that implements the PipeTransform module. " }, { "code": null, "e": 81860, "s": 81778, "text": "Creating a class called MultiplierPipe that implements the PipeTransform module. " }, { "code": null, "e": 81981, "s": 81860, "text": "The transform function will then take in the value and multiple parameter and output the multiplication of both numbers." }, { "code": null, "e": 82102, "s": 81981, "text": "The transform function will then take in the value and multiple parameter and output the multiplication of both numbers." }, { "code": null, "e": 82167, "s": 82102, "text": "Step 3 − In the app.component.ts file, place the following code." }, { "code": null, "e": 82351, "s": 82167, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n template: '<p>Multiplier: {{2 | Multiplier: 10}}</p>' \n}) \nexport class AppComponent { } " }, { "code": null, "e": 82403, "s": 82351, "text": "Note − In our template, we use our new custom pipe." }, { "code": null, "e": 82475, "s": 82403, "text": "Step 4 − Ensure the following code is placed in the app.module.ts file." }, { "code": null, "e": 82841, "s": 82475, "text": "import {\n NgModule\n} from '@angular/core';\n\nimport {\n BrowserModule\n} from '@angular/platform-browser';\n\nimport {\n AppComponent\n} from './app.component';\n\nimport {\n MultiplierPipe\n} from './multiplier.pipe'\n\n@NgModule ({\n imports: [BrowserModule],\n declarations: [AppComponent, MultiplierPipe],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule {}" }, { "code": null, "e": 82897, "s": 82841, "text": "Following things need to be noted about the above code." }, { "code": null, "e": 82953, "s": 82897, "text": "We need to ensure to include our MultiplierPipe module." }, { "code": null, "e": 83009, "s": 82953, "text": "We need to ensure to include our MultiplierPipe module." }, { "code": null, "e": 83076, "s": 83009, "text": "We also need to ensure it is included in the declarations section." }, { "code": null, "e": 83143, "s": 83076, "text": "We also need to ensure it is included in the declarations section." }, { "code": null, "e": 83238, "s": 83143, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 83386, "s": 83238, "text": "In Angular 2, you can make the use of DOM element structure of HTML to change the values of the elements at run time. Let�s look at some in detail." }, { "code": null, "e": 83441, "s": 83386, "text": "In the app.component.ts file place the following code." }, { "code": null, "e": 83707, "s": 83441, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n template: ' \n <div> \n <input [value] = \"name\" (input) = \"name = $event.target.value\"> \n {{name}} \n </div> \n ' \n}) \nexport class AppComponent { }" }, { "code": null, "e": 83763, "s": 83707, "text": "Following things need to be noted about the above code." }, { "code": null, "e": 83870, "s": 83763, "text": "[value] = �username� − This is used to bind the expression username to the input element�s value property." }, { "code": null, "e": 83977, "s": 83870, "text": "[value] = �username� − This is used to bind the expression username to the input element�s value property." }, { "code": null, "e": 84086, "s": 83977, "text": "(input) = �expression� − This a declarative way of binding an expression to the input element�s input event." }, { "code": null, "e": 84195, "s": 84086, "text": "(input) = �expression� − This a declarative way of binding an expression to the input element�s input event." }, { "code": null, "e": 84293, "s": 84195, "text": "username = $event.target.value − The expression that gets executed when the input event is fired." }, { "code": null, "e": 84391, "s": 84293, "text": "username = $event.target.value − The expression that gets executed when the input event is fired." }, { "code": null, "e": 84499, "s": 84391, "text": "$event − Is an expression exposed in event bindings by Angular, which has the value of the event�s payload." }, { "code": null, "e": 84607, "s": 84499, "text": "$event − Is an expression exposed in event bindings by Angular, which has the value of the event�s payload." }, { "code": null, "e": 84702, "s": 84607, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 84799, "s": 84702, "text": "You can now type anything and the same input will reflect in the text next to the Input control." }, { "code": null, "e": 84854, "s": 84799, "text": "In the app.component.ts file place the following code." }, { "code": null, "e": 85149, "s": 84854, "text": "import {\n Component\n} from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: '<button (click) = \"onClickMe()\"> Click Me </button> {{clickMessage}}'\n})\n\nexport class AppComponent {\n clickMessage = 'Hello';\n onClickMe() {\n this.clickMessage = 'This tutorial!';\n }\n}" }, { "code": null, "e": 85244, "s": 85149, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 85313, "s": 85244, "text": "When you hit the Click Me button, you will get the following output." }, { "code": null, "e": 85451, "s": 85313, "text": "Angular 2 application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application." }, { "code": null, "e": 85547, "s": 85451, "text": "The following diagram shows the entire processes in the lifecycle of the Angular 2 application." }, { "code": null, "e": 85598, "s": 85547, "text": "Following is a description of each lifecycle hook." }, { "code": null, "e": 85689, "s": 85598, "text": "ngOnChanges − When the value of a data bound property changes, then this method is called." }, { "code": null, "e": 85780, "s": 85689, "text": "ngOnChanges − When the value of a data bound property changes, then this method is called." }, { "code": null, "e": 85925, "s": 85780, "text": "ngOnInit − This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens." }, { "code": null, "e": 86070, "s": 85925, "text": "ngOnInit − This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens." }, { "code": null, "e": 86177, "s": 86070, "text": "ngDoCheck − This is for the detection and to act on changes that Angular can't or won't detect on its own." }, { "code": null, "e": 86284, "s": 86177, "text": "ngDoCheck − This is for the detection and to act on changes that Angular can't or won't detect on its own." }, { "code": null, "e": 86399, "s": 86284, "text": "ngAfterContentInit − This is called in response after Angular projects external content into the component's view." }, { "code": null, "e": 86514, "s": 86399, "text": "ngAfterContentInit − This is called in response after Angular projects external content into the component's view." }, { "code": null, "e": 86628, "s": 86514, "text": "ngAfterContentChecked − This is called in response after Angular checks the content projected into the component." }, { "code": null, "e": 86742, "s": 86628, "text": "ngAfterContentChecked − This is called in response after Angular checks the content projected into the component." }, { "code": null, "e": 86852, "s": 86742, "text": "ngAfterViewInit − This is called in response after Angular initializes the component's views and child views." }, { "code": null, "e": 86962, "s": 86852, "text": "ngAfterViewInit − This is called in response after Angular initializes the component's views and child views." }, { "code": null, "e": 87070, "s": 86962, "text": "ngAfterViewChecked − This is called in response after Angular checks the component's views and child views." }, { "code": null, "e": 87178, "s": 87070, "text": "ngAfterViewChecked − This is called in response after Angular checks the component's views and child views." }, { "code": null, "e": 87272, "s": 87178, "text": "ngOnDestroy − This is the cleanup phase just before Angular destroys the directive/component." }, { "code": null, "e": 87366, "s": 87272, "text": "ngOnDestroy − This is the cleanup phase just before Angular destroys the directive/component." }, { "code": null, "e": 87482, "s": 87366, "text": "Following is an example of implementing one lifecycle hook. In the app.component.ts file, place the following code." }, { "code": null, "e": 87719, "s": 87482, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n template: '<div> {{values}} </div> ' \n}) \n\nexport class AppComponent { \n values = ''; \n ngOnInit() { \n this.values = \"Hello\"; \n } \n}" }, { "code": null, "e": 87878, "s": 87719, "text": "In the above program, we are calling the ngOnInit lifecycle hook to specifically mention that the value of the this.values parameter should be set to �Hello�." }, { "code": null, "e": 87973, "s": 87878, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 88221, "s": 87973, "text": "In Angular JS, it is possible to nest containers inside each other. The outside container is known as the parent container and the inner one is known as the child container. Let�s look at an example on how to achieve this. Following are the steps." }, { "code": null, "e": 88298, "s": 88221, "text": "Step 1 − Create a ts file for the child container called child.component.ts." }, { "code": null, "e": 88372, "s": 88298, "text": "Step 2 − In the file created in the above step, place the following code." }, { "code": null, "e": 88614, "s": 88372, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'child-app', \n template: '<div> {{values}} </div> ' \n}) \n\nexport class ChildComponent { \n values = ''; \n ngOnInit() { \n this.values = \"Hello\"; \n } \n}" }, { "code": null, "e": 88685, "s": 88614, "text": "The above code sets the value of the parameter this.values to �Hello�." }, { "code": null, "e": 88750, "s": 88685, "text": "Step 3 − In the app.component.ts file, place the following code." }, { "code": null, "e": 88974, "s": 88750, "text": "import { \n Component \n} from '@angular/core'; \n\nimport { \n ChildComponent \n} from './child.component'; \n\n@Component ({ \n selector: 'my-app', \n template: '<child-app></child-app> ' \n}) \n\nexport class AppComponent { }" }, { "code": null, "e": 89176, "s": 88974, "text": "In the above code, notice that we are now calling the import statement to import the child.component module. Also we are calling the <child-app> selector from the child component to our main component." }, { "code": null, "e": 89273, "s": 89176, "text": "Step 4 − Next, we need to ensure the child component is also included in the app.module.ts file." }, { "code": null, "e": 89734, "s": 89273, "text": "import { \n NgModule \n} from '@angular/core'; \n\nimport { \n BrowserModule \n} from '@angular/platform-browser'; \n\nimport { \n AppComponent \n} from './app.component'; \n\nimport { \n MultiplierPipe \n} from './multiplier.pipe' \n\nimport { \n ChildComponent \n} from './child.component'; \n\n@NgModule ({ \n imports: [BrowserModule], \n declarations: [AppComponent, MultiplierPipe, ChildComponent], \n bootstrap: [AppComponent] \n}) \n\nexport class AppModule {}" }, { "code": null, "e": 89829, "s": 89734, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 90093, "s": 89829, "text": "A service is used when a common functionality needs to be provided to various modules. For example, we could have a database functionality that could be reused among various modules. And hence you could create a service that could have the database functionality." }, { "code": null, "e": 90165, "s": 90093, "text": "The following key steps need to be carried out when creating a service." }, { "code": null, "e": 90348, "s": 90165, "text": "Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module." }, { "code": null, "e": 90397, "s": 90348, "text": "@Injectable() \n export class classname { \n} \n" }, { "code": null, "e": 90556, "s": 90397, "text": "Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator." }, { "code": null, "e": 90604, "s": 90556, "text": "@Component ({ \n providers : [classname] \n})\n" }, { "code": null, "e": 90687, "s": 90604, "text": "Let�s look at an example on how to achieve this. Following are the steps involved." }, { "code": null, "e": 90752, "s": 90687, "text": "Step 1 − Create a ts file for the service called app.service.ts." }, { "code": null, "e": 90813, "s": 90752, "text": "Step 2 − Place the following code in the file created above." }, { "code": null, "e": 90968, "s": 90813, "text": "import { \n Injectable \n} from '@angular/core'; \n\n@Injectable()\nexport class appService { \n getApp(): string { \n return \"Hello world\"; \n } \n} " }, { "code": null, "e": 91027, "s": 90968, "text": "Following points need to be noted about the above program." }, { "code": null, "e": 91094, "s": 91027, "text": "The Injectable decorator is imported from the angular/core module." }, { "code": null, "e": 91161, "s": 91094, "text": "The Injectable decorator is imported from the angular/core module." }, { "code": null, "e": 91252, "s": 91161, "text": "We are creating a class called appService that is decorated with the Injectable decorator." }, { "code": null, "e": 91343, "s": 91252, "text": "We are creating a class called appService that is decorated with the Injectable decorator." }, { "code": null, "e": 91444, "s": 91343, "text": "We are creating a simple function called getApp, which returns a simple string called �Hello world�." }, { "code": null, "e": 91545, "s": 91444, "text": "We are creating a simple function called getApp, which returns a simple string called �Hello world�." }, { "code": null, "e": 91610, "s": 91545, "text": "Step 3 − In the app.component.ts file, place the following code." }, { "code": null, "e": 92012, "s": 91610, "text": "import { \n Component \n} from '@angular/core'; \n\nimport { \n appService \n} from './app.service'; \n\n@Component ({ \n selector: 'demo-app', \n template: '<div>{{value}}</div>', \n providers: [appService] \n}) \n\nexport class AppComponent { \n value: string = \"\"; \n constructor(private _appService: appService) { } \n\n ngOnInit(): void { \n this.value = this._appService.getApp(); \n } \n} " }, { "code": null, "e": 92071, "s": 92012, "text": "Following points need to be noted about the above program." }, { "code": null, "e": 92138, "s": 92071, "text": "First, we import our appService module in the appComponent module." }, { "code": null, "e": 92205, "s": 92138, "text": "First, we import our appService module in the appComponent module." }, { "code": null, "e": 92265, "s": 92205, "text": "Then, we register the service as a provider in this module." }, { "code": null, "e": 92325, "s": 92265, "text": "Then, we register the service as a provider in this module." }, { "code": null, "e": 92470, "s": 92325, "text": "In the constructor, we define a variable called _appService of the type appService so that it can be called anywhere in the appComponent module." }, { "code": null, "e": 92615, "s": 92470, "text": "In the constructor, we define a variable called _appService of the type appService so that it can be called anywhere in the appComponent module." }, { "code": null, "e": 92777, "s": 92615, "text": "As an example, in the ngOnInit lifecyclehook, we called the getApp function of the service and assign the output to the value property of the AppComponent class." }, { "code": null, "e": 92939, "s": 92777, "text": "As an example, in the ngOnInit lifecyclehook, we called the getApp function of the service and assign the output to the value property of the AppComponent class." }, { "code": null, "e": 93034, "s": 92939, "text": "Once you save all the code changes and refresh the browser, you will get the following output." }, { "code": null, "e": 93069, "s": 93034, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 93083, "s": 93069, "text": " Anadi Sharma" }, { "code": null, "e": 93118, "s": 93083, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 93132, "s": 93118, "text": " Anadi Sharma" }, { "code": null, "e": 93167, "s": 93132, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 93187, "s": 93167, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 93222, "s": 93187, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 93239, "s": 93222, "text": " Frahaan Hussain" }, { "code": null, "e": 93272, "s": 93239, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 93284, "s": 93272, "text": " Senol Atac" }, { "code": null, "e": 93319, "s": 93284, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 93331, "s": 93319, "text": " Senol Atac" }, { "code": null, "e": 93338, "s": 93331, "text": " Print" }, { "code": null, "e": 93349, "s": 93338, "text": " Add Notes" } ]
C# program to convert binary string to Integer
Use the Convert.ToInt32 class to fulfill your purpose of converting a binary string to an integer. Let’s say our binary string is − string str = "1001"; Now each char is parsed − try { //Parse each char of the passed string val = Int32.Parse(str1[i].ToString()); if (val == 1) result += (int) Math.Pow(2, str1.Length - 1 - i); else if (val > 1) throw new Exception("Invalid!"); } catch { throw new Exception("Invalid!"); } Check the above for each character in the passed string i.e. “100” using a for a loop. Find the length of the string using the length() method − str1.Length You can try to run the following code to convert a binary string to an integer in C#. Live Demo using System; class Program { static void Main() { string str = "1001"; Console.WriteLine("Integer:"+ConvertClass.Convert(str)); } } public static class ConvertClass { public static int Convert(string str1) { if (str1 == "") throw new Exception("Invalid input"); int val = 0, res = 0; for (int i = 0; i < str1.Length; i++) { try { val = Int32.Parse(str1[i].ToString()); if (val == 1) res += (int)Math.Pow(2, str1.Length - 1 - i); else if (val > 1) throw new Exception("Invalid!"); } catch { throw new Exception("Invalid!"); } } return res; } } Integer:9
[ { "code": null, "e": 1161, "s": 1062, "text": "Use the Convert.ToInt32 class to fulfill your purpose of converting a binary string to an integer." }, { "code": null, "e": 1194, "s": 1161, "text": "Let’s say our binary string is −" }, { "code": null, "e": 1215, "s": 1194, "text": "string str = \"1001\";" }, { "code": null, "e": 1241, "s": 1215, "text": "Now each char is parsed −" }, { "code": null, "e": 1512, "s": 1241, "text": "try {\n //Parse each char of the passed string\n val = Int32.Parse(str1[i].ToString());\n if (val == 1)\n result += (int) Math.Pow(2, str1.Length - 1 - i);\n else if (val > 1)\n throw new Exception(\"Invalid!\");\n} catch {\n throw new Exception(\"Invalid!\");\n}" }, { "code": null, "e": 1657, "s": 1512, "text": "Check the above for each character in the passed string i.e. “100” using a for a loop. Find the length of the string using the length() method −" }, { "code": null, "e": 1669, "s": 1657, "text": "str1.Length" }, { "code": null, "e": 1755, "s": 1669, "text": "You can try to run the following code to convert a binary string to an integer in C#." }, { "code": null, "e": 1765, "s": 1755, "text": "Live Demo" }, { "code": null, "e": 2477, "s": 1765, "text": "using System;\nclass Program {\n static void Main() {\n string str = \"1001\";\n Console.WriteLine(\"Integer:\"+ConvertClass.Convert(str));\n }\n}\npublic static class ConvertClass {\n public static int Convert(string str1) {\n if (str1 == \"\")\n throw new Exception(\"Invalid input\");\n int val = 0, res = 0;\n for (int i = 0; i < str1.Length; i++) {\n try {\n val = Int32.Parse(str1[i].ToString());\n if (val == 1)\n res += (int)Math.Pow(2, str1.Length - 1 - i);\n else if (val > 1)\n throw new Exception(\"Invalid!\");\n } catch {\n throw new Exception(\"Invalid!\");\n }\n }\n return res;\n }\n}" }, { "code": null, "e": 2487, "s": 2477, "text": "Integer:9" } ]
Java Math log() method with example - GeeksforGeeks
23 Mar, 2018 The java.lang.Math.log() method returns the natural logarithm (base e) of a double value as a parameter. There are various cases : If the argument is NaN or less than zero, then the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument is positive zero or negative zero, then the result is negative infinity. Syntax : public static double log(double a) Parameter : a : User input Return : This method returns the value ln a. Example :To show working of java.lang.Math.log() method. // Java program to demonstrate working// of java.lang.Math.log() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = -2.55; double b = 1.0 / 0; double c = 0, d = 145.256; // negative integer as argument, output NAN System.out.println(Math.log(a)); // positive infinity as argument, output Infinity System.out.println(Math.log(b)); // positive zero as argument, output -Infinity System.out.println(Math.log(c)); // positive double as argument System.out.println(Math.log(d)); }} NaN Infinity -Infinity 4.978497702968366 java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multithreading in Java
[ { "code": null, "e": 25857, "s": 25829, "text": "\n23 Mar, 2018" }, { "code": null, "e": 25988, "s": 25857, "text": "The java.lang.Math.log() method returns the natural logarithm (base e) of a double value as a parameter. There are various cases :" }, { "code": null, "e": 26054, "s": 25988, "text": "If the argument is NaN or less than zero, then the result is NaN." }, { "code": null, "e": 26130, "s": 26054, "text": "If the argument is positive infinity, then the result is positive infinity." }, { "code": null, "e": 26219, "s": 26130, "text": "If the argument is positive zero or negative zero, then the result is negative infinity." }, { "code": null, "e": 26228, "s": 26219, "text": "Syntax :" }, { "code": null, "e": 26263, "s": 26228, "text": "public static double log(double a)" }, { "code": null, "e": 26275, "s": 26263, "text": "Parameter :" }, { "code": null, "e": 26290, "s": 26275, "text": "a : User input" }, { "code": null, "e": 26299, "s": 26290, "text": "Return :" }, { "code": null, "e": 26335, "s": 26299, "text": "This method returns the value ln a." }, { "code": null, "e": 26392, "s": 26335, "text": "Example :To show working of java.lang.Math.log() method." }, { "code": "// Java program to demonstrate working// of java.lang.Math.log() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = -2.55; double b = 1.0 / 0; double c = 0, d = 145.256; // negative integer as argument, output NAN System.out.println(Math.log(a)); // positive infinity as argument, output Infinity System.out.println(Math.log(b)); // positive zero as argument, output -Infinity System.out.println(Math.log(c)); // positive double as argument System.out.println(Math.log(d)); }}", "e": 27060, "s": 26392, "text": null }, { "code": null, "e": 27102, "s": 27060, "text": "NaN\nInfinity\n-Infinity\n4.978497702968366\n" }, { "code": null, "e": 27112, "s": 27102, "text": "java-math" }, { "code": null, "e": 27117, "s": 27112, "text": "Java" }, { "code": null, "e": 27122, "s": 27117, "text": "Java" }, { "code": null, "e": 27220, "s": 27122, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27235, "s": 27220, "text": "Stream In Java" }, { "code": null, "e": 27286, "s": 27235, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27316, "s": 27286, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27335, "s": 27316, "text": "Interfaces in Java" }, { "code": null, "e": 27366, "s": 27335, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27384, "s": 27366, "text": "ArrayList in Java" }, { "code": null, "e": 27416, "s": 27384, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27436, "s": 27416, "text": "Stack Class in Java" }, { "code": null, "e": 27460, "s": 27436, "text": "Singleton Class in Java" } ]
3 easy tricks for beginners to improve plotly charts in R | by Stefan Haring | Towards Data Science
We’ve all been there at the end of a data science project: we’ve cleaned all the data, we’ve explored it, gained valuable insight and made the results accessible to the business via a webtool. We have even gone so far and made awesome interactive visualisations using plotly! The only problem is, the out-of-the-box formatting of those charts are mediocre. Co-workers are impressed with analytical insight but you hear them say things like “I wish the charts were nicer so we can show it to clients!” or “why is the cursor looking so weird?” and you’re left wondering how you can improve your charts for future projects. If this is you (or if you generally want to customise your charts more), here are 3simple tricks to improve your plotly charts in R (these tricks are also easily portable to other languages like Python). Before we start, we need a sample chart that we can improve upon. Below is a simple barchart displaying sales of three different products over the course of a year. The modebar is the small menu on the top right hand side that shows up once you mouse-over the chart. This feature can easily be disable, if you don’t want it to show up or if you just don’t want to provide certain features to users. fig %>% config(displayModeBar = FALSE) Alternatively, one can also customise the modebar and display only certain options, for example the download plot as image button. fig %>% config(modeBarButtons = list(list("toImage")), displaylogo = FALSE, toImageButtonOptions = list(filename = "plotOutput.png")) For more customisation possibilities, check out the plotly-r documentation here. The standard cursor that shows up when hovering over a plotly chart is the crosshair. Some people may like that but personally I prefer the default arrow cursor. To achieve this, the simplest way is to use the onRender function from the htmlwidgets package and a little bit of JavaScript. fig %>% onRender("function(el, x) {Plotly.d3.select('.cursor-crosshair').style('cursor', 'default')}") As we can see in our basic bar plot, the standard hover info that is displayed is (x value, y-value) and next to it the series name (in our case books, laptops or tvs). To add a little bit more information and formatting, we can create a separate variable and add it to the hover, e.g. if we wanted to show the percentage of total monthly sales we can create a new column with the percentage values and use that column for the text argument in our plot_ly function call. #add percentages to our datadata <- data %>% group_by(variable) %>% mutate(pct = value / sum(value), pct = scales::percent(pct))#updated plot_ly function callplot_ly(x = ~dates, y = ~value, type = 'bar', text = ~pct, name = ~variable, color = ~variable) If we want to take this a step further and show some custom text, there is no need to add another column to the data whose only use would be for displaying some text. We can just use the hovertemplate argument of plot_ly instead! Various parts of our data set can be accessed by using the %{var} syntax, e.g. x and y values, the text argument and even the dataset itself (by using fullData.var, see the bonus section). #updated plot_ly function callplot_ly(data, x = ~dates, y = ~value, type = 'bar', name = ~variable, color = ~variable, text = ~pct, hovertemplate = "Units sold: %{y} <br> Percentage: %{text}") While this hoverinfo already looks much better, wouldn’t it be nicer if “Units sold” would be replaced with e.g. tvs sold instead of displaying the series name outside of the box? Easy! Access the series names with ${fullData.name} and add it to the hovertemplate. To remove the extra text next to the box, add the empty html tag <extra> and don’t forget to close it! #updated plot_ly function callplot_ly(data, x = ~dates, y = ~value, type = 'bar', name = ~variable, color = ~variable, text = ~pct, hovertemplate = "%{fullData.name} sold: %{y}<br>Percentage: %{text} <extra></extra>") In this post, I’ve demonstrated 3 quick and easy tricks that you can immediately use when starting out with plotly in R. These methods allow you to enhance and customise certain aspects of your charts and enable you and your users to gain more insight from the data. And all that in just a few simple lines of code and without any complicated formatting!
[ { "code": null, "e": 447, "s": 171, "text": "We’ve all been there at the end of a data science project: we’ve cleaned all the data, we’ve explored it, gained valuable insight and made the results accessible to the business via a webtool. We have even gone so far and made awesome interactive visualisations using plotly!" }, { "code": null, "e": 792, "s": 447, "text": "The only problem is, the out-of-the-box formatting of those charts are mediocre. Co-workers are impressed with analytical insight but you hear them say things like “I wish the charts were nicer so we can show it to clients!” or “why is the cursor looking so weird?” and you’re left wondering how you can improve your charts for future projects." }, { "code": null, "e": 996, "s": 792, "text": "If this is you (or if you generally want to customise your charts more), here are 3simple tricks to improve your plotly charts in R (these tricks are also easily portable to other languages like Python)." }, { "code": null, "e": 1161, "s": 996, "text": "Before we start, we need a sample chart that we can improve upon. Below is a simple barchart displaying sales of three different products over the course of a year." }, { "code": null, "e": 1263, "s": 1161, "text": "The modebar is the small menu on the top right hand side that shows up once you mouse-over the chart." }, { "code": null, "e": 1395, "s": 1263, "text": "This feature can easily be disable, if you don’t want it to show up or if you just don’t want to provide certain features to users." }, { "code": null, "e": 1434, "s": 1395, "text": "fig %>% config(displayModeBar = FALSE)" }, { "code": null, "e": 1565, "s": 1434, "text": "Alternatively, one can also customise the modebar and display only certain options, for example the download plot as image button." }, { "code": null, "e": 1699, "s": 1565, "text": "fig %>% config(modeBarButtons = list(list(\"toImage\")), displaylogo = FALSE, toImageButtonOptions = list(filename = \"plotOutput.png\"))" }, { "code": null, "e": 1780, "s": 1699, "text": "For more customisation possibilities, check out the plotly-r documentation here." }, { "code": null, "e": 1942, "s": 1780, "text": "The standard cursor that shows up when hovering over a plotly chart is the crosshair. Some people may like that but personally I prefer the default arrow cursor." }, { "code": null, "e": 2069, "s": 1942, "text": "To achieve this, the simplest way is to use the onRender function from the htmlwidgets package and a little bit of JavaScript." }, { "code": null, "e": 2172, "s": 2069, "text": "fig %>% onRender(\"function(el, x) {Plotly.d3.select('.cursor-crosshair').style('cursor', 'default')}\")" }, { "code": null, "e": 2643, "s": 2172, "text": "As we can see in our basic bar plot, the standard hover info that is displayed is (x value, y-value) and next to it the series name (in our case books, laptops or tvs). To add a little bit more information and formatting, we can create a separate variable and add it to the hover, e.g. if we wanted to show the percentage of total monthly sales we can create a new column with the percentage values and use that column for the text argument in our plot_ly function call." }, { "code": null, "e": 2899, "s": 2643, "text": "#add percentages to our datadata <- data %>% group_by(variable) %>% mutate(pct = value / sum(value), pct = scales::percent(pct))#updated plot_ly function callplot_ly(x = ~dates, y = ~value, type = 'bar', text = ~pct, name = ~variable, color = ~variable)" }, { "code": null, "e": 3129, "s": 2899, "text": "If we want to take this a step further and show some custom text, there is no need to add another column to the data whose only use would be for displaying some text. We can just use the hovertemplate argument of plot_ly instead!" }, { "code": null, "e": 3318, "s": 3129, "text": "Various parts of our data set can be accessed by using the %{var} syntax, e.g. x and y values, the text argument and even the dataset itself (by using fullData.var, see the bonus section)." }, { "code": null, "e": 3511, "s": 3318, "text": "#updated plot_ly function callplot_ly(data, x = ~dates, y = ~value, type = 'bar', name = ~variable, color = ~variable, text = ~pct, hovertemplate = \"Units sold: %{y} <br> Percentage: %{text}\")" }, { "code": null, "e": 3879, "s": 3511, "text": "While this hoverinfo already looks much better, wouldn’t it be nicer if “Units sold” would be replaced with e.g. tvs sold instead of displaying the series name outside of the box? Easy! Access the series names with ${fullData.name} and add it to the hovertemplate. To remove the extra text next to the box, add the empty html tag <extra> and don’t forget to close it!" }, { "code": null, "e": 4097, "s": 3879, "text": "#updated plot_ly function callplot_ly(data, x = ~dates, y = ~value, type = 'bar', name = ~variable, color = ~variable, text = ~pct, hovertemplate = \"%{fullData.name} sold: %{y}<br>Percentage: %{text} <extra></extra>\")" } ]
Draw rectangle on an image using OpenCV
In this program, we will draw a rectangle using the OpenCV function rectangle(). This function takes some parameters like starting coordinates, ending coordinates, color and thickness and the image itself. Step 1: Import cv2. Step 2: Read the image using imread(). Step 3: Define the starting coordinates. Step 5: Define the ending coordinates. Step 6: Define the color and the thickness. Step 7: Draw the rectangle using the cv2.reactangle() function. Step 8: Display the rectangle. import cv2 image = cv2.imread('testimage.jpg') height, width, channels = image.shape start_point = (0,0) end_point = (width, height) color = (0,0,255) thickness = 5 image = cv2.rectangle(image, start_point, end_point, color, thickness) cv2.imshow('Rectangle',image)
[ { "code": null, "e": 1268, "s": 1062, "text": "In this program, we will draw a rectangle using the OpenCV function rectangle(). This function takes some parameters like starting coordinates, ending coordinates, color and thickness and the image itself." }, { "code": null, "e": 1546, "s": 1268, "text": "Step 1: Import cv2.\nStep 2: Read the image using imread().\nStep 3: Define the starting coordinates.\nStep 5: Define the ending coordinates.\nStep 6: Define the color and the thickness.\nStep 7: Draw the rectangle using the cv2.reactangle() function.\nStep 8: Display the rectangle." }, { "code": null, "e": 1814, "s": 1546, "text": "import cv2\n\nimage = cv2.imread('testimage.jpg')\nheight, width, channels = image.shape\nstart_point = (0,0)\nend_point = (width, height)\ncolor = (0,0,255)\nthickness = 5\n\nimage = cv2.rectangle(image, start_point, end_point, color, thickness)\ncv2.imshow('Rectangle',image)" } ]
Get only the date from datetime in MySQL?
To get only the date from DateTime, use the date format specifiers − %d for day %m for month %Y for year Let us first create a table − mysql> create table DemoTable ( AdmissionDate datetime ); Query OK, 0 rows affected (0.52 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('2019-07-21 12:34:56'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('2016-08-18 10:00:02'); Query OK, 1 row affected (0.51 sec) mysql> insert into DemoTable values('2018-01-03 11:02:20'); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +---------------------+ | AdmissionDate | +---------------------+ | 2019-07-21 12:34:56 | | 2016-08-18 10:00:02 | | 2018-01-03 11:02:20 | +---------------------+ 3 rows in set (0.00 sec) Here is the query to get only the date − mysql> select date_format(AdmissionDate,'%d.%m.%Y') AS Date from DemoTable; This will produce the following output − +------------+ | Date | +------------+ | 21.07.2019 | | 18.08.2016 | | 03.01.2018 | +------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1131, "s": 1062, "text": "To get only the date from DateTime, use the date format specifiers −" }, { "code": null, "e": 1167, "s": 1131, "text": "%d for day\n%m for month\n%Y for year" }, { "code": null, "e": 1197, "s": 1167, "text": "Let us first create a table −" }, { "code": null, "e": 1295, "s": 1197, "text": "mysql> create table DemoTable\n(\n AdmissionDate datetime\n);\nQuery OK, 0 rows affected (0.52 sec)" }, { "code": null, "e": 1351, "s": 1295, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1639, "s": 1351, "text": "mysql> insert into DemoTable values('2019-07-21 12:34:56');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values('2016-08-18 10:00:02');\nQuery OK, 1 row affected (0.51 sec)\nmysql> insert into DemoTable values('2018-01-03 11:02:20');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1699, "s": 1639, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1730, "s": 1699, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1771, "s": 1730, "text": "This will produce the following output −" }, { "code": null, "e": 1964, "s": 1771, "text": "+---------------------+\n| AdmissionDate |\n+---------------------+\n| 2019-07-21 12:34:56 |\n| 2016-08-18 10:00:02 |\n| 2018-01-03 11:02:20 |\n+---------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2005, "s": 1964, "text": "Here is the query to get only the date −" }, { "code": null, "e": 2081, "s": 2005, "text": "mysql> select date_format(AdmissionDate,'%d.%m.%Y') AS Date from DemoTable;" }, { "code": null, "e": 2122, "s": 2081, "text": "This will produce the following output −" }, { "code": null, "e": 2252, "s": 2122, "text": "+------------+\n| Date |\n+------------+\n| 21.07.2019 |\n| 18.08.2016 |\n| 03.01.2018 |\n+------------+\n3 rows in set (0.00 sec)" } ]
Constructors in Java - GeeksforGeeks
09 Feb, 2022 Java constructors or constructors in Java is a terminology been used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. Note: It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn’t have any. Constructors must have the same name as the class within which it is defined while it is not necessary for the method in Java. Constructors do not return any type while method(s) have the return type or void if does not return any value. Constructors are called only once at the time of Object creation while method(s) can be called any number of times. Now let us come up with the syntax for the constructor being invoked at the time of object or instance creation. class Geek { ....... // A Constructor new Geek() {} ....... } // We can create an object of the above class // using the below statement. This statement // calls above constructor. Geek obj = new Geek(); Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions. The answer is no. So constructors are used to assigning values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor). When is a Constructor called? Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. The rules for writing constructors are as follows: Constructor(s) of a class must have the same name as the class name in which it resides. A constructor in Java can not be abstract, final, static, or Synchronized. Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor. So by far, we have learned constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. Now is the correct time to discuss types of the constructor, so primarily there are two types of constructors in java: No-argument constructor Parameterized Constructor 1. No-argument constructor A constructor that has no parameter is known as the default constructor. If we don’t define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. And if we write a constructor with arguments or no-arguments then the compiler does not create a default constructor. Note: Default constructor provides the default values to the object like 0, null, etc. depending on the type. Example: Java // Java Program to illustrate calling a// no-argument constructor import java.io.*; class Geek { int num; String name; // this would be invoked while an object // of that class is created. Geek() { System.out.println("Constructor called"); }} class GFG { public static void main(String[] args) { // this would invoke default constructor. Geek geek1 = new Geek(); // Default constructor provides the default // values to the object like 0, null System.out.println(geek1.name); System.out.println(geek1.num); }} Constructor called null 0 2. Parameterized Constructor A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor. Example: Java // Java Program to Illustrate Working of// Parameterized Constructor // Importing required inputoutput classimport java.io.*; // Class 1class Geek { // data members of the class. String name; int id; // Constructor would initialize data members // With the values of passed arguments while // Object of that class created Geek(String name, int id) { this.name = name; this.id = id; }} // Class 2class GFG { // main driver method public static void main(String[] args) { // This would invoke the parameterized constructor. Geek geek1 = new Geek("adam", 1); System.out.println("GeekName :" + geek1.name + " and GeekId :" + geek1.id); }} GeekName :adam and GeekId :1 Remember: Does constructor return any value? There are no “return value” statements in the constructor, but the constructor returns the current class instance. We can write ‘return’ inside a constructor. Now the most important topic that comes into play is the strong incorporation of OOPS with constructors known as constructor overloading. JustLike methods, we can overload constructors for creating objects in different ways. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters, and order of the parameters. Example: Java // Java Program to illustrate constructor overloading// using same task (addition operation ) for different// types of arguments. import java.io.*; class Geek{ // constructor with one argument Geek(String name) { System.out.println("Constructor with one " + "argument - String : " + name); } // constructor with two arguments Geek(String name, int age) { System.out.println("Constructor with two arguments : " + " String and Integer : " + name + " "+ age); } // Constructor with one argument but with different // type than previous.. Geek(long id) { System.out.println("Constructor with one argument : " + "Long : " + id); }} class GFG{ public static void main(String[] args) { // Creating the objects of the class named 'Geek' // by passing different arguments // Invoke the constructor with one argument of // type 'String'. Geek geek2 = new Geek("Shikhar"); // Invoke the constructor with two arguments Geek geek3 = new Geek("Dharmesh", 26); // Invoke the constructor with one argument of // type 'Long'. Geek geek4 = new Geek(325614567); }} Constructor with one argument - String : Shikhar Constructor with two arguments : String and Integer : Dharmesh 26 Constructor with one argument : Long : 325614567 In order to know to deep down into constructors there are two concepts been widely used as listed below: Constructor Chaining Copy constructor This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. deepak_jain Kirti_Mangal kushvillia solankimayank anikakapoor nishkarshgandhi Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split() String method in Java with examples Arrays.sort() in Java with examples Initialize an ArrayList in Java Reverse a string in Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 28870, "s": 28842, "text": "\n09 Feb, 2022" }, { "code": null, "e": 29182, "s": 28870, "text": "Java constructors or constructors in Java is a terminology been used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. " }, { "code": null, "e": 29557, "s": 29182, "text": "In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called." }, { "code": null, "e": 29709, "s": 29557, "text": "Note: It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn’t have any." }, { "code": null, "e": 29836, "s": 29709, "text": "Constructors must have the same name as the class within which it is defined while it is not necessary for the method in Java." }, { "code": null, "e": 29947, "s": 29836, "text": "Constructors do not return any type while method(s) have the return type or void if does not return any value." }, { "code": null, "e": 30063, "s": 29947, "text": "Constructors are called only once at the time of Object creation while method(s) can be called any number of times." }, { "code": null, "e": 30176, "s": 30063, "text": "Now let us come up with the syntax for the constructor being invoked at the time of object or instance creation." }, { "code": null, "e": 30395, "s": 30176, "text": "class Geek\n{ \n .......\n\n // A Constructor\n new Geek() {}\n\n .......\n}\n\n// We can create an object of the above class\n// using the below statement. This statement\n// calls above constructor.\nGeek obj = new Geek(); " }, { "code": null, "e": 30871, "s": 30395, "text": "Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions. The answer is no. So constructors are used to assigning values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor)." }, { "code": null, "e": 30902, "s": 30871, "text": "When is a Constructor called? " }, { "code": null, "e": 31095, "s": 30902, "text": "Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. " }, { "code": null, "e": 31146, "s": 31095, "text": "The rules for writing constructors are as follows:" }, { "code": null, "e": 31235, "s": 31146, "text": "Constructor(s) of a class must have the same name as the class name in which it resides." }, { "code": null, "e": 31310, "s": 31235, "text": "A constructor in Java can not be abstract, final, static, or Synchronized." }, { "code": null, "e": 31436, "s": 31310, "text": "Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor." }, { "code": null, "e": 31659, "s": 31436, "text": "So by far, we have learned constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation." }, { "code": null, "e": 31779, "s": 31659, "text": "Now is the correct time to discuss types of the constructor, so primarily there are two types of constructors in java: " }, { "code": null, "e": 31803, "s": 31779, "text": "No-argument constructor" }, { "code": null, "e": 31829, "s": 31803, "text": "Parameterized Constructor" }, { "code": null, "e": 31856, "s": 31829, "text": "1. No-argument constructor" }, { "code": null, "e": 32175, "s": 31856, "text": "A constructor that has no parameter is known as the default constructor. If we don’t define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. And if we write a constructor with arguments or no-arguments then the compiler does not create a default constructor. " }, { "code": null, "e": 32285, "s": 32175, "text": "Note: Default constructor provides the default values to the object like 0, null, etc. depending on the type." }, { "code": null, "e": 32294, "s": 32285, "text": "Example:" }, { "code": null, "e": 32299, "s": 32294, "text": "Java" }, { "code": "// Java Program to illustrate calling a// no-argument constructor import java.io.*; class Geek { int num; String name; // this would be invoked while an object // of that class is created. Geek() { System.out.println(\"Constructor called\"); }} class GFG { public static void main(String[] args) { // this would invoke default constructor. Geek geek1 = new Geek(); // Default constructor provides the default // values to the object like 0, null System.out.println(geek1.name); System.out.println(geek1.num); }}", "e": 32882, "s": 32299, "text": null }, { "code": null, "e": 32908, "s": 32882, "text": "Constructor called\nnull\n0" }, { "code": null, "e": 32937, "s": 32908, "text": "2. Parameterized Constructor" }, { "code": null, "e": 33114, "s": 32937, "text": "A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor." }, { "code": null, "e": 33123, "s": 33114, "text": "Example:" }, { "code": null, "e": 33128, "s": 33123, "text": "Java" }, { "code": "// Java Program to Illustrate Working of// Parameterized Constructor // Importing required inputoutput classimport java.io.*; // Class 1class Geek { // data members of the class. String name; int id; // Constructor would initialize data members // With the values of passed arguments while // Object of that class created Geek(String name, int id) { this.name = name; this.id = id; }} // Class 2class GFG { // main driver method public static void main(String[] args) { // This would invoke the parameterized constructor. Geek geek1 = new Geek(\"adam\", 1); System.out.println(\"GeekName :\" + geek1.name + \" and GeekId :\" + geek1.id); }}", "e": 33868, "s": 33128, "text": null }, { "code": null, "e": 33897, "s": 33868, "text": "GeekName :adam and GeekId :1" }, { "code": null, "e": 33942, "s": 33897, "text": "Remember: Does constructor return any value?" }, { "code": null, "e": 34101, "s": 33942, "text": "There are no “return value” statements in the constructor, but the constructor returns the current class instance. We can write ‘return’ inside a constructor." }, { "code": null, "e": 34457, "s": 34101, "text": "Now the most important topic that comes into play is the strong incorporation of OOPS with constructors known as constructor overloading. JustLike methods, we can overload constructors for creating objects in different ways. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters, and order of the parameters. " }, { "code": null, "e": 34466, "s": 34457, "text": "Example:" }, { "code": null, "e": 34471, "s": 34466, "text": "Java" }, { "code": "// Java Program to illustrate constructor overloading// using same task (addition operation ) for different// types of arguments. import java.io.*; class Geek{ // constructor with one argument Geek(String name) { System.out.println(\"Constructor with one \" + \"argument - String : \" + name); } // constructor with two arguments Geek(String name, int age) { System.out.println(\"Constructor with two arguments : \" + \" String and Integer : \" + name + \" \"+ age); } // Constructor with one argument but with different // type than previous.. Geek(long id) { System.out.println(\"Constructor with one argument : \" + \"Long : \" + id); }} class GFG{ public static void main(String[] args) { // Creating the objects of the class named 'Geek' // by passing different arguments // Invoke the constructor with one argument of // type 'String'. Geek geek2 = new Geek(\"Shikhar\"); // Invoke the constructor with two arguments Geek geek3 = new Geek(\"Dharmesh\", 26); // Invoke the constructor with one argument of // type 'Long'. Geek geek4 = new Geek(325614567); }}", "e": 35752, "s": 34471, "text": null }, { "code": null, "e": 35917, "s": 35752, "text": "Constructor with one argument - String : Shikhar\nConstructor with two arguments : String and Integer : Dharmesh 26\nConstructor with one argument : Long : 325614567" }, { "code": null, "e": 36023, "s": 35917, "text": "In order to know to deep down into constructors there are two concepts been widely used as listed below: " }, { "code": null, "e": 36044, "s": 36023, "text": "Constructor Chaining" }, { "code": null, "e": 36061, "s": 36044, "text": "Copy constructor" }, { "code": null, "e": 36484, "s": 36061, "text": "This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36496, "s": 36484, "text": "deepak_jain" }, { "code": null, "e": 36509, "s": 36496, "text": "Kirti_Mangal" }, { "code": null, "e": 36520, "s": 36509, "text": "kushvillia" }, { "code": null, "e": 36534, "s": 36520, "text": "solankimayank" }, { "code": null, "e": 36546, "s": 36534, "text": "anikakapoor" }, { "code": null, "e": 36562, "s": 36546, "text": "nishkarshgandhi" }, { "code": null, "e": 36567, "s": 36562, "text": "Java" }, { "code": null, "e": 36586, "s": 36567, "text": "School Programming" }, { "code": null, "e": 36591, "s": 36586, "text": "Java" }, { "code": null, "e": 36689, "s": 36591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36698, "s": 36689, "text": "Comments" }, { "code": null, "e": 36711, "s": 36698, "text": "Old Comments" }, { "code": null, "e": 36755, "s": 36711, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36791, "s": 36755, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 36823, "s": 36791, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 36848, "s": 36823, "text": "Reverse a string in Java" }, { "code": null, "e": 36879, "s": 36848, "text": "How to iterate any Map in Java" }, { "code": null, "e": 36897, "s": 36879, "text": "Python Dictionary" }, { "code": null, "e": 36913, "s": 36897, "text": "Arrays in C/C++" }, { "code": null, "e": 36932, "s": 36913, "text": "Inheritance in C++" }, { "code": null, "e": 36957, "s": 36932, "text": "Reverse a string in Java" } ]
How do I give focus to a python Tkinter text widget?
In various applications, tkinter widgets are required to be focused to make them active. Widgets can also grab focus and prevent the other events outside the bounds. To manage and give focus to a particular widget, we generally use the focus_set() method. It focuses the widget and makes them active until the termination of the program. In the following example, we have created two widgets: an Entry widget and a text widget in the same window. By using the focus_set() method, we will activate the focus on the text widget. #Import tkinter library from tkinter import * from PIL import Image,ImageTk #Create an instance of tkinter frame win = Tk() #Set the geometry win.geometry("750x250") #Create a Text WIdget text= Text(win, width= 30, height= 10) text.insert(INSERT, "Hello World!") #Activate the focus text.focus_set() text.pack() #Create an Entry Widget entry=Entry(win,width= 30) entry.pack() win.mainloop() Running the above code will display a window that contains the focus on the text widget.
[ { "code": null, "e": 1400, "s": 1062, "text": "In various applications, tkinter widgets are required to be focused to make them active. Widgets can also grab focus and prevent the other events outside the bounds. To manage and give focus to a particular widget, we generally use the focus_set() method. It focuses the widget and makes them active until the termination of the program." }, { "code": null, "e": 1589, "s": 1400, "text": "In the following example, we have created two widgets: an Entry widget and a text widget in the same window. By using the focus_set() method, we will activate the focus on the text widget." }, { "code": null, "e": 1980, "s": 1589, "text": "#Import tkinter library\nfrom tkinter import *\nfrom PIL import Image,ImageTk\n#Create an instance of tkinter frame\nwin = Tk()\n#Set the geometry\nwin.geometry(\"750x250\")\n#Create a Text WIdget\ntext= Text(win, width= 30, height= 10)\ntext.insert(INSERT, \"Hello World!\")\n#Activate the focus\ntext.focus_set()\ntext.pack()\n#Create an Entry Widget\nentry=Entry(win,width= 30)\nentry.pack()\nwin.mainloop()" }, { "code": null, "e": 2069, "s": 1980, "text": "Running the above code will display a window that contains the focus on the text widget." } ]
High-level language program
High level language is the next development in the evolution of computer languages. Examples of some high-level languages are given below PROLOG (for “PROgramming LOGic”) FORTRAN (for ‘FORrmula TRANslation’) LISP (for “LISt Processing”) Pascal (named after the French scientist Blaise Pascal). High-level languages are like English-like language, with less words also known as keywords and fewer ambiguities. Each high level language will have its own syntax and keywords. The meaning of the word syntax is grammar. Now let us discuss about the disadvantages of high-level languages A high level language program can’t get executed directly. It requires some translator to get it translated to machine language. There are two types of translators for high level language programs. They are interpreter and compiler. In case of interpreter, prior execution, each and every line will get translated and then executed. In case of compiler, the whole program will get translated as a whole and will create an executable file. And after that, as when required, the executable code will get executed. These translator programs, specially compilers, are huge one and so are quite expensive. A high level language program can’t get executed directly. It requires some translator to get it translated to machine language. There are two types of translators for high level language programs. They are interpreter and compiler. In case of interpreter, prior execution, each and every line will get translated and then executed. In case of compiler, the whole program will get translated as a whole and will create an executable file. And after that, as when required, the executable code will get executed. These translator programs, specially compilers, are huge one and so are quite expensive. The machine language code generated by the compiler might not be as compact as written straightaway in low-level language. Thus a program written in high-level language usually takes longer time to execute. The machine language code generated by the compiler might not be as compact as written straightaway in low-level language. Thus a program written in high-level language usually takes longer time to execute. Now we shall discuss about the advantages of high-level languages High-level language programs are easy to get developed. While coding if we do some errors then we can easily locate those errors and if we miss then during compilation those errors would get detected by the compiler. And the programmer will initiate respective corrections to do needful accordingly. High-level language programs are easy to get developed. While coding if we do some errors then we can easily locate those errors and if we miss then during compilation those errors would get detected by the compiler. And the programmer will initiate respective corrections to do needful accordingly. By a glance through the program it is easy to visualize the function of the program. By a glance through the program it is easy to visualize the function of the program. The programmer may not remain aware about the architecture of the hardware. So people with our hardware knowledge can also do high level language programming. The programmer may not remain aware about the architecture of the hardware. So people with our hardware knowledge can also do high level language programming. The same high level language program works on any other computer, provided the respective compiler is available for the target new architecture. So high-level languages are portable. The same high level language program works on any other computer, provided the respective compiler is available for the target new architecture. So high-level languages are portable. Productivity against high level language programming is enormously increased. Productivity against high level language programming is enormously increased. To conclude, high-level languages are almost always used nowadays except where very high-speed execution is required. As an example, let us consider the following program code written in high-level language C #include <stdio.h> int main() { int a,b,c; printf("\n\n\t\t Welcome to the world of programming..."); printf("\n\n\t\t Please enter the first number..."); scanf("%d",&a); printf("\n\n\t\t Please enter the second number..."); scanf("%d",&b); c = a+b; printf("\n\n\t\t So the sum of %d and %d is %d...",a,b,c); printf("\n\n\t\t End of the program..."); }
[ { "code": null, "e": 1200, "s": 1062, "text": "High level language is the next development in the evolution of computer languages. Examples of some high-level languages are given below" }, { "code": null, "e": 1233, "s": 1200, "text": "PROLOG (for “PROgramming LOGic”)" }, { "code": null, "e": 1270, "s": 1233, "text": "FORTRAN (for ‘FORrmula TRANslation’)" }, { "code": null, "e": 1299, "s": 1270, "text": "LISP (for “LISt Processing”)" }, { "code": null, "e": 1356, "s": 1299, "text": "Pascal (named after the French scientist Blaise Pascal)." }, { "code": null, "e": 1578, "s": 1356, "text": "High-level languages are like English-like language, with less words also known as keywords and fewer ambiguities. Each high level language will have its own syntax and keywords. The meaning of the word syntax is grammar." }, { "code": null, "e": 1645, "s": 1578, "text": "Now let us discuss about the disadvantages of high-level languages" }, { "code": null, "e": 2246, "s": 1645, "text": "A high level language program can’t get executed directly. It requires some translator to get it translated to machine language. There are two types of translators for high level language programs. They are interpreter and compiler. In case of interpreter, prior execution, each and every line will get translated and then executed. In case of compiler, the whole program will get translated as a whole and will create an executable file. And after that, as when required, the executable code will get executed. These translator programs, specially compilers, are huge one and so are quite expensive." }, { "code": null, "e": 2847, "s": 2246, "text": "A high level language program can’t get executed directly. It requires some translator to get it translated to machine language. There are two types of translators for high level language programs. They are interpreter and compiler. In case of interpreter, prior execution, each and every line will get translated and then executed. In case of compiler, the whole program will get translated as a whole and will create an executable file. And after that, as when required, the executable code will get executed. These translator programs, specially compilers, are huge one and so are quite expensive." }, { "code": null, "e": 3054, "s": 2847, "text": "The machine language code generated by the compiler might not be as compact as written straightaway in low-level language. Thus a program written in high-level language usually takes longer time to execute." }, { "code": null, "e": 3261, "s": 3054, "text": "The machine language code generated by the compiler might not be as compact as written straightaway in low-level language. Thus a program written in high-level language usually takes longer time to execute." }, { "code": null, "e": 3327, "s": 3261, "text": "Now we shall discuss about the advantages of high-level languages" }, { "code": null, "e": 3627, "s": 3327, "text": "High-level language programs are easy to get developed. While coding if we do some errors then we can easily locate those errors and if we miss then during compilation those errors would get detected by the compiler. And the programmer will initiate respective corrections to do needful accordingly." }, { "code": null, "e": 3927, "s": 3627, "text": "High-level language programs are easy to get developed. While coding if we do some errors then we can easily locate those errors and if we miss then during compilation those errors would get detected by the compiler. And the programmer will initiate respective corrections to do needful accordingly." }, { "code": null, "e": 4012, "s": 3927, "text": "By a glance through the program it is easy to visualize the function of the program." }, { "code": null, "e": 4097, "s": 4012, "text": "By a glance through the program it is easy to visualize the function of the program." }, { "code": null, "e": 4256, "s": 4097, "text": "The programmer may not remain aware about the architecture of the hardware. So people with our hardware knowledge can also do high level language programming." }, { "code": null, "e": 4415, "s": 4256, "text": "The programmer may not remain aware about the architecture of the hardware. So people with our hardware knowledge can also do high level language programming." }, { "code": null, "e": 4598, "s": 4415, "text": "The same high level language program works on any other computer, provided the respective compiler is available for the target new architecture. So high-level languages are portable." }, { "code": null, "e": 4781, "s": 4598, "text": "The same high level language program works on any other computer, provided the respective compiler is available for the target new architecture. So high-level languages are portable." }, { "code": null, "e": 4859, "s": 4781, "text": "Productivity against high level language programming is enormously increased." }, { "code": null, "e": 4937, "s": 4859, "text": "Productivity against high level language programming is enormously increased." }, { "code": null, "e": 5055, "s": 4937, "text": "To conclude, high-level languages are almost always used nowadays except where very high-speed execution is required." }, { "code": null, "e": 5146, "s": 5055, "text": "As an example, let us consider the following program code written in high-level language C" }, { "code": null, "e": 5526, "s": 5146, "text": "#include <stdio.h>\nint main() {\n int a,b,c;\n printf(\"\\n\\n\\t\\t Welcome to the world of programming...\");\n printf(\"\\n\\n\\t\\t Please enter the first number...\");\n scanf(\"%d\",&a);\n printf(\"\\n\\n\\t\\t Please enter the second number...\");\n scanf(\"%d\",&b);\n c = a+b;\n printf(\"\\n\\n\\t\\t So the sum of %d and %d is %d...\",a,b,c);\n printf(\"\\n\\n\\t\\t End of the program...\");\n}" } ]
Conversion of Array To ArrayList in Java - GeeksforGeeks
26 Oct, 2021 Following methods can be used for converting Array To ArrayList: Method 1: Using Arrays.asList() method Syntax: public static List asList(T... a) // Returns a fixed-size List as of size of given array. // Element Type of List is of same as type of array element type. // It returns an List containing all of the elements in this // array in the same order. // T represents generics Note that the there is an array parameter and List return value. Returns a fixed-size list backed by the specified array. The returned list is serializable and implements RandomAccess. Since returned List is fixed-size therefore we can’t add more element in it, but we can replace existing element with new element using set(index, new Element) method defined in ArrayList class. Java // Java program to demonstrate conversion of// Array to ArrayList of fixed-size.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {"Rahul", "Utkarsh", "Shubham", "Neelam"}; // Conversion of array to ArrayList // using Arrays.asList List al = Arrays.asList(geeks); System.out.println(al); }} Output: [Rahul, Utkarsh, Shubham, Neelam] What if we add more elements to the converted list? Since returned List is fixed-size List, we can’t add more element(s). An attempt of adding more elements would cause UnsupportedOperationException.Consider the following example. Java // Java program to demonstrate error// if we add more element(s) to// a fixed-size List.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {"Rahul", "Utkarsh", "Shubham", "Neelam"}; // Conversion of array to ArrayList // using Arrays.asList List al = Arrays.asList(geeks); System.out.println(al); // Adding some more values to the List. al.add("Shashank"); al.add("Nishant"); System.out.println(al); }} Output: [Rahul, Utkarsh, Shubham, Neelam] Runtime error Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:148) at java.util.AbstractList.add(AbstractList.java:108) at GFG.main(File.java:16) It is therefore recommended to create new ArrayList and pass Arrays.asList(array reference) as an argument to it (i.e. as an constructor argument of ArrayList).Consider the following example: Java // Java program to demonstrate how to add// one or more element(s) to returned// resizable List.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {"Rahul", "Utkarsh", "Shubham", "Neelam"}; List<String> al = new ArrayList<String>(Arrays.asList(geeks)); System.out.println(al); // Adding some more values to the List. al.add("Shashank"); al.add("Nishant"); System.out.println("\nArrayList After adding two" + " more Geeks: "); System.out.println(al); }} [Rahul, Utkarsh, Shubham, Neelam] ArrayList After adding two more Geeks: [Rahul, Utkarsh, Shubham, Neelam, Nishant, Shashank] &nbap; Method 2: Using Collections.addAll() method Syntax: public static boolean addAll(Collection c, T... a) // Adds all of the specified elements to the specified collection. // Elements to be added may be specified individually or as an array. // T is generics Note that there is a collection parameter c into which elements to be inserted and array parameter a contains the elements to insert into c. Return type is boolean type. It returns true if the collection changed as a result of the call.It throws UnsupportedOperationException if collection c does not support add method and throws IllegalArgumentException if some aspect of a value in elements(or elements of array) prevents it from being added to collection c.Consider the following example: Java // Java program to demonstrate how to// add all elements of array to arrayList.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {"Rahul", "Utkarsh", "Shubham", "Neelam"}; List<String> al = new ArrayList<String>(); // adding elements of array to arrayList. Collections.addAll(al, geeks); System.out.println(al); }} Output : [Rahul, Utkarsh, Shubham, Neelam] Adding null to the list Note : If the specified collection or specified array is null then it throw NullpointerException. Java // Adding null to a listimport java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {"Rahul", "Utkarsh", "Shubham", "Neelam"}; List<String> al = new ArrayList<String>(); Collections.addAll(null, geeks); System.out.println(al); }} Adding null to the end of list Java import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {"Rahul", "Utkarsh", "Shubham", "Neelam"}; List<String> al = new ArrayList<String>(); Collections.addAll(al, null); System.out.println(al); }} RunTime Error Exception in thread "main" java.lang.NullPointerException at java.util.Collections.addAll(Collections.java:5401) at GFG.main(File.java:11) Method 3: Using Manual method to convert Array using add() method We can use this method if we don’t want to use java in built method(s). This is a manual method of adding all array’s elements to List. Syntax: public boolean add(Object obj) // Appends the specified element to the end of this list. // Returns true. Java // Java program to convert a ArrayList to// an array using add() in a loop.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {"Rahul", "Utkarsh", "Shubham", "Neelam"}; List<String> al = new ArrayList<String>(); // Array to ArrayList Conversion for (String geek : geeks) al.add(geek); System.out.println(al); }} Output: [Rahul, Utkarsh, Shubham, Neelam] Related Article: ArrayList to Array ConversionThis article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet ruhelaa48 Java-Array-Programs Java-ArrayList Java-Collections java-list Java-List-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24671, "s": 24643, "text": "\n26 Oct, 2021" }, { "code": null, "e": 24737, "s": 24671, "text": "Following methods can be used for converting Array To ArrayList: " }, { "code": null, "e": 24778, "s": 24739, "text": "Method 1: Using Arrays.asList() method" }, { "code": null, "e": 25063, "s": 24780, "text": " Syntax: public static List asList(T... a)\n// Returns a fixed-size List as of size of given array. \n// Element Type of List is of same as type of array element type.\n// It returns an List containing all of the elements in this \n// array in the same order. \n// T represents generics " }, { "code": null, "e": 25130, "s": 25063, "text": "Note that the there is an array parameter and List return value. " }, { "code": null, "e": 25187, "s": 25130, "text": "Returns a fixed-size list backed by the specified array." }, { "code": null, "e": 25250, "s": 25187, "text": "The returned list is serializable and implements RandomAccess." }, { "code": null, "e": 25447, "s": 25250, "text": "Since returned List is fixed-size therefore we can’t add more element in it, but we can replace existing element with new element using set(index, new Element) method defined in ArrayList class. " }, { "code": null, "e": 25454, "s": 25449, "text": "Java" }, { "code": "// Java program to demonstrate conversion of// Array to ArrayList of fixed-size.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {\"Rahul\", \"Utkarsh\", \"Shubham\", \"Neelam\"}; // Conversion of array to ArrayList // using Arrays.asList List al = Arrays.asList(geeks); System.out.println(al); }}", "e": 25856, "s": 25454, "text": null }, { "code": null, "e": 25866, "s": 25856, "text": "Output: " }, { "code": null, "e": 25900, "s": 25866, "text": "[Rahul, Utkarsh, Shubham, Neelam]" }, { "code": null, "e": 26133, "s": 25900, "text": "What if we add more elements to the converted list? Since returned List is fixed-size List, we can’t add more element(s). An attempt of adding more elements would cause UnsupportedOperationException.Consider the following example. " }, { "code": null, "e": 26138, "s": 26133, "text": "Java" }, { "code": "// Java program to demonstrate error// if we add more element(s) to// a fixed-size List.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {\"Rahul\", \"Utkarsh\", \"Shubham\", \"Neelam\"}; // Conversion of array to ArrayList // using Arrays.asList List al = Arrays.asList(geeks); System.out.println(al); // Adding some more values to the List. al.add(\"Shashank\"); al.add(\"Nishant\"); System.out.println(al); }}", "e": 26681, "s": 26138, "text": null }, { "code": null, "e": 26691, "s": 26681, "text": "Output: " }, { "code": null, "e": 26725, "s": 26691, "text": "[Rahul, Utkarsh, Shubham, Neelam]" }, { "code": null, "e": 26741, "s": 26725, "text": "Runtime error " }, { "code": null, "e": 26952, "s": 26741, "text": "Exception in thread \"main\" java.lang.UnsupportedOperationException\n at java.util.AbstractList.add(AbstractList.java:148)\n at java.util.AbstractList.add(AbstractList.java:108)\n at GFG.main(File.java:16)" }, { "code": null, "e": 27146, "s": 26952, "text": "It is therefore recommended to create new ArrayList and pass Arrays.asList(array reference) as an argument to it (i.e. as an constructor argument of ArrayList).Consider the following example: " }, { "code": null, "e": 27151, "s": 27146, "text": "Java" }, { "code": "// Java program to demonstrate how to add// one or more element(s) to returned// resizable List.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {\"Rahul\", \"Utkarsh\", \"Shubham\", \"Neelam\"}; List<String> al = new ArrayList<String>(Arrays.asList(geeks)); System.out.println(al); // Adding some more values to the List. al.add(\"Shashank\"); al.add(\"Nishant\"); System.out.println(\"\\nArrayList After adding two\" + \" more Geeks: \"); System.out.println(al); }}", "e": 27773, "s": 27151, "text": null }, { "code": null, "e": 27901, "s": 27773, "text": "[Rahul, Utkarsh, Shubham, Neelam]\n\nArrayList After adding two more Geeks: \n[Rahul, Utkarsh, Shubham, Neelam, Nishant, Shashank]" }, { "code": null, "e": 27909, "s": 27901, "text": "&nbap; " }, { "code": null, "e": 27953, "s": 27909, "text": "Method 2: Using Collections.addAll() method" }, { "code": null, "e": 28169, "s": 27955, "text": "Syntax: public static boolean addAll(Collection c, T... a)\n// Adds all of the specified elements to the specified collection.\n// Elements to be added may be specified individually or as an array.\n// T is generics" }, { "code": null, "e": 28664, "s": 28169, "text": "Note that there is a collection parameter c into which elements to be inserted and array parameter a contains the elements to insert into c. Return type is boolean type. It returns true if the collection changed as a result of the call.It throws UnsupportedOperationException if collection c does not support add method and throws IllegalArgumentException if some aspect of a value in elements(or elements of array) prevents it from being added to collection c.Consider the following example: " }, { "code": null, "e": 28669, "s": 28664, "text": "Java" }, { "code": "// Java program to demonstrate how to// add all elements of array to arrayList.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {\"Rahul\", \"Utkarsh\", \"Shubham\", \"Neelam\"}; List<String> al = new ArrayList<String>(); // adding elements of array to arrayList. Collections.addAll(al, geeks); System.out.println(al); }}", "e": 29095, "s": 28669, "text": null }, { "code": null, "e": 29105, "s": 29095, "text": "Output : " }, { "code": null, "e": 29139, "s": 29105, "text": "[Rahul, Utkarsh, Shubham, Neelam]" }, { "code": null, "e": 29263, "s": 29139, "text": "Adding null to the list Note : If the specified collection or specified array is null then it throw NullpointerException. " }, { "code": null, "e": 29268, "s": 29263, "text": "Java" }, { "code": "// Adding null to a listimport java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {\"Rahul\", \"Utkarsh\", \"Shubham\", \"Neelam\"}; List<String> al = new ArrayList<String>(); Collections.addAll(null, geeks); System.out.println(al); }}", "e": 29591, "s": 29268, "text": null }, { "code": null, "e": 29624, "s": 29591, "text": "Adding null to the end of list " }, { "code": null, "e": 29629, "s": 29624, "text": "Java" }, { "code": "import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {\"Rahul\", \"Utkarsh\", \"Shubham\", \"Neelam\"}; List<String> al = new ArrayList<String>(); Collections.addAll(al, null); System.out.println(al); }}", "e": 29926, "s": 29629, "text": null }, { "code": null, "e": 29942, "s": 29926, "text": "RunTime Error " }, { "code": null, "e": 30089, "s": 29942, "text": "Exception in thread \"main\" java.lang.NullPointerException\n at java.util.Collections.addAll(Collections.java:5401)\n at GFG.main(File.java:11)" }, { "code": null, "e": 30158, "s": 30092, "text": "Method 3: Using Manual method to convert Array using add() method" }, { "code": null, "e": 30296, "s": 30158, "text": "We can use this method if we don’t want to use java in built method(s). This is a manual method of adding all array’s elements to List. " }, { "code": null, "e": 30410, "s": 30296, "text": "Syntax: public boolean add(Object obj)\n// Appends the specified element to the end of this list.\n// Returns true." }, { "code": null, "e": 30417, "s": 30412, "text": "Java" }, { "code": "// Java program to convert a ArrayList to// an array using add() in a loop.import java.util.*; class GFG{ public static void main (String[] args) { String[] geeks = {\"Rahul\", \"Utkarsh\", \"Shubham\", \"Neelam\"}; List<String> al = new ArrayList<String>(); // Array to ArrayList Conversion for (String geek : geeks) al.add(geek); System.out.println(al); }}", "e": 30851, "s": 30417, "text": null }, { "code": null, "e": 30861, "s": 30851, "text": "Output: " }, { "code": null, "e": 30895, "s": 30861, "text": "[Rahul, Utkarsh, Shubham, Neelam]" }, { "code": null, "e": 31364, "s": 30895, "text": "Related Article: ArrayList to Array ConversionThis article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31375, "s": 31364, "text": "nidhi_biet" }, { "code": null, "e": 31385, "s": 31375, "text": "ruhelaa48" }, { "code": null, "e": 31405, "s": 31385, "text": "Java-Array-Programs" }, { "code": null, "e": 31420, "s": 31405, "text": "Java-ArrayList" }, { "code": null, "e": 31437, "s": 31420, "text": "Java-Collections" }, { "code": null, "e": 31447, "s": 31437, "text": "java-list" }, { "code": null, "e": 31466, "s": 31447, "text": "Java-List-Programs" }, { "code": null, "e": 31471, "s": 31466, "text": "Java" }, { "code": null, "e": 31476, "s": 31471, "text": "Java" }, { "code": null, "e": 31493, "s": 31476, "text": "Java-Collections" }, { "code": null, "e": 31591, "s": 31493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31600, "s": 31591, "text": "Comments" }, { "code": null, "e": 31613, "s": 31600, "text": "Old Comments" }, { "code": null, "e": 31664, "s": 31613, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31694, "s": 31664, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31725, "s": 31694, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31744, "s": 31725, "text": "Interfaces in Java" }, { "code": null, "e": 31776, "s": 31744, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31794, "s": 31776, "text": "ArrayList in Java" }, { "code": null, "e": 31814, "s": 31794, "text": "Stack Class in Java" }, { "code": null, "e": 31846, "s": 31814, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31870, "s": 31846, "text": "Singleton Class in Java" } ]
Tryit Editor v3.7
CSS Grid Intro Tryit: The row-gap property
[ { "code": null, "e": 24, "s": 9, "text": "CSS Grid Intro" } ]
Current Date and Time in Perl
Let's start with localtime() function in Perl, which returns values for the current date and time if given no arguments. Following is the 9-element list returned by the localtime function while using in list context − sec, # seconds of minutes from 0 to 61 min, # minutes of hour from 0 to 59 hour, # hours of day from 0 to 24 mday, # day of month from 1 to 31 mon, # month of year from 0 to 11 year, # year since 1900 wday, # days since sunday yday, # days since January 1st isdst # hours of daylight savings time Try the following example to print different elements returned by localtime() function − Live Demo #!/usr/local/bin/perl @months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); @days = qw(Sun Mon Tue Wed Thu Fri Sat Sun); ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); print "$mday $months[$mon] $days[$wday]\n"; When the above code is executed, it produces the following result − 16 Feb Sat If you will use localtime() function in the scalar context, then it will return date and time from the current time zone set in the system. Try the following example to print the current date and time in full format − Live Demo #!/usr/local/bin/perl $datestring = localtime(); print "Local date and time $datestring\n"; When the above code is executed, it produces the following result − Local date and time Sat Feb 16 06:50:45 2013
[ { "code": null, "e": 1280, "s": 1062, "text": "Let's start with localtime() function in Perl, which returns values for the current date and time if given no arguments. Following is the 9-element list returned by the localtime function while using in list context −" }, { "code": null, "e": 1577, "s": 1280, "text": "sec, # seconds of minutes from 0 to 61\nmin, # minutes of hour from 0 to 59\nhour, # hours of day from 0 to 24\nmday, # day of month from 1 to 31\nmon, # month of year from 0 to 11\nyear, # year since 1900\nwday, # days since sunday\nyday, # days since January 1st\nisdst # hours of daylight savings time" }, { "code": null, "e": 1666, "s": 1577, "text": "Try the following example to print different elements returned by localtime() function −" }, { "code": null, "e": 1677, "s": 1666, "text": " Live Demo" }, { "code": null, "e": 1922, "s": 1677, "text": "#!/usr/local/bin/perl\n@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );\n@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();\nprint \"$mday $months[$mon] $days[$wday]\\n\";" }, { "code": null, "e": 1990, "s": 1922, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 2001, "s": 1990, "text": "16 Feb Sat" }, { "code": null, "e": 2219, "s": 2001, "text": "If you will use localtime() function in the scalar context, then it will return date and time from the current time zone set in the system. Try the following example to print the current date and time in full format −" }, { "code": null, "e": 2230, "s": 2219, "text": " Live Demo" }, { "code": null, "e": 2322, "s": 2230, "text": "#!/usr/local/bin/perl\n$datestring = localtime();\nprint \"Local date and time $datestring\\n\";" }, { "code": null, "e": 2390, "s": 2322, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 2435, "s": 2390, "text": "Local date and time Sat Feb 16 06:50:45 2013" } ]
Simplify your Python Code: Automating Code Complexity Analysis with Wily | by Niels D. Goet | Towards Data Science
So you’ve written a piece of Python code and it does the job. Great, but is your code sufficiently simple? Complex code is difficult to read and makes code maintenance more costly. Catching complexity early can save time, money, and a lot of frustration. In this post, I’ll show you how to use the wily command-line tool to trace the complexity of your code over time. Code complexity matters. Unnecessarily complex code is harder to read, and more difficult to maintain. If your code is hard to understand, it’s harder to spot existing bugs and easier to introduce new ones. Clunky code complicates teamwork, and makes it hard to get new colleagues up to speed. There’s a reason why tech companies have complexity thresholds that must be met. Developers use several different measures of code complexity. Two such measures are universally represented in complexity analysis tools. First, the McCabe’s Cyclometic Complexity (CYC) relies on graph theory. Developed by Thomas McCabe in 1976, the metric is calculated from a function’s control flow graph, which consists of nodes and edges. Based on such a graph, we can calculate the CYC using the following formula: CYC = E – N + 2P In this formula, P is the number of predicate nodes (i.e. nodes that contain an if/else condition), E is the number of edges, and N is the number of nodes. CYC effectively is a measure of the number of independent paths through your module, giving some indication of how difficult the code is to understand, and how many unit tests would be required to achieve full test coverage (i.e. its “testability”). The higher the value of the CYC, the more complex your code. The Software Engineering Institute at Carnegie Mellon defines the following ranges (see this publication, p. 147): 1–10: low risk, simple program; 11–20: moderate risk, more difficult program; 21–50: high risk, very difficult program; > 50: very high risk, untestable program. Second, the maintainability index (MI) is a combination of the McCabe metric (C), the Halstead Volume (V), and Lines of Code (LoC). In formula1: MI = 171 - 5.2*ln(V) - 0.23*(C) - 16.2*ln(LoC) The MI is bound between 0 and 100 in theory but not in practice (most software implementations cap it at 100). The original paper introducing the metric noted the following thresholds: if your code’s MI is below 65 is is hard to maintain; if it’s 85 or higher, your code is easy to maintain. Anything between 65 and 85 is moderately maintainable (Coleman, Lowther, and Oman, 1994). The rescaled version (to between 0 and 100) used by Visual Studio2 puts the thresholds at 0 to 9 for low maintainability, 10–19 for moderate, and 20 and above for high maintainability respectively. (Please note that different IDEs and libraries may use different thresholds.) The CYC and MI should not be used in isolation to establish whether your code is overly complex or hard to maintain, for a number of reasons. First, these metrics do not account for other indicators of unnecessary complexity such as code duplication, nesting depth, or readability to a human. Second, the MI in particular suffers from bunch of problems that make it inconsistent. It was calibrated several decades ago and makes some rather dubious assumptions on how increases and decreases in some of the variables it uses contribute to overall complexity. (For a more detailed assessment of the shortcomings of the MI, check out this excellent blog post by Arie van Deursen, professor at the Delft University of Technology.) Finally, we should expect the MI’s values to differ depending on what framework you are analysing. A simple measure, like Lines of Code (LOC) may therefore be preferred. These limitations do give us some idea of when and how to use the CYC and MI. First, the MI cannot reliably be used to compare the complexity of two different systems, even if they are built using the same frameworks. Second, we cannot use hard cutoffs for when a piece of code is simple and maintainable enough because these metrics cannot be divorced from human evaluation and expert knowledge of a code base. Instead, the CYC and MI may be useful — in combination with other simpler metrics — if we treat them as heuristics that help us identify potential problems with our code. This can be particularly useful if we evaluate our code regularly, and observe how the metrics evolve over time. Sudden and large changes should catch our attention and prompt us to investigate further. Needless to say: as with most code quality tools, the CYC and MI should complement quality control in your development workflow, not replace it. In the remainder of this post, I’ll show you how to integrate wily in your Python development workflow to perform complexity analyses for you at every new code commit. Wily is a command-line tool that allows you to analyse, track, and visualise the complexity and maintainability of your Python code. While the mccabe and radon libraries offer similar functionalities, wily has some nice features that allow us to trace complexity over time with relative ease. Check out the video below for an introduction to wily by its author, Anthony Shaw. Detecting code complexity is only as useful as the frequency with which you perform the analysis. If you regularly check your code complexity, you can easily spot sudden increases. Such outliers are not necessarily problematic, but they should prompt you to investigate. The best way to ensure you get these insights frequently is to include wily in your project’s pre-commit hooks. Pre-commit hooks are small “scripts” that are run locally on staged files when using the git commit command. (If you’d like to learn more about pre-commit hooks, you may be interested in my post on using pre-commit hooks to automatically enforce code style.) To get started with pre-commit hooks, first install the pre-commit library using terminal (instructions for Homebrew and Conda are available on this page): pip install pre-commit You can check whether your installation was successful using the command below. This command should return the version of your pre-commit installation. pre-commit --version After you’ve installed pre-commit, create a .yaml file. Your .yaml file specifies your pre-commit hooks configuration. Use the following command in terminal to create a new .yamlfile in your project directory: nano .pre-commit-config.yaml Subsequently, add the following configuration: repos:- repo: local hooks: - id: wily name: wily entry: wily diff verbose: true language: python additional_dependencies: [wily] Now that you have installed the pre-commit package and set up your .yamlfile, you’re all set to use pre-commit with wily to analyse code complexity. To get started, first run the following command in terminal to install the pre-commit hooks: pre-commit install After you’ve installed the pre-commit hooks, the pre-commit command will be executed every time you commit a change to git. Optionally, you can run the pre-commit hooks directly from terminal by using the following command: pre-commit run Before you can use wily with pre-commit, you’ll have to go run wily build from terminal. The build command compiles a cache of the complexity changes of your code in your last 50 commits. You need this cache so that wily can compute metrics across your commits. Alternatively, you can use wily setup and follow the instructions in terminal. After you’ve set up and configured pre-commit and created your wily cache, the wily diff command will be run automatically upon every new commit. Upon a new commit, your terminal output will show the complexity of the version of the code in your current commit compared to the previous revision. The output below shows an example of wily’s diff report after removing some lines of code. We obtain four scores, including Lines of Code (LOC), Unique Operands, and the Cyclomatic Complexity and Maintainability Index. If your complexity increases dramatically after a relatively small change, you should probably pause and reconsider the changes you’ve just made. Getting an overview of how your code changed between two commits is useful, but does not give us that much data to work with. To identify and prioritise potential problem areas, we have to consider how a specific module changed over time. To get this information, run the following commands in terminal: wily buildwily report <my-module-name> As shown in the example below, the report command will produce a CLI table of the changes in complexity metrics between all commits for the specified module. This report allows you to easily spot changes, as well as patterns and trends in complexity, and where you might have gone wrong. Another useful command to identify (potentially) problematic modules within a larger project is wily rank, which will show the maintainability index of your different modules. In this case all values are above 75, meaning they’re easy to maintain. (Do note the caveats with using the maintainability index that I’ve outlined earlier in this post). Finally, it’s easiest to spot trends when plotting the complexity of a piece of code across different commits. You can visualise a module’s complexity report using the graph command, e.g.: wily graph create_tables.py loc sloc complexity This command will produce a plot of the create_tables.py module (see below), showing the lines of code on the y-axis, the commits on the x-axis, and the complexity represented by the size of the bubbles on each observation. Combined, wily’s diff, report, rank, and graph commands can give you useful information on whether your code is becoming unnecessarily complex. Writing simple, clear, and legible code is challenging. While code style and (unit) testing can to a large degree be automated, the design of your code itself is still a human task. That is, if the latest advancements in machine programming do not make developers obsolete. Automating complexity analysis can help you make informed decisions about when to reconsider your code, and what areas of your code base to prioritise. These analyses can never replace a proper code design process, but it can go a long way to avoiding unnecessary mistakes and catching potential problems during the development process. Thanks for reading! 1 Original version of the MI. Note that different versions of the MI exist. See, e.g. Radon’s documentation on this metric. 2 Visual Studio’s rescaled MI can be calculated using the following formula: MAX(0,(171–5.2*ln(V) — 0.23 * (C) — 16.2*ln(LoC))*100 / 171). See this article for further details. Support my work: If you liked this article and you’d like to support my work, please consider becoming a paying Medium member via my referral page. The price of the subscription is the same if you sign up via my referral page, but I will receive part of your monthly membership fee. Are you interested in learning more about automating your Python development process? Check out some of my earlier posts on this topic: towardsdatascience.com medium.com Please read this disclaimer carefully before relying on any of the content in my articles on Medium.com.
[ { "code": null, "e": 541, "s": 172, "text": "So you’ve written a piece of Python code and it does the job. Great, but is your code sufficiently simple? Complex code is difficult to read and makes code maintenance more costly. Catching complexity early can save time, money, and a lot of frustration. In this post, I’ll show you how to use the wily command-line tool to trace the complexity of your code over time." }, { "code": null, "e": 916, "s": 541, "text": "Code complexity matters. Unnecessarily complex code is harder to read, and more difficult to maintain. If your code is hard to understand, it’s harder to spot existing bugs and easier to introduce new ones. Clunky code complicates teamwork, and makes it hard to get new colleagues up to speed. There’s a reason why tech companies have complexity thresholds that must be met." }, { "code": null, "e": 1054, "s": 916, "text": "Developers use several different measures of code complexity. Two such measures are universally represented in complexity analysis tools." }, { "code": null, "e": 1260, "s": 1054, "text": "First, the McCabe’s Cyclometic Complexity (CYC) relies on graph theory. Developed by Thomas McCabe in 1976, the metric is calculated from a function’s control flow graph, which consists of nodes and edges." }, { "code": null, "e": 1337, "s": 1260, "text": "Based on such a graph, we can calculate the CYC using the following formula:" }, { "code": null, "e": 1354, "s": 1337, "text": "CYC = E – N + 2P" }, { "code": null, "e": 1760, "s": 1354, "text": "In this formula, P is the number of predicate nodes (i.e. nodes that contain an if/else condition), E is the number of edges, and N is the number of nodes. CYC effectively is a measure of the number of independent paths through your module, giving some indication of how difficult the code is to understand, and how many unit tests would be required to achieve full test coverage (i.e. its “testability”)." }, { "code": null, "e": 1936, "s": 1760, "text": "The higher the value of the CYC, the more complex your code. The Software Engineering Institute at Carnegie Mellon defines the following ranges (see this publication, p. 147):" }, { "code": null, "e": 1968, "s": 1936, "text": "1–10: low risk, simple program;" }, { "code": null, "e": 2014, "s": 1968, "text": "11–20: moderate risk, more difficult program;" }, { "code": null, "e": 2056, "s": 2014, "text": "21–50: high risk, very difficult program;" }, { "code": null, "e": 2098, "s": 2056, "text": "> 50: very high risk, untestable program." }, { "code": null, "e": 2243, "s": 2098, "text": "Second, the maintainability index (MI) is a combination of the McCabe metric (C), the Halstead Volume (V), and Lines of Code (LoC). In formula1:" }, { "code": null, "e": 2290, "s": 2243, "text": "MI = 171 - 5.2*ln(V) - 0.23*(C) - 16.2*ln(LoC)" }, { "code": null, "e": 2948, "s": 2290, "text": "The MI is bound between 0 and 100 in theory but not in practice (most software implementations cap it at 100). The original paper introducing the metric noted the following thresholds: if your code’s MI is below 65 is is hard to maintain; if it’s 85 or higher, your code is easy to maintain. Anything between 65 and 85 is moderately maintainable (Coleman, Lowther, and Oman, 1994). The rescaled version (to between 0 and 100) used by Visual Studio2 puts the thresholds at 0 to 9 for low maintainability, 10–19 for moderate, and 20 and above for high maintainability respectively. (Please note that different IDEs and libraries may use different thresholds.)" }, { "code": null, "e": 3090, "s": 2948, "text": "The CYC and MI should not be used in isolation to establish whether your code is overly complex or hard to maintain, for a number of reasons." }, { "code": null, "e": 3675, "s": 3090, "text": "First, these metrics do not account for other indicators of unnecessary complexity such as code duplication, nesting depth, or readability to a human. Second, the MI in particular suffers from bunch of problems that make it inconsistent. It was calibrated several decades ago and makes some rather dubious assumptions on how increases and decreases in some of the variables it uses contribute to overall complexity. (For a more detailed assessment of the shortcomings of the MI, check out this excellent blog post by Arie van Deursen, professor at the Delft University of Technology.)" }, { "code": null, "e": 3845, "s": 3675, "text": "Finally, we should expect the MI’s values to differ depending on what framework you are analysing. A simple measure, like Lines of Code (LOC) may therefore be preferred." }, { "code": null, "e": 4257, "s": 3845, "text": "These limitations do give us some idea of when and how to use the CYC and MI. First, the MI cannot reliably be used to compare the complexity of two different systems, even if they are built using the same frameworks. Second, we cannot use hard cutoffs for when a piece of code is simple and maintainable enough because these metrics cannot be divorced from human evaluation and expert knowledge of a code base." }, { "code": null, "e": 4776, "s": 4257, "text": "Instead, the CYC and MI may be useful — in combination with other simpler metrics — if we treat them as heuristics that help us identify potential problems with our code. This can be particularly useful if we evaluate our code regularly, and observe how the metrics evolve over time. Sudden and large changes should catch our attention and prompt us to investigate further. Needless to say: as with most code quality tools, the CYC and MI should complement quality control in your development workflow, not replace it." }, { "code": null, "e": 5320, "s": 4776, "text": "In the remainder of this post, I’ll show you how to integrate wily in your Python development workflow to perform complexity analyses for you at every new code commit. Wily is a command-line tool that allows you to analyse, track, and visualise the complexity and maintainability of your Python code. While the mccabe and radon libraries offer similar functionalities, wily has some nice features that allow us to trace complexity over time with relative ease. Check out the video below for an introduction to wily by its author, Anthony Shaw." }, { "code": null, "e": 5703, "s": 5320, "text": "Detecting code complexity is only as useful as the frequency with which you perform the analysis. If you regularly check your code complexity, you can easily spot sudden increases. Such outliers are not necessarily problematic, but they should prompt you to investigate. The best way to ensure you get these insights frequently is to include wily in your project’s pre-commit hooks." }, { "code": null, "e": 5962, "s": 5703, "text": "Pre-commit hooks are small “scripts” that are run locally on staged files when using the git commit command. (If you’d like to learn more about pre-commit hooks, you may be interested in my post on using pre-commit hooks to automatically enforce code style.)" }, { "code": null, "e": 6118, "s": 5962, "text": "To get started with pre-commit hooks, first install the pre-commit library using terminal (instructions for Homebrew and Conda are available on this page):" }, { "code": null, "e": 6141, "s": 6118, "text": "pip install pre-commit" }, { "code": null, "e": 6293, "s": 6141, "text": "You can check whether your installation was successful using the command below. This command should return the version of your pre-commit installation." }, { "code": null, "e": 6314, "s": 6293, "text": "pre-commit --version" }, { "code": null, "e": 6524, "s": 6314, "text": "After you’ve installed pre-commit, create a .yaml file. Your .yaml file specifies your pre-commit hooks configuration. Use the following command in terminal to create a new .yamlfile in your project directory:" }, { "code": null, "e": 6553, "s": 6524, "text": "nano .pre-commit-config.yaml" }, { "code": null, "e": 6600, "s": 6553, "text": "Subsequently, add the following configuration:" }, { "code": null, "e": 6774, "s": 6600, "text": "repos:- repo: local hooks: - id: wily name: wily entry: wily diff verbose: true language: python additional_dependencies: [wily]" }, { "code": null, "e": 7016, "s": 6774, "text": "Now that you have installed the pre-commit package and set up your .yamlfile, you’re all set to use pre-commit with wily to analyse code complexity. To get started, first run the following command in terminal to install the pre-commit hooks:" }, { "code": null, "e": 7035, "s": 7016, "text": "pre-commit install" }, { "code": null, "e": 7259, "s": 7035, "text": "After you’ve installed the pre-commit hooks, the pre-commit command will be executed every time you commit a change to git. Optionally, you can run the pre-commit hooks directly from terminal by using the following command:" }, { "code": null, "e": 7274, "s": 7259, "text": "pre-commit run" }, { "code": null, "e": 7615, "s": 7274, "text": "Before you can use wily with pre-commit, you’ll have to go run wily build from terminal. The build command compiles a cache of the complexity changes of your code in your last 50 commits. You need this cache so that wily can compute metrics across your commits. Alternatively, you can use wily setup and follow the instructions in terminal." }, { "code": null, "e": 8276, "s": 7615, "text": "After you’ve set up and configured pre-commit and created your wily cache, the wily diff command will be run automatically upon every new commit. Upon a new commit, your terminal output will show the complexity of the version of the code in your current commit compared to the previous revision. The output below shows an example of wily’s diff report after removing some lines of code. We obtain four scores, including Lines of Code (LOC), Unique Operands, and the Cyclomatic Complexity and Maintainability Index. If your complexity increases dramatically after a relatively small change, you should probably pause and reconsider the changes you’ve just made." }, { "code": null, "e": 8580, "s": 8276, "text": "Getting an overview of how your code changed between two commits is useful, but does not give us that much data to work with. To identify and prioritise potential problem areas, we have to consider how a specific module changed over time. To get this information, run the following commands in terminal:" }, { "code": null, "e": 8619, "s": 8580, "text": "wily buildwily report <my-module-name>" }, { "code": null, "e": 8907, "s": 8619, "text": "As shown in the example below, the report command will produce a CLI table of the changes in complexity metrics between all commits for the specified module. This report allows you to easily spot changes, as well as patterns and trends in complexity, and where you might have gone wrong." }, { "code": null, "e": 9255, "s": 8907, "text": "Another useful command to identify (potentially) problematic modules within a larger project is wily rank, which will show the maintainability index of your different modules. In this case all values are above 75, meaning they’re easy to maintain. (Do note the caveats with using the maintainability index that I’ve outlined earlier in this post)." }, { "code": null, "e": 9444, "s": 9255, "text": "Finally, it’s easiest to spot trends when plotting the complexity of a piece of code across different commits. You can visualise a module’s complexity report using the graph command, e.g.:" }, { "code": null, "e": 9492, "s": 9444, "text": "wily graph create_tables.py loc sloc complexity" }, { "code": null, "e": 9716, "s": 9492, "text": "This command will produce a plot of the create_tables.py module (see below), showing the lines of code on the y-axis, the commits on the x-axis, and the complexity represented by the size of the bubbles on each observation." }, { "code": null, "e": 9860, "s": 9716, "text": "Combined, wily’s diff, report, rank, and graph commands can give you useful information on whether your code is becoming unnecessarily complex." }, { "code": null, "e": 10471, "s": 9860, "text": "Writing simple, clear, and legible code is challenging. While code style and (unit) testing can to a large degree be automated, the design of your code itself is still a human task. That is, if the latest advancements in machine programming do not make developers obsolete. Automating complexity analysis can help you make informed decisions about when to reconsider your code, and what areas of your code base to prioritise. These analyses can never replace a proper code design process, but it can go a long way to avoiding unnecessary mistakes and catching potential problems during the development process." }, { "code": null, "e": 10491, "s": 10471, "text": "Thanks for reading!" }, { "code": null, "e": 10615, "s": 10491, "text": "1 Original version of the MI. Note that different versions of the MI exist. See, e.g. Radon’s documentation on this metric." }, { "code": null, "e": 10792, "s": 10615, "text": "2 Visual Studio’s rescaled MI can be calculated using the following formula: MAX(0,(171–5.2*ln(V) — 0.23 * (C) — 16.2*ln(LoC))*100 / 171). See this article for further details." }, { "code": null, "e": 11075, "s": 10792, "text": "Support my work: If you liked this article and you’d like to support my work, please consider becoming a paying Medium member via my referral page. The price of the subscription is the same if you sign up via my referral page, but I will receive part of your monthly membership fee." }, { "code": null, "e": 11211, "s": 11075, "text": "Are you interested in learning more about automating your Python development process? Check out some of my earlier posts on this topic:" }, { "code": null, "e": 11234, "s": 11211, "text": "towardsdatascience.com" }, { "code": null, "e": 11245, "s": 11234, "text": "medium.com" } ]
id command in Linux with examples - GeeksforGeeks
22 May, 2019 id command in Linux is used to find out user and group names and numeric ID’s (UID or group ID) of the current user or any other user in the server. This command is useful to find out the following information as listed below: User name and real user id. Find out the specific Users UID. Show the UID and all groups associated with a user. List out all the groups a user belongs to. Display security context of the current user. Synopsis: id [OPTION]... [USER] Options: -g : Print only the effective group id. -G : Print all Group ID’s. -n : Prints name instead of number. -r : Prints real ID instead of numbers. -u : Prints only the effective user ID. –help : Display help messages and exit. –version : Display the version information and exit. Note: Without any OPTION it prints every set of identified information i.e. numeric ID’s. Examples: To print your own id without any Options:idThe output shows the ID of current user UID and GID. id The output shows the ID of current user UID and GID. To find a specific users id: Now assume that we have a user named master, to find his UID we will use the command:id -u master id -u master To find a specific users GID: Again assuming to find GID of master, we will use the command:id -g master id -g master To find out UID and all groups associated with a username: In this case we will use the user “master” to find UID and all groups associated with it, use command:id master id master To find out all the groups a user belongs to: Displaying the UID and all groups a user “master” belongs to:id -G master id -G master To display a name instead of numbers: By default the id command shows us the UDI and GID in numbers which a user may not understand, with use of -n option with -u, -g and -G, use command(s)id -ng master or id -nu master or id -nG master id -ng master or id -nu master or id -nG master To display real id instead of effective id: To show the real id with the use of -r option with -g, -u and -G, use command(s):id -r -g master id -r -u master id -r -G master id -r -g master id -r -u master id -r -G master linux-command Linux-misc-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 ZIP command in Linux with examples tar command in Linux with examples SORT command in Linux/Unix with examples UDP Server-Client implementation in C curl command in Linux with Examples 'crontab' in Linux with Examples Conditional Statements | Shell Script diff command in Linux with examples Cat command in Linux with examples
[ { "code": null, "e": 24530, "s": 24502, "text": "\n22 May, 2019" }, { "code": null, "e": 24757, "s": 24530, "text": "id command in Linux is used to find out user and group names and numeric ID’s (UID or group ID) of the current user or any other user in the server. This command is useful to find out the following information as listed below:" }, { "code": null, "e": 24785, "s": 24757, "text": "User name and real user id." }, { "code": null, "e": 24818, "s": 24785, "text": "Find out the specific Users UID." }, { "code": null, "e": 24870, "s": 24818, "text": "Show the UID and all groups associated with a user." }, { "code": null, "e": 24913, "s": 24870, "text": "List out all the groups a user belongs to." }, { "code": null, "e": 24959, "s": 24913, "text": "Display security context of the current user." }, { "code": null, "e": 24969, "s": 24959, "text": "Synopsis:" }, { "code": null, "e": 24991, "s": 24969, "text": "id [OPTION]... [USER]" }, { "code": null, "e": 25000, "s": 24991, "text": "Options:" }, { "code": null, "e": 25040, "s": 25000, "text": "-g : Print only the effective group id." }, { "code": null, "e": 25067, "s": 25040, "text": "-G : Print all Group ID’s." }, { "code": null, "e": 25103, "s": 25067, "text": "-n : Prints name instead of number." }, { "code": null, "e": 25143, "s": 25103, "text": "-r : Prints real ID instead of numbers." }, { "code": null, "e": 25183, "s": 25143, "text": "-u : Prints only the effective user ID." }, { "code": null, "e": 25223, "s": 25183, "text": "–help : Display help messages and exit." }, { "code": null, "e": 25276, "s": 25223, "text": "–version : Display the version information and exit." }, { "code": null, "e": 25366, "s": 25276, "text": "Note: Without any OPTION it prints every set of identified information i.e. numeric ID’s." }, { "code": null, "e": 25376, "s": 25366, "text": "Examples:" }, { "code": null, "e": 25472, "s": 25376, "text": "To print your own id without any Options:idThe output shows the ID of current user UID and GID." }, { "code": null, "e": 25475, "s": 25472, "text": "id" }, { "code": null, "e": 25528, "s": 25475, "text": "The output shows the ID of current user UID and GID." }, { "code": null, "e": 25655, "s": 25528, "text": "To find a specific users id: Now assume that we have a user named master, to find his UID we will use the command:id -u master" }, { "code": null, "e": 25668, "s": 25655, "text": "id -u master" }, { "code": null, "e": 25773, "s": 25668, "text": "To find a specific users GID: Again assuming to find GID of master, we will use the command:id -g master" }, { "code": null, "e": 25786, "s": 25773, "text": "id -g master" }, { "code": null, "e": 25957, "s": 25786, "text": "To find out UID and all groups associated with a username: In this case we will use the user “master” to find UID and all groups associated with it, use command:id master" }, { "code": null, "e": 25967, "s": 25957, "text": "id master" }, { "code": null, "e": 26087, "s": 25967, "text": "To find out all the groups a user belongs to: Displaying the UID and all groups a user “master” belongs to:id -G master" }, { "code": null, "e": 26100, "s": 26087, "text": "id -G master" }, { "code": null, "e": 26339, "s": 26100, "text": "To display a name instead of numbers: By default the id command shows us the UDI and GID in numbers which a user may not understand, with use of -n option with -u, -g and -G, use command(s)id -ng master \nor\nid -nu master\nor\nid -nG master\n" }, { "code": null, "e": 26389, "s": 26339, "text": "id -ng master \nor\nid -nu master\nor\nid -nG master\n" }, { "code": null, "e": 26563, "s": 26389, "text": "To display real id instead of effective id: To show the real id with the use of -r option with -g, -u and -G, use command(s):id -r -g master\nid -r -u master\nid -r -G master\n" }, { "code": null, "e": 26612, "s": 26563, "text": "id -r -g master\nid -r -u master\nid -r -G master\n" }, { "code": null, "e": 26626, "s": 26612, "text": "linux-command" }, { "code": null, "e": 26646, "s": 26626, "text": "Linux-misc-commands" }, { "code": null, "e": 26653, "s": 26646, "text": "Picked" }, { "code": null, "e": 26664, "s": 26653, "text": "Linux-Unix" }, { "code": null, "e": 26762, "s": 26664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26771, "s": 26762, "text": "Comments" }, { "code": null, "e": 26784, "s": 26771, "text": "Old Comments" }, { "code": null, "e": 26822, "s": 26784, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26857, "s": 26822, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 26892, "s": 26857, "text": "tar command in Linux with examples" }, { "code": null, "e": 26933, "s": 26892, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 26971, "s": 26933, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27007, "s": 26971, "text": "curl command in Linux with Examples" }, { "code": null, "e": 27040, "s": 27007, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 27078, "s": 27040, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 27114, "s": 27078, "text": "diff command in Linux with examples" } ]
C Library - <limits.h>
The limits.h header determines various properties of the various variable types. The macros defined in this header, limits the values of various variable types like char, int and long. These limits specify that a variable cannot store any value beyond these limits, for example an unsigned character can store up to a maximum value of 255. The following values are implementation-specific and defined with the #define directive, but these values may not be any lower than what is given here. The following example shows the usage of few of the constants defined in limits.h file. #include <stdio.h> #include <limits.h> int main() { printf("The number of bits in a byte %d\n", CHAR_BIT); printf("The minimum value of SIGNED CHAR = %d\n", SCHAR_MIN); printf("The maximum value of SIGNED CHAR = %d\n", SCHAR_MAX); printf("The maximum value of UNSIGNED CHAR = %d\n", UCHAR_MAX); printf("The minimum value of SHORT INT = %d\n", SHRT_MIN); printf("The maximum value of SHORT INT = %d\n", SHRT_MAX); printf("The minimum value of INT = %d\n", INT_MIN); printf("The maximum value of INT = %d\n", INT_MAX); printf("The minimum value of CHAR = %d\n", CHAR_MIN); printf("The maximum value of CHAR = %d\n", CHAR_MAX); printf("The minimum value of LONG = %ld\n", LONG_MIN); printf("The maximum value of LONG = %ld\n", LONG_MAX); return(0); } Let us compile and run the above program that will produce the following result − The number of bits in a byte 8 The minimum value of SIGNED CHAR = -128 The maximum value of SIGNED CHAR = 127 The maximum value of UNSIGNED CHAR = 255 The minimum value of SHORT INT = -32768 The maximum value of SHORT INT = 32767 The minimum value of INT = -2147483648 The maximum value of INT = 2147483647 The minimum value of CHAR = -128 The maximum value of CHAR = 127 The minimum value of LONG = -9223372036854775808 The maximum value of LONG = 9223372036854775807 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2192, "s": 2007, "text": "The limits.h header determines various properties of the various variable types. The macros defined in this header, limits the values of various variable types like char, int and long." }, { "code": null, "e": 2347, "s": 2192, "text": "These limits specify that a variable cannot store any value beyond these limits, for example an unsigned character can store up to a maximum value of 255." }, { "code": null, "e": 2499, "s": 2347, "text": "The following values are implementation-specific and defined with the #define directive, but these values may not be any lower than what is given here." }, { "code": null, "e": 2587, "s": 2499, "text": "The following example shows the usage of few of the constants defined in limits.h file." }, { "code": null, "e": 3385, "s": 2587, "text": "#include <stdio.h>\n#include <limits.h>\n\nint main() {\n\n printf(\"The number of bits in a byte %d\\n\", CHAR_BIT);\n\n printf(\"The minimum value of SIGNED CHAR = %d\\n\", SCHAR_MIN);\n printf(\"The maximum value of SIGNED CHAR = %d\\n\", SCHAR_MAX);\n printf(\"The maximum value of UNSIGNED CHAR = %d\\n\", UCHAR_MAX);\n\n printf(\"The minimum value of SHORT INT = %d\\n\", SHRT_MIN);\n printf(\"The maximum value of SHORT INT = %d\\n\", SHRT_MAX); \n\n printf(\"The minimum value of INT = %d\\n\", INT_MIN);\n printf(\"The maximum value of INT = %d\\n\", INT_MAX);\n\n printf(\"The minimum value of CHAR = %d\\n\", CHAR_MIN);\n printf(\"The maximum value of CHAR = %d\\n\", CHAR_MAX);\n\n printf(\"The minimum value of LONG = %ld\\n\", LONG_MIN);\n printf(\"The maximum value of LONG = %ld\\n\", LONG_MAX);\n \n return(0);\n}" }, { "code": null, "e": 3467, "s": 3385, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3937, "s": 3467, "text": "The number of bits in a byte 8\nThe minimum value of SIGNED CHAR = -128\nThe maximum value of SIGNED CHAR = 127\nThe maximum value of UNSIGNED CHAR = 255\nThe minimum value of SHORT INT = -32768\nThe maximum value of SHORT INT = 32767\nThe minimum value of INT = -2147483648\nThe maximum value of INT = 2147483647\nThe minimum value of CHAR = -128\nThe maximum value of CHAR = 127\nThe minimum value of LONG = -9223372036854775808\nThe maximum value of LONG = 9223372036854775807\n" }, { "code": null, "e": 3970, "s": 3937, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3985, "s": 3970, "text": " Nishant Malik" }, { "code": null, "e": 4020, "s": 3985, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4035, "s": 4020, "text": " Nishant Malik" }, { "code": null, "e": 4070, "s": 4035, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4084, "s": 4070, "text": " Asif Hussain" }, { "code": null, "e": 4117, "s": 4084, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4135, "s": 4117, "text": " Richa Maheshwari" }, { "code": null, "e": 4170, "s": 4135, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4189, "s": 4170, "text": " Vandana Annavaram" }, { "code": null, "e": 4222, "s": 4189, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4234, "s": 4222, "text": " Amit Diwan" }, { "code": null, "e": 4241, "s": 4234, "text": " Print" }, { "code": null, "e": 4252, "s": 4241, "text": " Add Notes" } ]
DAX Other - VAR function
Stores the result of an expression as a named variable, which can then be passed as a parameter to other calculated field expressions. Once the resultant values have been calculated for a variable expression, those values do not change, even if the variable is referenced in another expression. DAX VAR function is new in Excel 2016. VAR <name> = <expression> name The name of the variable (identifier). Delimiters are not supported. For e.g. ‘varName’ or [varName] will result in an error. Delimiters are not supported. For e.g. ‘varName’ or [varName] will result in an error. Supported character set: a-z, A-Z, 0-9. 0-9 are not valid as first character. __ (double underscore) is allowed as a prefix to the identifier name. No other special characters are supported. Supported character set: a-z, A-Z, 0-9. 0-9 are not valid as first character. 0-9 are not valid as first character. __ (double underscore) is allowed as a prefix to the identifier name. No other special characters are supported. __ (double underscore) is allowed as a prefix to the identifier name. No other special characters are supported. Reserved keywords not allowed. Reserved keywords not allowed. Names of the existing tables are not allowed. Names of the existing tables are not allowed. Empty spaces are not allowed. Empty spaces are not allowed. expression A DAX expression which returns a scalar or table value. A named variable containing the result of the expression parameter. An expression passed as a parameter to VAR can contain another VAR declaration. When referencing a variable − Calculated fields cannot refer to variables defined outside the calculated field expression, but can refer to functional scope variables defined within the expression. Calculated fields cannot refer to variables defined outside the calculated field expression, but can refer to functional scope variables defined within the expression. Variables can refer to calculated fields. Variables can refer to calculated fields. Variables can refer to previously defined variables. Variables can refer to previously defined variables. Columns in table variables cannot be referenced via TableName[ColumnName] syntax. Columns in table variables cannot be referenced via TableName[ColumnName] syntax. = Var SouthSales = SUMX(FILTER(Sales,Sales[Region]="South") ,Sales[Sales Amount]) Var EastSales = SUMX(FILTER(Sales,Sales[Region]="East") ,Sales[Sales Amount]) return SouthSales+EastSales 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2296, "s": 2001, "text": "Stores the result of an expression as a named variable, which can then be passed as a parameter to other calculated field expressions. Once the resultant values have been calculated for a variable expression, those values do not change, even if the variable is referenced in another expression." }, { "code": null, "e": 2335, "s": 2296, "text": "DAX VAR function is new in Excel 2016." }, { "code": null, "e": 2363, "s": 2335, "text": "VAR <name> = <expression> \n" }, { "code": null, "e": 2368, "s": 2363, "text": "name" }, { "code": null, "e": 2407, "s": 2368, "text": "The name of the variable (identifier)." }, { "code": null, "e": 2494, "s": 2407, "text": "Delimiters are not supported. For e.g. ‘varName’ or [varName] will result in an error." }, { "code": null, "e": 2581, "s": 2494, "text": "Delimiters are not supported. For e.g. ‘varName’ or [varName] will result in an error." }, { "code": null, "e": 2775, "s": 2581, "text": "Supported character set: a-z, A-Z, 0-9.\n\n0-9 are not valid as first character.\n__ (double underscore) is allowed as a prefix to the identifier name. No other special characters are supported.\n\n" }, { "code": null, "e": 2815, "s": 2775, "text": "Supported character set: a-z, A-Z, 0-9." }, { "code": null, "e": 2853, "s": 2815, "text": "0-9 are not valid as first character." }, { "code": null, "e": 2891, "s": 2853, "text": "0-9 are not valid as first character." }, { "code": null, "e": 3004, "s": 2891, "text": "__ (double underscore) is allowed as a prefix to the identifier name. No other special characters are supported." }, { "code": null, "e": 3117, "s": 3004, "text": "__ (double underscore) is allowed as a prefix to the identifier name. No other special characters are supported." }, { "code": null, "e": 3148, "s": 3117, "text": "Reserved keywords not allowed." }, { "code": null, "e": 3179, "s": 3148, "text": "Reserved keywords not allowed." }, { "code": null, "e": 3225, "s": 3179, "text": "Names of the existing tables are not allowed." }, { "code": null, "e": 3271, "s": 3225, "text": "Names of the existing tables are not allowed." }, { "code": null, "e": 3301, "s": 3271, "text": "Empty spaces are not allowed." }, { "code": null, "e": 3331, "s": 3301, "text": "Empty spaces are not allowed." }, { "code": null, "e": 3342, "s": 3331, "text": "expression" }, { "code": null, "e": 3398, "s": 3342, "text": "A DAX expression which returns a scalar or table value." }, { "code": null, "e": 3466, "s": 3398, "text": "A named variable containing the result of the expression parameter." }, { "code": null, "e": 3546, "s": 3466, "text": "An expression passed as a parameter to VAR can contain another VAR declaration." }, { "code": null, "e": 3576, "s": 3546, "text": "When referencing a variable −" }, { "code": null, "e": 3744, "s": 3576, "text": "Calculated fields cannot refer to variables defined outside the calculated field expression, but can refer to functional scope variables defined within the expression." }, { "code": null, "e": 3912, "s": 3744, "text": "Calculated fields cannot refer to variables defined outside the calculated field expression, but can refer to functional scope variables defined within the expression." }, { "code": null, "e": 3954, "s": 3912, "text": "Variables can refer to calculated fields." }, { "code": null, "e": 3996, "s": 3954, "text": "Variables can refer to calculated fields." }, { "code": null, "e": 4049, "s": 3996, "text": "Variables can refer to previously defined variables." }, { "code": null, "e": 4102, "s": 4049, "text": "Variables can refer to previously defined variables." }, { "code": null, "e": 4184, "s": 4102, "text": "Columns in table variables cannot be referenced via TableName[ColumnName] syntax." }, { "code": null, "e": 4266, "s": 4184, "text": "Columns in table variables cannot be referenced via TableName[ColumnName] syntax." }, { "code": null, "e": 4455, "s": 4266, "text": "= Var SouthSales = SUMX(FILTER(Sales,Sales[Region]=\"South\")\n,Sales[Sales Amount]) Var EastSales = SUMX(FILTER(Sales,Sales[Region]=\"East\")\n,Sales[Sales Amount]) return SouthSales+EastSales " }, { "code": null, "e": 4490, "s": 4455, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4504, "s": 4490, "text": " Abhay Gadiya" }, { "code": null, "e": 4537, "s": 4504, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4551, "s": 4537, "text": " Randy Minder" }, { "code": null, "e": 4586, "s": 4551, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4600, "s": 4586, "text": " Randy Minder" }, { "code": null, "e": 4607, "s": 4600, "text": " Print" }, { "code": null, "e": 4618, "s": 4607, "text": " Add Notes" } ]
Difference between Structure and Union in C
Structure is a user defined datatype. It is used to combine different types of data into a single type. It can have multiple members and structure variables. The keyword “struct” is used to define structures in C language. Structure members can be accessed by using dot(.) operator. Here is the syntax of structures in C language, struct structure_name { member definition; } structure_variables; Here, structure_name − Any name given to the structure. structure_name − Any name given to the structure. member definition − Set of member variables. member definition − Set of member variables. structure_variable − This is the object of structure. structure_variable − This is the object of structure. Here is an example of structures in C language, Live Demo #include <stdio.h> #include <string.h> struct Data { int i; long int f; } data, data1; int main( ) { data.i = 28; printf("The value of i : %d\n", (data.i)); printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1)); return 0; } Here is the output The value of i : 28 Memory size occupied by data : 16 16 Union is also a user defined datatype. All the members of union share the same memory location. Size of union is decided by the size of largest member of union. If you want to use same memory location for two or more members, union is the best for that. Unions are similar to the structure. Union variables are created in same manner as structure variables. The keyword “union” is used to define unions in C language. Here is the syntax of unions in C language, union union_name { member definition; } union_variables; Here, union_name − Any name given to the union. union_name − Any name given to the union. member definition − Set of member variables. member definition − Set of member variables. union_variable − This is the object of union. union_variable − This is the object of union. Here is an example of unions in C language, Live Demo #include <stdio.h> #include <string.h> union Data { int i; float f; } data, data1; int main( ) { printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1)); return 0; } Here is the output Memory size occupied by data : 4 4
[ { "code": null, "e": 1345, "s": 1062, "text": "Structure is a user defined datatype. It is used to combine different types of data into a single type. It can have multiple members and structure variables. The keyword “struct” is used to define structures in C language. Structure members can be accessed by using dot(.) operator." }, { "code": null, "e": 1393, "s": 1345, "text": "Here is the syntax of structures in C language," }, { "code": null, "e": 1462, "s": 1393, "text": "struct structure_name {\n member definition;\n} structure_variables;" }, { "code": null, "e": 1468, "s": 1462, "text": "Here," }, { "code": null, "e": 1518, "s": 1468, "text": "structure_name − Any name given to the structure." }, { "code": null, "e": 1568, "s": 1518, "text": "structure_name − Any name given to the structure." }, { "code": null, "e": 1613, "s": 1568, "text": "member definition − Set of member variables." }, { "code": null, "e": 1658, "s": 1613, "text": "member definition − Set of member variables." }, { "code": null, "e": 1712, "s": 1658, "text": "structure_variable − This is the object of structure." }, { "code": null, "e": 1766, "s": 1712, "text": "structure_variable − This is the object of structure." }, { "code": null, "e": 1814, "s": 1766, "text": "Here is an example of structures in C language," }, { "code": null, "e": 1825, "s": 1814, "text": " Live Demo" }, { "code": null, "e": 2093, "s": 1825, "text": "#include <stdio.h>\n#include <string.h>\n\nstruct Data {\n int i;\n long int f;\n} data, data1;\n\nint main( ) {\n data.i = 28;\n printf(\"The value of i : %d\\n\", (data.i));\n printf( \"Memory size occupied by data : %d\\t%d\", sizeof(data), sizeof(data1));\n return 0;\n}" }, { "code": null, "e": 2112, "s": 2093, "text": "Here is the output" }, { "code": null, "e": 2169, "s": 2112, "text": "The value of i : 28\nMemory size occupied by data : 16 16" }, { "code": null, "e": 2423, "s": 2169, "text": "Union is also a user defined datatype. All the members of union share the same memory location. Size of union is decided by the size of largest member of union. If you want to use same memory location for two or more members, union is the best for that." }, { "code": null, "e": 2587, "s": 2423, "text": "Unions are similar to the structure. Union variables are created in same manner as structure variables. The keyword “union” is used to define unions in C language." }, { "code": null, "e": 2631, "s": 2587, "text": "Here is the syntax of unions in C language," }, { "code": null, "e": 2691, "s": 2631, "text": "union union_name {\n member definition;\n} union_variables;" }, { "code": null, "e": 2697, "s": 2691, "text": "Here," }, { "code": null, "e": 2739, "s": 2697, "text": "union_name − Any name given to the union." }, { "code": null, "e": 2781, "s": 2739, "text": "union_name − Any name given to the union." }, { "code": null, "e": 2826, "s": 2781, "text": "member definition − Set of member variables." }, { "code": null, "e": 2871, "s": 2826, "text": "member definition − Set of member variables." }, { "code": null, "e": 2917, "s": 2871, "text": "union_variable − This is the object of union." }, { "code": null, "e": 2963, "s": 2917, "text": "union_variable − This is the object of union." }, { "code": null, "e": 3007, "s": 2963, "text": "Here is an example of unions in C language," }, { "code": null, "e": 3018, "s": 3007, "text": " Live Demo" }, { "code": null, "e": 3220, "s": 3018, "text": "#include <stdio.h>\n#include <string.h>\n\nunion Data {\n int i;\n float f;\n} data, data1;\n\nint main( ) {\n printf( \"Memory size occupied by data : %d\\t%d\", sizeof(data), sizeof(data1));\n return 0;\n}" }, { "code": null, "e": 3239, "s": 3220, "text": "Here is the output" }, { "code": null, "e": 3274, "s": 3239, "text": "Memory size occupied by data : 4 4" } ]
Python - scipy.fft.dst() method - GeeksforGeeks
01 Oct, 2020 With the help of scipy.fft.dst() method, we can compute the discrete sine transform by selecting different types of sequences and return the transformed array by using this method. Syntax : scipy.fft.dst(x, type=2) Return value: It will return the transformed array. Example #1: In this example, we can see that by using scipy.fft.dst() method, we are able to get the discrete sine transform by selecting different types of sequences by default it’s 2. Python3 # import scipyfrom scipy import fft # Using scipy.fft.dst() methodgfg = fft.dst([1, 2, 3, 4]) print(gfg) Output : [13.06562965 -5.65685425 5.41196100 -4.00000000] Example #2 : Python3 # import scipyfrom scipy import fft # Using scipy.fft.dst() methodgfg = fft.dst([-6, 5, -4, 3, -2, 1], 3) print(gfg) Output : [ -1.43023367 -2.3137085 -6.16568427 -7.77337942 -20.3137085 -23.82253852] Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n01 Oct, 2020" }, { "code": null, "e": 25718, "s": 25537, "text": "With the help of scipy.fft.dst() method, we can compute the discrete sine transform by selecting different types of sequences and return the transformed array by using this method." }, { "code": null, "e": 25727, "s": 25718, "text": "Syntax :" }, { "code": null, "e": 25753, "s": 25727, "text": "scipy.fft.dst(x, type=2)\n" }, { "code": null, "e": 25805, "s": 25753, "text": "Return value: It will return the transformed array." }, { "code": null, "e": 25991, "s": 25805, "text": "Example #1: In this example, we can see that by using scipy.fft.dst() method, we are able to get the discrete sine transform by selecting different types of sequences by default it’s 2." }, { "code": null, "e": 25999, "s": 25991, "text": "Python3" }, { "code": "# import scipyfrom scipy import fft # Using scipy.fft.dst() methodgfg = fft.dst([1, 2, 3, 4]) print(gfg)", "e": 26106, "s": 25999, "text": null }, { "code": null, "e": 26115, "s": 26106, "text": "Output :" }, { "code": null, "e": 26166, "s": 26115, "text": "[13.06562965 -5.65685425 5.41196100 -4.00000000]\n" }, { "code": null, "e": 26179, "s": 26166, "text": "Example #2 :" }, { "code": null, "e": 26187, "s": 26179, "text": "Python3" }, { "code": "# import scipyfrom scipy import fft # Using scipy.fft.dst() methodgfg = fft.dst([-6, 5, -4, 3, -2, 1], 3) print(gfg)", "e": 26306, "s": 26187, "text": null }, { "code": null, "e": 26315, "s": 26306, "text": "Output :" }, { "code": null, "e": 26396, "s": 26315, "text": "[ -1.43023367 -2.3137085 -6.16568427 -7.77337942 -20.3137085\n -23.82253852]\n" }, { "code": null, "e": 26409, "s": 26396, "text": "Python-scipy" }, { "code": null, "e": 26416, "s": 26409, "text": "Python" }, { "code": null, "e": 26514, "s": 26416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26546, "s": 26514, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26588, "s": 26546, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26630, "s": 26588, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26657, "s": 26630, "text": "Python Classes and Objects" }, { "code": null, "e": 26713, "s": 26657, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26735, "s": 26713, "text": "Defaultdict in Python" }, { "code": null, "e": 26774, "s": 26735, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26805, "s": 26774, "text": "Python | os.path.join() method" }, { "code": null, "e": 26834, "s": 26805, "text": "Create a directory in Python" } ]
How to calculate the number of words in a string using JQuery? - GeeksforGeeks
06 Sep, 2019 In order to calculate the number of words in a string, we can Use the JQuery split() method along with or without trim() method..split() method simply split a string into an array of substrings by a specified character and .trim() method to remove the leading and trailing white spaces. Syntax: string.split(separator, limit) Get the string from the HTML element. Split the string into substring on the basis of whitespaces. Count the number of substrings. Example 1: Along with trim() method, removing starting and ending spaces from the string <!DOCTYPE html><html> <head> <title>How to calculate the number of words in a string using Javascript?</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>How to calculate the number of words in a string using Javascript?</h3> <textarea> Geeks For GEEKS </textarea> <br> <button type="button">Click</button> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { // reduce the whitespace from both sides of a string. var geeks1 = $.trim($("textarea").val()); //split a string into an array of substrings var geek = geeks1.split(" ") // count number of elements alert(geek.length); }); }); </script></body> </html> Output: Before Click on button: After Click on button: Example 2: Without trim() method <!DOCTYPE html><html> <head> <title>Calculate the number of Words in a String</title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>How to calculate the number of words in a string using Javascript?</h3> <p id="geeks1"></p> <br> <button onclick="myFunction()">Click</button> <p id="geeks"></p> <script> var str = "Geeks For Geeks"; document.getElementById("geeks1").innerHTML = str; function myFunction() { var res = str.split(" "); document.getElementById( "geeks").innerHTML = res.length; } </script></body> </html> Output: Before Click on button: After Click on button: jQuery-Misc JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? Scroll to the top of the page using JavaScript/jQuery jQuery | children() with Examples How to Show and Hide div elements using radio buttons? 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": 26242, "s": 26214, "text": "\n06 Sep, 2019" }, { "code": null, "e": 26529, "s": 26242, "text": "In order to calculate the number of words in a string, we can Use the JQuery split() method along with or without trim() method..split() method simply split a string into an array of substrings by a specified character and .trim() method to remove the leading and trailing white spaces." }, { "code": null, "e": 26537, "s": 26529, "text": "Syntax:" }, { "code": null, "e": 26568, "s": 26537, "text": "string.split(separator, limit)" }, { "code": null, "e": 26606, "s": 26568, "text": "Get the string from the HTML element." }, { "code": null, "e": 26667, "s": 26606, "text": "Split the string into substring on the basis of whitespaces." }, { "code": null, "e": 26699, "s": 26667, "text": "Count the number of substrings." }, { "code": null, "e": 26788, "s": 26699, "text": "Example 1: Along with trim() method, removing starting and ending spaces from the string" }, { "code": "<!DOCTYPE html><html> <head> <title>How to calculate the number of words in a string using Javascript?</title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3>How to calculate the number of words in a string using Javascript?</h3> <textarea> Geeks For GEEKS </textarea> <br> <button type=\"button\">Click</button> <script type=\"text/javascript\"> $(document).ready(function() { $(\"button\").click(function() { // reduce the whitespace from both sides of a string. var geeks1 = $.trim($(\"textarea\").val()); //split a string into an array of substrings var geek = geeks1.split(\" \") // count number of elements alert(geek.length); }); }); </script></body> </html>", "e": 27743, "s": 26788, "text": null }, { "code": null, "e": 27751, "s": 27743, "text": "Output:" }, { "code": null, "e": 27775, "s": 27751, "text": "Before Click on button:" }, { "code": null, "e": 27798, "s": 27775, "text": "After Click on button:" }, { "code": null, "e": 27831, "s": 27798, "text": "Example 2: Without trim() method" }, { "code": "<!DOCTYPE html><html> <head> <title>Calculate the number of Words in a String</title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3>How to calculate the number of words in a string using Javascript?</h3> <p id=\"geeks1\"></p> <br> <button onclick=\"myFunction()\">Click</button> <p id=\"geeks\"></p> <script> var str = \"Geeks For Geeks\"; document.getElementById(\"geeks1\").innerHTML = str; function myFunction() { var res = str.split(\" \"); document.getElementById( \"geeks\").innerHTML = res.length; } </script></body> </html>", "e": 28515, "s": 27831, "text": null }, { "code": null, "e": 28523, "s": 28515, "text": "Output:" }, { "code": null, "e": 28547, "s": 28523, "text": "Before Click on button:" }, { "code": null, "e": 28570, "s": 28547, "text": "After Click on button:" }, { "code": null, "e": 28582, "s": 28570, "text": "jQuery-Misc" }, { "code": null, "e": 28589, "s": 28582, "text": "JQuery" }, { "code": null, "e": 28606, "s": 28589, "text": "Web Technologies" }, { "code": null, "e": 28633, "s": 28606, "text": "Web technologies Questions" }, { "code": null, "e": 28731, "s": 28633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28760, "s": 28731, "text": "Form validation using jQuery" }, { "code": null, "e": 28816, "s": 28760, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 28870, "s": 28816, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 28904, "s": 28870, "text": "jQuery | children() with Examples" }, { "code": null, "e": 28959, "s": 28904, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 28999, "s": 28959, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29032, "s": 28999, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29077, "s": 29032, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29120, "s": 29077, "text": "How to fetch data from an API in ReactJS ?" } ]
Instant with() Method in Java with Examples - GeeksforGeeks
15 Jan, 2019 In Instant class, there are two types of with() method depending upon the parameters passed to it. with(TemporalAdjuster adjuster) method of the Instant class used to adjusted this instant using TemporalAdjuster and after adjustment returns the copy of adjusted instant.The adjustment takes place using the specified adjuster strategy object. This instance of Instant is immutable and unaffected by this method call. Syntax: public Instant with(TemporalAdjuster adjuster) Parameters: This method accepts adjuster as parameter which is the adjuster to use. Return value: This method returns a Instant based on this with the adjustment made. Exception: This method throws following Exceptions: DateTimeException – if the adjustment cannot be made. ArithmeticException – if numeric overflow occurs. Below programs illustrate the with() method:Program 1: // Java program to demonstrate// Instant.with() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant local = Instant.parse( "2018-12-30T19:34:50.63Z"); // print instance System.out.println("Instant before" + " adjustment: " + local); // apply with method of Instant class Instant updatedlocal = local.with(Instant.EPOCH); // print instance System.out.println("Instant after" + " adjustment: " + updatedlocal); }} Instant before adjustment: 2018-12-30T19:34:50.630Z Instant after adjustment: 1970-01-01T00:00:00Z with(TemporalField field, long newValue) method of the Instant class used to set the specified field of Instant to a new value and returns the copy of new time.This method can be used to change any supported field, such as year, day, month, hour, minute or second. An exception is thrown If setting the new value is not possible due to the field is not supported or for some other reason. This instance of Instant is immutable and unaffected by this method call. Syntax: public Instant with(TemporalField field, long newValue) Parameters: This method accepts field which is the field to set in the result and newValue which the new value of the field in the result as parameters. Return value: This method returns a Instant based on this with the specified field set. Exception: This method throws following Exceptions: DateTimeException – if the adjustment cannot be made. UnsupportedTemporalTypeException – if the field is not supported. ArithmeticException – if numeric overflow occurs. Below programs illustrate the with() method:Program 1: // Java program to demonstrate// Instant.with() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant local = Instant.parse( "2021-01-01T19:55:30Z"); // print instance System.out.println("Instant before" + " applying method: " + local); // apply with method of Instant class Instant updatedlocal = local.with( ChronoField.INSTANT_SECONDS, 45000000000); // print instance System.out.println("Instant after" + " applying method: " + updatedlocal); }} Instant before applying method: 2021-01-01T19:55:30Z Instant after applying method: 1970-01-01T00:00:45Z References:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#with(java.time.temporal.TemporalAdjuster)https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#with(java.time.temporal.TemporalField, long) Java-Functions Java-Instant Java-time 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 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": "\n15 Jan, 2019" }, { "code": null, "e": 25324, "s": 25225, "text": "In Instant class, there are two types of with() method depending upon the parameters passed to it." }, { "code": null, "e": 25642, "s": 25324, "text": "with(TemporalAdjuster adjuster) method of the Instant class used to adjusted this instant using TemporalAdjuster and after adjustment returns the copy of adjusted instant.The adjustment takes place using the specified adjuster strategy object. This instance of Instant is immutable and unaffected by this method call." }, { "code": null, "e": 25650, "s": 25642, "text": "Syntax:" }, { "code": null, "e": 25698, "s": 25650, "text": "public Instant with(TemporalAdjuster adjuster)\n" }, { "code": null, "e": 25782, "s": 25698, "text": "Parameters: This method accepts adjuster as parameter which is the adjuster to use." }, { "code": null, "e": 25866, "s": 25782, "text": "Return value: This method returns a Instant based on this with the adjustment made." }, { "code": null, "e": 25918, "s": 25866, "text": "Exception: This method throws following Exceptions:" }, { "code": null, "e": 25972, "s": 25918, "text": "DateTimeException – if the adjustment cannot be made." }, { "code": null, "e": 26022, "s": 25972, "text": "ArithmeticException – if numeric overflow occurs." }, { "code": null, "e": 26077, "s": 26022, "text": "Below programs illustrate the with() method:Program 1:" }, { "code": "// Java program to demonstrate// Instant.with() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant local = Instant.parse( \"2018-12-30T19:34:50.63Z\"); // print instance System.out.println(\"Instant before\" + \" adjustment: \" + local); // apply with method of Instant class Instant updatedlocal = local.with(Instant.EPOCH); // print instance System.out.println(\"Instant after\" + \" adjustment: \" + updatedlocal); }}", "e": 26803, "s": 26077, "text": null }, { "code": null, "e": 26903, "s": 26803, "text": "Instant before adjustment: 2018-12-30T19:34:50.630Z\nInstant after adjustment: 1970-01-01T00:00:00Z\n" }, { "code": null, "e": 27366, "s": 26903, "text": "with(TemporalField field, long newValue) method of the Instant class used to set the specified field of Instant to a new value and returns the copy of new time.This method can be used to change any supported field, such as year, day, month, hour, minute or second. An exception is thrown If setting the new value is not possible due to the field is not supported or for some other reason. This instance of Instant is immutable and unaffected by this method call." }, { "code": null, "e": 27374, "s": 27366, "text": "Syntax:" }, { "code": null, "e": 27431, "s": 27374, "text": "public Instant with(TemporalField field, long newValue)\n" }, { "code": null, "e": 27584, "s": 27431, "text": "Parameters: This method accepts field which is the field to set in the result and newValue which the new value of the field in the result as parameters." }, { "code": null, "e": 27672, "s": 27584, "text": "Return value: This method returns a Instant based on this with the specified field set." }, { "code": null, "e": 27724, "s": 27672, "text": "Exception: This method throws following Exceptions:" }, { "code": null, "e": 27778, "s": 27724, "text": "DateTimeException – if the adjustment cannot be made." }, { "code": null, "e": 27844, "s": 27778, "text": "UnsupportedTemporalTypeException – if the field is not supported." }, { "code": null, "e": 27894, "s": 27844, "text": "ArithmeticException – if numeric overflow occurs." }, { "code": null, "e": 27949, "s": 27894, "text": "Below programs illustrate the with() method:Program 1:" }, { "code": "// Java program to demonstrate// Instant.with() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant local = Instant.parse( \"2021-01-01T19:55:30Z\"); // print instance System.out.println(\"Instant before\" + \" applying method: \" + local); // apply with method of Instant class Instant updatedlocal = local.with( ChronoField.INSTANT_SECONDS, 45000000000); // print instance System.out.println(\"Instant after\" + \" applying method: \" + updatedlocal); }}", "e": 28740, "s": 27949, "text": null }, { "code": null, "e": 28846, "s": 28740, "text": "Instant before applying method: 2021-01-01T19:55:30Z\nInstant after applying method: 1970-01-01T00:00:45Z\n" }, { "code": null, "e": 29075, "s": 28846, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#with(java.time.temporal.TemporalAdjuster)https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#with(java.time.temporal.TemporalField, long)" }, { "code": null, "e": 29090, "s": 29075, "text": "Java-Functions" }, { "code": null, "e": 29103, "s": 29090, "text": "Java-Instant" }, { "code": null, "e": 29121, "s": 29103, "text": "Java-time package" }, { "code": null, "e": 29126, "s": 29121, "text": "Java" }, { "code": null, "e": 29131, "s": 29126, "text": "Java" }, { "code": null, "e": 29229, "s": 29131, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29244, "s": 29229, "text": "Stream In Java" }, { "code": null, "e": 29265, "s": 29244, "text": "Constructors in Java" }, { "code": null, "e": 29284, "s": 29265, "text": "Exceptions in Java" }, { "code": null, "e": 29314, "s": 29284, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29360, "s": 29314, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29377, "s": 29360, "text": "Generics in Java" }, { "code": null, "e": 29398, "s": 29377, "text": "Introduction to Java" }, { "code": null, "e": 29441, "s": 29398, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29477, "s": 29441, "text": "Internal Working of HashMap in Java" } ]
Find the number of times every day occurs in a month - GeeksforGeeks
08 Apr, 2021 Given the starting day and the number of days in a month. Find the number of times every day occurs in a month Examples: Input : Number of days in month = 28 First day = Wednesday Output : Monday = 4 Tuesday = 4 Wednesday = 4 Thursday = 4 Friday = 4 Saturday = 4 Sunday = 4 Explanation: In the month of February, every day occurs 4 times. Input : Number of days in month = 31 First day = Tuesday Output : Monday = 4 Tuesday = 5 Wednesday = 5 Thursday = 5 Friday = 4 Saturday = 4 Sunday = 4 Explanation: The month starts on Tuesday and ends on Thursday. Observations: We have to make some key observations. First one will be if the month has 28 days then every day occurs 4 times. The second one will be if it has 29 days then the day on which the month starts will occur 5 times. The third one will be if the month has 30 days, then the day on which the month starts and the next day will occur 5 days. The last one is if the month has 31 days, then the day on which the month starts and the next 2 days will occur 5 days with the rest occurring 4 times each. Approach: Create an count array with size 7 and having an initial value of 4 as the minimum number of occurrence will be 4. (number of days-28). Find the index of the firstday. Calculate the number of days whose occurrence will be 5. Then run a loop from pos to pos+(number of days-28) to mark the occurrence as 5. If pos+(number of days-28) exceeds 6, then use %7 to get to the indexes from the beginning. Below is the C++ implementation of the above approach: CPP Java Python3 C# Javascript // C++ program to count occurrence of days in a month#include <bits/stdc++.h>using namespace std; // function to find occurrencesvoid occurrenceDays(int n, string firstday){ // stores days in a week string days[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; // Initialize all counts as 4. int count[7]; for (int i = 0; i < 7; i++) count[i] = 4; // find index of the first day int pos; for (int i = 0; i < 7; i++) { if (firstday == days[i]) { pos = i; break; } } // number of days whose occurrence will be 5 int inc = n - 28; // mark the occurrence to be 5 of n-28 days for (int i = pos; i < pos + inc; i++) { if (i > 6) count[i % 7] = 5; else count[i] = 5; } // print the days for (int i = 0; i < 7; i++) { cout << days[i] << " " << count[i] << endl; }} // driver program to test the above functionint main(){ int n = 31; string firstday = "Tuesday"; occurrenceDays(n, firstday); return 0;} // Java program to count// occurrence of days in a monthimport java.util.*;import java.lang.*; public class GfG{ // function to find occurrences public static void occurrenceDays(int n, String firstday) { // stores days in a week String[] days = new String[]{ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; // Initialize all counts as 4. int[] count = new int[7]; for (int i = 0; i < 7; i++) count[i] = 4; // find index of the first day int pos = 0; for (int i = 0; i < 7; i++) { if (firstday == days[i]) { pos = i; break; } } // number of days whose occurrence // will be 5 int inc = n - 28; // mark the occurrence to be 5 of n-28 days for (int i = pos; i < pos + inc; i++) { if (i > 6) count[i % 7] = 5; else count[i] = 5; } // print the days for (int i = 0; i < 7; i++) { System.out.println(days[i] + " " + count[i]); } } // Driver function public static void main(String argc[]){ int n = 31; String firstday = "Tuesday"; occurrenceDays(n, firstday); }} // This code is contributed by Sagar Shukla # Python program to count# occurrence of days in a monthimport math # function to find occurrencesdef occurrenceDays( n, firstday): # stores days in a week days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] # Initialize all counts as 4. count= [4 for i in range(0,7)] # find index of the first day pos=-1 for i in range(0,7): if (firstday == days[i]): pos = i break # number of days whose occurrence will be 5 inc = n - 28 # mark the occurrence to be 5 of n-28 days for i in range( pos, pos + inc): if (i > 6): count[i % 7] = 5 else: count[i] = 5 # print the days for i in range(0,7): print (days[i] , " " , count[i]) # driver program to test# the above functionn = 31firstday = "Tuesday"occurrenceDays(n, firstday) # This code is contributed by Gitanjali. // C# program to count occurrence of// days in a monthusing System; public class GfG { // function to find occurrences public static void occurrenceDays(int n, string firstday) { // stores days in a week String[] days = new String[]{ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; // Initialize all counts as 4. int[] count = new int[7]; for (int i = 0; i < 7; i++) count[i] = 4; // find index of the first day int pos = 0; for (int i = 0; i < 7; i++) { if (firstday == days[i]) { pos = i; break; } } // number of days whose occurrence // will be 5 int inc = n - 28; // mark the occurrence to be 5 of // n-28 days for (int i = pos; i < pos + inc; i++) { if (i > 6) count[i % 7] = 5; else count[i] = 5; } // print the days for (int i = 0; i < 7; i++) { Console.WriteLine(days[i] + " " + count[i]); } } // Driver function public static void Main() { int n = 31; string firstday = "Tuesday"; occurrenceDays(n, firstday); }} // This code is contributed by vt_m. <script> // JavaScript program to count// occurrence of days in a month // function to find occurrences function occurrenceDays(n, firstday) { // stores days in a week let days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]; // Initialize all counts as 4. let count = []; for (let i = 0; i < 7; i++) count[i] = 4; // find index of the first day let pos = 0; for (let i = 0; i < 7; i++) { if (firstday == days[i]) { pos = i; break; } } // number of days whose occurrence // will be 5 let inc = n - 28; // mark the occurrence to be 5 of n-28 days for (let i = pos; i < pos + inc; i++) { if (i > 6) count[i % 7] = 5; else count[i] = 5; } // print the days for (let i = 0; i < 7; i++) { document.write(days[i] + " " + count[i] + "<br/>"); } } // Driver code let n = 31; let firstday = "Tuesday"; occurrenceDays(n, firstday); </script> Output: Monday 4 Tuesday 5 Wednesday 5 Thursday 5 Friday 4 Saturday 4 Sunday 4 Akanksha_Rai splevel62 date-time-program Searching Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best First Search (Informed Search) 3 Different ways to print Fibonacci series in Java Find whether an array is subset of another array | Added Method 5 Given a sorted and rotated array, find if there is a pair with a given sum Recursive Programs to find Minimum and Maximum elements of array Find closest number in array Program to remove vowels from a String Interpolation search vs Binary search Find common elements in three sorted arrays Binary Search In JavaScript
[ { "code": null, "e": 26214, "s": 26186, "text": "\n08 Apr, 2021" }, { "code": null, "e": 26337, "s": 26214, "text": "Given the starting day and the number of days in a month. Find the number of times every day occurs in a month Examples: " }, { "code": null, "e": 26922, "s": 26337, "text": "Input : Number of days in month = 28 \n First day = Wednesday \nOutput : Monday = 4 \n Tuesday = 4 \n Wednesday = 4 \n Thursday = 4 \n Friday = 4 \n Saturday = 4 \n Sunday = 4\nExplanation: In the month of February, \nevery day occurs 4 times. \n\nInput : Number of days in month = 31 \n First day = Tuesday \nOutput : Monday = 4 \n Tuesday = 5 \n Wednesday = 5 \n Thursday = 5 \n Friday = 4 \n Saturday = 4 \n Sunday = 4 \nExplanation: The month starts on Tuesday \nand ends on Thursday. " }, { "code": null, "e": 27895, "s": 26924, "text": "Observations: We have to make some key observations. First one will be if the month has 28 days then every day occurs 4 times. The second one will be if it has 29 days then the day on which the month starts will occur 5 times. The third one will be if the month has 30 days, then the day on which the month starts and the next day will occur 5 days. The last one is if the month has 31 days, then the day on which the month starts and the next 2 days will occur 5 days with the rest occurring 4 times each. Approach: Create an count array with size 7 and having an initial value of 4 as the minimum number of occurrence will be 4. (number of days-28). Find the index of the firstday. Calculate the number of days whose occurrence will be 5. Then run a loop from pos to pos+(number of days-28) to mark the occurrence as 5. If pos+(number of days-28) exceeds 6, then use %7 to get to the indexes from the beginning. Below is the C++ implementation of the above approach: " }, { "code": null, "e": 27899, "s": 27895, "text": "CPP" }, { "code": null, "e": 27904, "s": 27899, "text": "Java" }, { "code": null, "e": 27912, "s": 27904, "text": "Python3" }, { "code": null, "e": 27915, "s": 27912, "text": "C#" }, { "code": null, "e": 27926, "s": 27915, "text": "Javascript" }, { "code": "// C++ program to count occurrence of days in a month#include <bits/stdc++.h>using namespace std; // function to find occurrencesvoid occurrenceDays(int n, string firstday){ // stores days in a week string days[] = { \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\" }; // Initialize all counts as 4. int count[7]; for (int i = 0; i < 7; i++) count[i] = 4; // find index of the first day int pos; for (int i = 0; i < 7; i++) { if (firstday == days[i]) { pos = i; break; } } // number of days whose occurrence will be 5 int inc = n - 28; // mark the occurrence to be 5 of n-28 days for (int i = pos; i < pos + inc; i++) { if (i > 6) count[i % 7] = 5; else count[i] = 5; } // print the days for (int i = 0; i < 7; i++) { cout << days[i] << \" \" << count[i] << endl; }} // driver program to test the above functionint main(){ int n = 31; string firstday = \"Tuesday\"; occurrenceDays(n, firstday); return 0;}", "e": 29021, "s": 27926, "text": null }, { "code": "// Java program to count// occurrence of days in a monthimport java.util.*;import java.lang.*; public class GfG{ // function to find occurrences public static void occurrenceDays(int n, String firstday) { // stores days in a week String[] days = new String[]{ \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\" }; // Initialize all counts as 4. int[] count = new int[7]; for (int i = 0; i < 7; i++) count[i] = 4; // find index of the first day int pos = 0; for (int i = 0; i < 7; i++) { if (firstday == days[i]) { pos = i; break; } } // number of days whose occurrence // will be 5 int inc = n - 28; // mark the occurrence to be 5 of n-28 days for (int i = pos; i < pos + inc; i++) { if (i > 6) count[i % 7] = 5; else count[i] = 5; } // print the days for (int i = 0; i < 7; i++) { System.out.println(days[i] + \" \" + count[i]); } } // Driver function public static void main(String argc[]){ int n = 31; String firstday = \"Tuesday\"; occurrenceDays(n, firstday); }} // This code is contributed by Sagar Shukla", "e": 30477, "s": 29021, "text": null }, { "code": "# Python program to count# occurrence of days in a monthimport math # function to find occurrencesdef occurrenceDays( n, firstday): # stores days in a week days = [ \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\" ] # Initialize all counts as 4. count= [4 for i in range(0,7)] # find index of the first day pos=-1 for i in range(0,7): if (firstday == days[i]): pos = i break # number of days whose occurrence will be 5 inc = n - 28 # mark the occurrence to be 5 of n-28 days for i in range( pos, pos + inc): if (i > 6): count[i % 7] = 5 else: count[i] = 5 # print the days for i in range(0,7): print (days[i] , \" \" , count[i]) # driver program to test# the above functionn = 31firstday = \"Tuesday\"occurrenceDays(n, firstday) # This code is contributed by Gitanjali.", "e": 31444, "s": 30477, "text": null }, { "code": "// C# program to count occurrence of// days in a monthusing System; public class GfG { // function to find occurrences public static void occurrenceDays(int n, string firstday) { // stores days in a week String[] days = new String[]{ \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\" }; // Initialize all counts as 4. int[] count = new int[7]; for (int i = 0; i < 7; i++) count[i] = 4; // find index of the first day int pos = 0; for (int i = 0; i < 7; i++) { if (firstday == days[i]) { pos = i; break; } } // number of days whose occurrence // will be 5 int inc = n - 28; // mark the occurrence to be 5 of // n-28 days for (int i = pos; i < pos + inc; i++) { if (i > 6) count[i % 7] = 5; else count[i] = 5; } // print the days for (int i = 0; i < 7; i++) { Console.WriteLine(days[i] + \" \" + count[i]); } } // Driver function public static void Main() { int n = 31; string firstday = \"Tuesday\"; occurrenceDays(n, firstday); }} // This code is contributed by vt_m.", "e": 32984, "s": 31444, "text": null }, { "code": "<script> // JavaScript program to count// occurrence of days in a month // function to find occurrences function occurrenceDays(n, firstday) { // stores days in a week let days = [ \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\" ]; // Initialize all counts as 4. let count = []; for (let i = 0; i < 7; i++) count[i] = 4; // find index of the first day let pos = 0; for (let i = 0; i < 7; i++) { if (firstday == days[i]) { pos = i; break; } } // number of days whose occurrence // will be 5 let inc = n - 28; // mark the occurrence to be 5 of n-28 days for (let i = pos; i < pos + inc; i++) { if (i > 6) count[i % 7] = 5; else count[i] = 5; } // print the days for (let i = 0; i < 7; i++) { document.write(days[i] + \" \" + count[i] + \"<br/>\"); } } // Driver code let n = 31; let firstday = \"Tuesday\"; occurrenceDays(n, firstday); </script>", "e": 34285, "s": 32984, "text": null }, { "code": null, "e": 34294, "s": 34285, "text": "Output: " }, { "code": null, "e": 34365, "s": 34294, "text": "Monday 4\nTuesday 5\nWednesday 5\nThursday 5\nFriday 4\nSaturday 4\nSunday 4" }, { "code": null, "e": 34380, "s": 34367, "text": "Akanksha_Rai" }, { "code": null, "e": 34390, "s": 34380, "text": "splevel62" }, { "code": null, "e": 34408, "s": 34390, "text": "date-time-program" }, { "code": null, "e": 34418, "s": 34408, "text": "Searching" }, { "code": null, "e": 34428, "s": 34418, "text": "Searching" }, { "code": null, "e": 34526, "s": 34428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34562, "s": 34526, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 34613, "s": 34562, "text": "3 Different ways to print Fibonacci series in Java" }, { "code": null, "e": 34679, "s": 34613, "text": "Find whether an array is subset of another array | Added Method 5" }, { "code": null, "e": 34754, "s": 34679, "text": "Given a sorted and rotated array, find if there is a pair with a given sum" }, { "code": null, "e": 34819, "s": 34754, "text": "Recursive Programs to find Minimum and Maximum elements of array" }, { "code": null, "e": 34848, "s": 34819, "text": "Find closest number in array" }, { "code": null, "e": 34887, "s": 34848, "text": "Program to remove vowels from a String" }, { "code": null, "e": 34925, "s": 34887, "text": "Interpolation search vs Binary search" }, { "code": null, "e": 34969, "s": 34925, "text": "Find common elements in three sorted arrays" } ]
C# | Getting the type of the current instance - GeeksforGeeks
01 Feb, 2019 Object.GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType (); Return Value: This method return the exact runtime type of the current instance. Below given are some examples to understand the implementation in a better way: Example 1: // C# program to illustrate the // GetType() methodusing System; class GFG { // Main method static public void Main() { // string type string str1 = "GFG"; string str2 = "5"; // using GetType() method Console.WriteLine("Type of str1: " +str1.GetType()); Console.WriteLine("Type of str2: " +str2.GetType()); }} Output: Type of str1: System.String Type of str2: System.String Example 2: // C# program to illustrate the // GetType() methodusing System; class GFG { // Main method static public void Main() { // Variables string str1 = "C#"; string str2 = "DSA"; int str3 = 43; // Display the given string and their type // using GetType() method Console.WriteLine("Str 1 is : {0}", str1); Console.WriteLine("Str 2 is : {0}", str2); Console.WriteLine("Str 3 is : {0}", str3); // Check the given str1, str2, // and str3 are of same type or not // using GetType() method Console.WriteLine("Is Str 1 and Str 2 of same type? : {0}", Object.ReferenceEquals(str1.GetType(), str2.GetType())); Console.WriteLine("Is Str 2 and Str 3 of same type? : {0}", Object.ReferenceEquals(str2.GetType(), str3.GetType())); Console.WriteLine("Is Str 3 and Str 2 of same type? : {0}", Object.ReferenceEquals(str3.GetType(), str2.GetType())); }} Output: Str 1 is : C# Str 2 is : DSA Str 3 is : 43 Is Str 1 and Str 2 of same type? : True Is Str 2 and Str 3 of same type? : False Is Str 3 and Str 2 of same type? : False Reference: https://docs.microsoft.com/en-us/dotnet/api/system.object.gettype?view=netframework-4.7.2 CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method C# | Arrays
[ { "code": null, "e": 25179, "s": 25151, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25336, "s": 25179, "text": "Object.GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration." }, { "code": null, "e": 25344, "s": 25336, "text": "Syntax:" }, { "code": null, "e": 25368, "s": 25344, "text": "public Type GetType ();" }, { "code": null, "e": 25449, "s": 25368, "text": "Return Value: This method return the exact runtime type of the current instance." }, { "code": null, "e": 25529, "s": 25449, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 25540, "s": 25529, "text": "Example 1:" }, { "code": "// C# program to illustrate the // GetType() methodusing System; class GFG { // Main method static public void Main() { // string type string str1 = \"GFG\"; string str2 = \"5\"; // using GetType() method Console.WriteLine(\"Type of str1: \" +str1.GetType()); Console.WriteLine(\"Type of str2: \" +str2.GetType()); }}", "e": 25911, "s": 25540, "text": null }, { "code": null, "e": 25919, "s": 25911, "text": "Output:" }, { "code": null, "e": 25976, "s": 25919, "text": "Type of str1: System.String\nType of str2: System.String\n" }, { "code": null, "e": 25987, "s": 25976, "text": "Example 2:" }, { "code": "// C# program to illustrate the // GetType() methodusing System; class GFG { // Main method static public void Main() { // Variables string str1 = \"C#\"; string str2 = \"DSA\"; int str3 = 43; // Display the given string and their type // using GetType() method Console.WriteLine(\"Str 1 is : {0}\", str1); Console.WriteLine(\"Str 2 is : {0}\", str2); Console.WriteLine(\"Str 3 is : {0}\", str3); // Check the given str1, str2, // and str3 are of same type or not // using GetType() method Console.WriteLine(\"Is Str 1 and Str 2 of same type? : {0}\", Object.ReferenceEquals(str1.GetType(), str2.GetType())); Console.WriteLine(\"Is Str 2 and Str 3 of same type? : {0}\", Object.ReferenceEquals(str2.GetType(), str3.GetType())); Console.WriteLine(\"Is Str 3 and Str 2 of same type? : {0}\", Object.ReferenceEquals(str3.GetType(), str2.GetType())); }}", "e": 27011, "s": 25987, "text": null }, { "code": null, "e": 27019, "s": 27011, "text": "Output:" }, { "code": null, "e": 27185, "s": 27019, "text": "Str 1 is : C#\nStr 2 is : DSA\nStr 3 is : 43\nIs Str 1 and Str 2 of same type? : True\nIs Str 2 and Str 3 of same type? : False\nIs Str 3 and Str 2 of same type? : False\n" }, { "code": null, "e": 27196, "s": 27185, "text": "Reference:" }, { "code": null, "e": 27286, "s": 27196, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.object.gettype?view=netframework-4.7.2" }, { "code": null, "e": 27300, "s": 27286, "text": "CSharp-method" }, { "code": null, "e": 27303, "s": 27300, "text": "C#" }, { "code": null, "e": 27401, "s": 27303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27429, "s": 27401, "text": "C# Dictionary with examples" }, { "code": null, "e": 27444, "s": 27429, "text": "C# | Delegates" }, { "code": null, "e": 27467, "s": 27444, "text": "C# | Method Overriding" }, { "code": null, "e": 27489, "s": 27467, "text": "C# | Abstract Classes" }, { "code": null, "e": 27535, "s": 27489, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27558, "s": 27535, "text": "Extension Method in C#" }, { "code": null, "e": 27589, "s": 27558, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27629, "s": 27589, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27651, "s": 27629, "text": "C# | Replace() Method" } ]
Harmonic progression Sum - GeeksforGeeks
12 Apr, 2021 Given the first element of the progression ‘a’, common difference between the element ‘d’ and number of terms in the progression ‘n’, where . The task is to generate harmonic progression using the above set of information.Examples: Input : a = 12, d = 12, n = 5 Output : Harmonic Progression : 1/12 1/24 1/36 1/48 1/60 Sum of the generated harmonic progression : 0.19 Sum of the generated harmonic progression using approximation :0.19 Arithmetic Progression : In an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers such that the difference between the consecutive terms is constant.Harmonic Progression: A harmonic progression (or harmonic sequence) is a progression formed by taking the reciprocals of an arithmetic progression.Now, we need to generate this harmonic progression. We even have to calculate the sum of the generated sequence.1. Generating of HP or 1/AP is a simple task. The Nth term in an AP = a + (n-1)d. Using this formula, we can easily generate the sequence.2. Calculating the sum of this progression or sequence can be a time taking task. We can either iterate while generating this sequence or we could use some approximations and come up with a formula which would give us a value accurate up to some decimal places. Below is an approximate formula. Sum = 1/d (ln(2a + (2n – 1)d) / (2a – d)) Please refer brilliant.org for details of above formula.Below is implementation of above formula. C++ Java Python3 C# PHP Javascript // C++ code to generate Harmonic Progression// and calculate the sum of the progression.#include <bits/stdc++.h>using namespace std; // Function that generates the harmonic progression// and calculates the sum of its elements by iterating.double generateAP(int a, int d, int n, int AP[]){ double sum = 0; for (int i = 1; i <= n; i++) { // HP = 1/AP // In AP, ith term is calculated by a+(i-1)d; AP[i] = (a + (i - 1) * d); // Calculating the sum. sum += (double)1 / (double)((a + (i - 1) * d)); } return sum;} // Function that uses riemenn sum method to calculate// the approximate sum of HP in O(1) time complexitydouble sumApproximation(int a, int d, int n){ return log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d;} // Driver codeint main(){ int a = 12, d = 12, n = 5; int AP[n + 5] ; // Generating AP from the above data double sum = generateAP(a, d, n, AP); // Generating HP from the generated AP cout<<"Harmonic Progression :"<<endl; for (int i = 1; i <= n; i++) cout << "1/" << AP[i] << " "; cout << endl; string str = ""; str = str + to_string(sum); str = str.substr(0, 4); cout<< "Sum of the generated" <<" harmonic progression : " << str << endl; sum = sumApproximation(a, d, n); str = ""; str = str + to_string(sum); str = str.substr(0, 4); cout << "Sum of the generated " << "harmonic progression using approximation : " << str; return 0;} // This code is contributed by Rajput-Ji // Java code to generate Harmonic Progression// and calculate the sum of the progression.import java.util.*;import java.lang.*; class GeeksforGeeks { // Function that generates the harmonic progression // and calculates the sum of its elements by iterating. static double generateAP(int a, int d, int n, int AP[]) { double sum = 0; for (int i = 1; i <= n; i++) { // HP = 1/AP // In AP, ith term is calculated by a+(i-1)d; AP[i] = (a + (i - 1) * d); // Calculating the sum. sum += (double)1 / (double)((a + (i - 1) * d)); } return sum; } // Function that uses riemenn sum method to calculate // the approximate sum of HP in O(1) time complexity static double sumApproximation(int a, int d, int n) { return Math.log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d; } public static void main(String args[]) { int a = 12, d = 12, n = 5; int AP[] = new int[n + 5]; // Generating AP from the above data double sum = generateAP(a, d, n, AP); // Generating HP from the generated AP System.out.println("Harmonic Progression :"); for (int i = 1; i <= n; i++) System.out.print("1/" + AP[i] + " "); System.out.println(); String str = ""; str = str + sum; str = str.substring(0, 4); System.out.println("Sum of the generated" + " harmonic progression : " + str); sum = sumApproximation(a, d, n); str = ""; str = str + sum; str = str.substring(0, 4); System.out.println("Sum of the generated " + "harmonic progression using approximation : " + str); }} # Python3 code to generate Harmonic Progression# and calculate the sum of the progression.import math # Function that generates the harmonic# progression and calculates the sum of# its elements by iterating.n = 5;AP = [0] * (n + 5); def generateAP(a, d, n): sum = 0; for i in range(1, n + 1): # HP = 1/AP # In AP, ith term is calculated # by a+(i-1)d; AP[i] = (a + (i - 1) * d); # Calculating the sum. sum += float(1) / float((a + (i - 1) * d)); return sum; # Function that uses riemenn sum method to calculate# the approximate sum of HP in O(1) time complexitydef sumApproximation(a, d, n): return math.log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d; # Driver Codea = 12;d = 12;#n = 5; # Generating AP from the above datasum = generateAP(a, d, n); # Generating HP from the generated APprint("Harmonic Progression :");for i in range(1, n + 1): print("1 /", AP[i], end = " ");print("");str1 = "";str1 = str1 + str(sum);str1 = str1[0:4]; print("Sum of the generated harmonic", "progression :", str1);sum = sumApproximation(a, d, n); str1 = "";str1 = str1 + str(sum);str1 = str1[0:4];print("Sum of the generated harmonic", "progression using approximation :", str1); # This code is contributed by mits // C# code to generate Harmonic// Progression and calculate// the sum of the progression.using System; class GFG{ // Function that generates // the harmonic progression // and calculates the sum of // its elements by iterating. static double generateAP(int a, int d, int n, int []AP) { double sum = 0; for (int i = 1; i <= n; i++) { // HP = 1/AP // In AP, ith term is // calculated by a+(i-1)d; AP[i] = (a + (i - 1) * d); // Calculating the sum. sum += (double)1 / (double)((a + (i - 1) * d)); } return sum; } // Function that uses riemenn // sum method to calculate // the approximate sum of HP // in O(1) time complexity static double sumApproximation(int a, int d, int n) { return Math.Log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d; } // Driver code static void Main() { int a = 12, d = 12, n = 5; int []AP = new int[n + 5]; // Generating AP from // the above data double sum = generateAP(a, d, n, AP); // Generating HP from // the generated AP Console.WriteLine("Harmonic Progression :"); for (int i = 1; i <= n; i++) Console.Write("1/" + AP[i] + " "); Console.WriteLine(); String str = ""; str = str + sum; str = str.Substring(0, 4); Console.WriteLine("Sum of the generated" + " harmonic progression : " + str); sum = sumApproximation(a, d, n); str = ""; str = str + sum; str = str.Substring(0, 4); Console.WriteLine("Sum of the generated " + "harmonic progression using approximation : " + str); }} // This code is contributed by// ManishShaw(manishshaw1) <?php// PHP code to generate Harmonic Progression// and calculate the sum of the progression. // Function that generates the harmonic progression // and calculates the sum of its elements by iterating. function generateAP($a, $d, $n, &$AP) { $sum = 0; for ($i = 1; $i <= $n; $i++) { // HP = 1/AP // In AP, ith term is calculated by a+(i-1)d; $AP[$i] = ($a + ($i - 1) * $d); // Calculating the sum. $sum += (double)1 / (double)(($a + ($i - 1) * $d)); } return $sum; } // Function that uses riemenn sum method to calculate // the approximate sum of HP in O(1) time complexity function sumApproximation($a, $d, $n) { return log((2 * $a + (2 * $n - 1) * $d) / (2 * $a - $d)) / $d; } // Drive main $a = 12; $d = 12; $n = 5; $AP = array_fill(0,$n + 5,0); // Generating AP from the above data $sum = generateAP($a, $d, $n, $AP); // Generating HP from the generated AP echo "Harmonic Progression :\n"; for ($i = 1; $i <= $n; $i++) echo "1/".$AP[$i]." "; echo "\n"; $str = ""; $str = $str.strval($sum); $str = substr($str,0, 4); echo "Sum of the generated". " harmonic progression : ".$str; $sum = sumApproximation($a, $d, $n); $str = ""; $str = $str + strval($sum); $str = substr($str,0, 4); echo "\nSum of the generated ". "harmonic progression using approximation : ".$str; // this code is contributed by mits ?> <script> // JavaScript code to generate Harmonic Progression// and calculate the sum of the progression. // Function that generates the harmonic progression // and calculates the sum of its elements by iterating. function generateAP(a, d, n, AP) { let sum = 0; for (let i = 1; i <= n; i++) { // HP = 1/AP // In AP, ith term is calculated by a+(i-1)d; AP[i] = (a + (i - 1) * d); // Calculating the sum. sum += 1 / ((a + (i - 1) * d)); } return sum; } // Function that uses riemenn sum method to calculate // the approximate sum of HP in O(1) time complexity function sumApproximation(a, d, n) { return Math.log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d; } // Driver code let a = 12, d = 12, n = 5; let AP = []; // Generating AP from the above data let sum = generateAP(a, d, n, AP); // Generating HP from the generated AP document.write("Harmonic Progression :" + "<br/>"); for (let i = 1; i <= n; i++) document.write("1/" + AP[i] + " "); document.write("<br/>"); let str = ""; str = str + sum; str = str.substring(0, 4); document.write("Sum of the generated" + " harmonic progression : " + str + "<br/>"); sum = sumApproximation(a, d, n); str = ""; str = str + sum; str = str.substring(0, 4); document.write("Sum of the generated " + "harmonic progression using approximation : " + str + "<br/>"); </script> Output: Harmonic Progression : 1/12 1/24 1/36 1/48 1/60 Sum of the generated harmonic progression : 0.19 Sum of the generated harmonic progression using approximation :0.19 manishshaw1 Mithun Kumar Rajput-Ji souravghosh0416 harmonic progression series series-sum Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Sieve of Eratosthenes The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion Operators in C / C++ Program for factorial of a number
[ { "code": null, "e": 26065, "s": 26037, "text": "\n12 Apr, 2021" }, { "code": null, "e": 26299, "s": 26065, "text": "Given the first element of the progression ‘a’, common difference between the element ‘d’ and number of terms in the progression ‘n’, where . The task is to generate harmonic progression using the above set of information.Examples: " }, { "code": null, "e": 26567, "s": 26299, "text": "Input : a = 12, d = 12, n = 5 \nOutput : Harmonic Progression :\n 1/12 1/24 1/36 1/48 1/60 \n\n Sum of the generated harmonic \n progression : 0.19\n \n Sum of the generated harmonic \n progression using approximation :0.19 " }, { "code": null, "e": 27436, "s": 26569, "text": "Arithmetic Progression : In an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers such that the difference between the consecutive terms is constant.Harmonic Progression: A harmonic progression (or harmonic sequence) is a progression formed by taking the reciprocals of an arithmetic progression.Now, we need to generate this harmonic progression. We even have to calculate the sum of the generated sequence.1. Generating of HP or 1/AP is a simple task. The Nth term in an AP = a + (n-1)d. Using this formula, we can easily generate the sequence.2. Calculating the sum of this progression or sequence can be a time taking task. We can either iterate while generating this sequence or we could use some approximations and come up with a formula which would give us a value accurate up to some decimal places. Below is an approximate formula. " }, { "code": null, "e": 27478, "s": 27436, "text": "Sum = 1/d (ln(2a + (2n – 1)d) / (2a – d))" }, { "code": null, "e": 27577, "s": 27478, "text": "Please refer brilliant.org for details of above formula.Below is implementation of above formula. " }, { "code": null, "e": 27581, "s": 27577, "text": "C++" }, { "code": null, "e": 27586, "s": 27581, "text": "Java" }, { "code": null, "e": 27594, "s": 27586, "text": "Python3" }, { "code": null, "e": 27597, "s": 27594, "text": "C#" }, { "code": null, "e": 27601, "s": 27597, "text": "PHP" }, { "code": null, "e": 27612, "s": 27601, "text": "Javascript" }, { "code": "// C++ code to generate Harmonic Progression// and calculate the sum of the progression.#include <bits/stdc++.h>using namespace std; // Function that generates the harmonic progression// and calculates the sum of its elements by iterating.double generateAP(int a, int d, int n, int AP[]){ double sum = 0; for (int i = 1; i <= n; i++) { // HP = 1/AP // In AP, ith term is calculated by a+(i-1)d; AP[i] = (a + (i - 1) * d); // Calculating the sum. sum += (double)1 / (double)((a + (i - 1) * d)); } return sum;} // Function that uses riemenn sum method to calculate// the approximate sum of HP in O(1) time complexitydouble sumApproximation(int a, int d, int n){ return log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d;} // Driver codeint main(){ int a = 12, d = 12, n = 5; int AP[n + 5] ; // Generating AP from the above data double sum = generateAP(a, d, n, AP); // Generating HP from the generated AP cout<<\"Harmonic Progression :\"<<endl; for (int i = 1; i <= n; i++) cout << \"1/\" << AP[i] << \" \"; cout << endl; string str = \"\"; str = str + to_string(sum); str = str.substr(0, 4); cout<< \"Sum of the generated\" <<\" harmonic progression : \" << str << endl; sum = sumApproximation(a, d, n); str = \"\"; str = str + to_string(sum); str = str.substr(0, 4); cout << \"Sum of the generated \" << \"harmonic progression using approximation : \" << str; return 0;} // This code is contributed by Rajput-Ji", "e": 29208, "s": 27612, "text": null }, { "code": "// Java code to generate Harmonic Progression// and calculate the sum of the progression.import java.util.*;import java.lang.*; class GeeksforGeeks { // Function that generates the harmonic progression // and calculates the sum of its elements by iterating. static double generateAP(int a, int d, int n, int AP[]) { double sum = 0; for (int i = 1; i <= n; i++) { // HP = 1/AP // In AP, ith term is calculated by a+(i-1)d; AP[i] = (a + (i - 1) * d); // Calculating the sum. sum += (double)1 / (double)((a + (i - 1) * d)); } return sum; } // Function that uses riemenn sum method to calculate // the approximate sum of HP in O(1) time complexity static double sumApproximation(int a, int d, int n) { return Math.log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d; } public static void main(String args[]) { int a = 12, d = 12, n = 5; int AP[] = new int[n + 5]; // Generating AP from the above data double sum = generateAP(a, d, n, AP); // Generating HP from the generated AP System.out.println(\"Harmonic Progression :\"); for (int i = 1; i <= n; i++) System.out.print(\"1/\" + AP[i] + \" \"); System.out.println(); String str = \"\"; str = str + sum; str = str.substring(0, 4); System.out.println(\"Sum of the generated\" + \" harmonic progression : \" + str); sum = sumApproximation(a, d, n); str = \"\"; str = str + sum; str = str.substring(0, 4); System.out.println(\"Sum of the generated \" + \"harmonic progression using approximation : \" + str); }}", "e": 31024, "s": 29208, "text": null }, { "code": "# Python3 code to generate Harmonic Progression# and calculate the sum of the progression.import math # Function that generates the harmonic# progression and calculates the sum of# its elements by iterating.n = 5;AP = [0] * (n + 5); def generateAP(a, d, n): sum = 0; for i in range(1, n + 1): # HP = 1/AP # In AP, ith term is calculated # by a+(i-1)d; AP[i] = (a + (i - 1) * d); # Calculating the sum. sum += float(1) / float((a + (i - 1) * d)); return sum; # Function that uses riemenn sum method to calculate# the approximate sum of HP in O(1) time complexitydef sumApproximation(a, d, n): return math.log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d; # Driver Codea = 12;d = 12;#n = 5; # Generating AP from the above datasum = generateAP(a, d, n); # Generating HP from the generated APprint(\"Harmonic Progression :\");for i in range(1, n + 1): print(\"1 /\", AP[i], end = \" \");print(\"\");str1 = \"\";str1 = str1 + str(sum);str1 = str1[0:4]; print(\"Sum of the generated harmonic\", \"progression :\", str1);sum = sumApproximation(a, d, n); str1 = \"\";str1 = str1 + str(sum);str1 = str1[0:4];print(\"Sum of the generated harmonic\", \"progression using approximation :\", str1); # This code is contributed by mits ", "e": 32352, "s": 31024, "text": null }, { "code": "// C# code to generate Harmonic// Progression and calculate// the sum of the progression.using System; class GFG{ // Function that generates // the harmonic progression // and calculates the sum of // its elements by iterating. static double generateAP(int a, int d, int n, int []AP) { double sum = 0; for (int i = 1; i <= n; i++) { // HP = 1/AP // In AP, ith term is // calculated by a+(i-1)d; AP[i] = (a + (i - 1) * d); // Calculating the sum. sum += (double)1 / (double)((a + (i - 1) * d)); } return sum; } // Function that uses riemenn // sum method to calculate // the approximate sum of HP // in O(1) time complexity static double sumApproximation(int a, int d, int n) { return Math.Log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d; } // Driver code static void Main() { int a = 12, d = 12, n = 5; int []AP = new int[n + 5]; // Generating AP from // the above data double sum = generateAP(a, d, n, AP); // Generating HP from // the generated AP Console.WriteLine(\"Harmonic Progression :\"); for (int i = 1; i <= n; i++) Console.Write(\"1/\" + AP[i] + \" \"); Console.WriteLine(); String str = \"\"; str = str + sum; str = str.Substring(0, 4); Console.WriteLine(\"Sum of the generated\" + \" harmonic progression : \" + str); sum = sumApproximation(a, d, n); str = \"\"; str = str + sum; str = str.Substring(0, 4); Console.WriteLine(\"Sum of the generated \" + \"harmonic progression using approximation : \" + str); }} // This code is contributed by// ManishShaw(manishshaw1)", "e": 34331, "s": 32352, "text": null }, { "code": "<?php// PHP code to generate Harmonic Progression// and calculate the sum of the progression. // Function that generates the harmonic progression // and calculates the sum of its elements by iterating. function generateAP($a, $d, $n, &$AP) { $sum = 0; for ($i = 1; $i <= $n; $i++) { // HP = 1/AP // In AP, ith term is calculated by a+(i-1)d; $AP[$i] = ($a + ($i - 1) * $d); // Calculating the sum. $sum += (double)1 / (double)(($a + ($i - 1) * $d)); } return $sum; } // Function that uses riemenn sum method to calculate // the approximate sum of HP in O(1) time complexity function sumApproximation($a, $d, $n) { return log((2 * $a + (2 * $n - 1) * $d) / (2 * $a - $d)) / $d; } // Drive main $a = 12; $d = 12; $n = 5; $AP = array_fill(0,$n + 5,0); // Generating AP from the above data $sum = generateAP($a, $d, $n, $AP); // Generating HP from the generated AP echo \"Harmonic Progression :\\n\"; for ($i = 1; $i <= $n; $i++) echo \"1/\".$AP[$i].\" \"; echo \"\\n\"; $str = \"\"; $str = $str.strval($sum); $str = substr($str,0, 4); echo \"Sum of the generated\". \" harmonic progression : \".$str; $sum = sumApproximation($a, $d, $n); $str = \"\"; $str = $str + strval($sum); $str = substr($str,0, 4); echo \"\\nSum of the generated \". \"harmonic progression using approximation : \".$str; // this code is contributed by mits ?>", "e": 36014, "s": 34331, "text": null }, { "code": "<script> // JavaScript code to generate Harmonic Progression// and calculate the sum of the progression. // Function that generates the harmonic progression // and calculates the sum of its elements by iterating. function generateAP(a, d, n, AP) { let sum = 0; for (let i = 1; i <= n; i++) { // HP = 1/AP // In AP, ith term is calculated by a+(i-1)d; AP[i] = (a + (i - 1) * d); // Calculating the sum. sum += 1 / ((a + (i - 1) * d)); } return sum; } // Function that uses riemenn sum method to calculate // the approximate sum of HP in O(1) time complexity function sumApproximation(a, d, n) { return Math.log((2 * a + (2 * n - 1) * d) / (2 * a - d)) / d; } // Driver code let a = 12, d = 12, n = 5; let AP = []; // Generating AP from the above data let sum = generateAP(a, d, n, AP); // Generating HP from the generated AP document.write(\"Harmonic Progression :\" + \"<br/>\"); for (let i = 1; i <= n; i++) document.write(\"1/\" + AP[i] + \" \"); document.write(\"<br/>\"); let str = \"\"; str = str + sum; str = str.substring(0, 4); document.write(\"Sum of the generated\" + \" harmonic progression : \" + str + \"<br/>\"); sum = sumApproximation(a, d, n); str = \"\"; str = str + sum; str = str.substring(0, 4); document.write(\"Sum of the generated \" + \"harmonic progression using approximation : \" + str + \"<br/>\"); </script>", "e": 37738, "s": 36014, "text": null }, { "code": null, "e": 37747, "s": 37738, "text": "Output: " }, { "code": null, "e": 37913, "s": 37747, "text": "Harmonic Progression :\n1/12 1/24 1/36 1/48 1/60 \nSum of the generated harmonic progression : 0.19\nSum of the generated harmonic progression using approximation :0.19" }, { "code": null, "e": 37927, "s": 37915, "text": "manishshaw1" }, { "code": null, "e": 37940, "s": 37927, "text": "Mithun Kumar" }, { "code": null, "e": 37950, "s": 37940, "text": "Rajput-Ji" }, { "code": null, "e": 37966, "s": 37950, "text": "souravghosh0416" }, { "code": null, "e": 37987, "s": 37966, "text": "harmonic progression" }, { "code": null, "e": 37994, "s": 37987, "text": "series" }, { "code": null, "e": 38005, "s": 37994, "text": "series-sum" }, { "code": null, "e": 38018, "s": 38005, "text": "Mathematical" }, { "code": null, "e": 38031, "s": 38018, "text": "Mathematical" }, { "code": null, "e": 38038, "s": 38031, "text": "series" }, { "code": null, "e": 38136, "s": 38038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38160, "s": 38136, "text": "Merge two sorted arrays" }, { "code": null, "e": 38203, "s": 38160, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 38217, "s": 38203, "text": "Prime Numbers" }, { "code": null, "e": 38259, "s": 38217, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 38332, "s": 38259, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 38354, "s": 38332, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 38397, "s": 38354, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 38438, "s": 38397, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 38459, "s": 38438, "text": "Operators in C / C++" } ]
C program to Insert an element in an Array - GeeksforGeeks
15 Oct, 2020 An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C.Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos. Approach: Here’s how to do it. First get the element to be inserted, say xThen get the position at which this element is to be inserted, say posThen shift the array elements from this position to one position forward, and do this for all the other elements next to pos.Insert the element x now at the position pos, as this is now empty. First get the element to be inserted, say x Then get the position at which this element is to be inserted, say pos Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos. Insert the element x now at the position pos, as this is now empty. Below is the implementation of the above approach: C // C Program to Insert an element// at a specific position in an Array #include <stdio.h> int main(){ int arr[100] = { 0 }; int i, x, pos, n = 10; // initial array of size 10 for (i = 0; i < 10; i++) arr[i] = i + 1; // print the original array for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); // element to be inserted x = 50; // position at which element // is to be inserted pos = 5; // increase the size by 1 n++; // shift elements forward for (i = n-1; i >= pos; i--) arr[i] = arr[i - 1]; // insert x at pos arr[pos - 1] = x; // print the updated array for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); return 0;} 1 2 3 4 5 6 7 8 9 10 1 2 3 4 50 5 6 7 8 9 10 aniket_lodh c-array C-Arrays C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Converting Strings to Numbers in C/C++ rand() and srand() in C/C++ std::string class in C++ fork() in C Different methods to reverse a string in C/C++ Enumeration (or enum) in C Command line arguments in C/C++
[ { "code": null, "e": 25659, "s": 25631, "text": "\n15 Oct, 2020" }, { "code": null, "e": 25926, "s": 25659, "text": "An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C.Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos. " }, { "code": null, "e": 25958, "s": 25926, "text": "Approach: Here’s how to do it. " }, { "code": null, "e": 26264, "s": 25958, "text": "First get the element to be inserted, say xThen get the position at which this element is to be inserted, say posThen shift the array elements from this position to one position forward, and do this for all the other elements next to pos.Insert the element x now at the position pos, as this is now empty." }, { "code": null, "e": 26308, "s": 26264, "text": "First get the element to be inserted, say x" }, { "code": null, "e": 26379, "s": 26308, "text": "Then get the position at which this element is to be inserted, say pos" }, { "code": null, "e": 26505, "s": 26379, "text": "Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos." }, { "code": null, "e": 26573, "s": 26505, "text": "Insert the element x now at the position pos, as this is now empty." }, { "code": null, "e": 26625, "s": 26573, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26627, "s": 26625, "text": "C" }, { "code": "// C Program to Insert an element// at a specific position in an Array #include <stdio.h> int main(){ int arr[100] = { 0 }; int i, x, pos, n = 10; // initial array of size 10 for (i = 0; i < 10; i++) arr[i] = i + 1; // print the original array for (i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\"); // element to be inserted x = 50; // position at which element // is to be inserted pos = 5; // increase the size by 1 n++; // shift elements forward for (i = n-1; i >= pos; i--) arr[i] = arr[i - 1]; // insert x at pos arr[pos - 1] = x; // print the updated array for (i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\"); return 0;}", "e": 27371, "s": 26627, "text": null }, { "code": null, "e": 27419, "s": 27371, "text": "1 2 3 4 5 6 7 8 9 10 \n1 2 3 4 50 5 6 7 8 9 10\n\n" }, { "code": null, "e": 27433, "s": 27421, "text": "aniket_lodh" }, { "code": null, "e": 27441, "s": 27433, "text": "c-array" }, { "code": null, "e": 27450, "s": 27441, "text": "C-Arrays" }, { "code": null, "e": 27461, "s": 27450, "text": "C Language" }, { "code": null, "e": 27559, "s": 27461, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27576, "s": 27559, "text": "Substring in C++" }, { "code": null, "e": 27611, "s": 27576, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27657, "s": 27611, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27696, "s": 27657, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 27724, "s": 27696, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27749, "s": 27724, "text": "std::string class in C++" }, { "code": null, "e": 27761, "s": 27749, "text": "fork() in C" }, { "code": null, "e": 27808, "s": 27761, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 27835, "s": 27808, "text": "Enumeration (or enum) in C" } ]
Kotlin hashSetOf() - GeeksforGeeks
18 Aug, 2021 Kotlin HashSet is a generic unordered collection of elements and it does not contain duplicate elements. It implements the set interface. hashSetOf() is a function which returns a mutable hashSet, which can be both read and written. The HashSet class store all the elements using hashing mechanism. Syntax: fun <T> hashSetOf(vararg elements: T): HashSet<T> It returns a new HashSet with the given elements but does not guarantee about the order sequence specified at the storing time. Example of hashSetOf() Kotlin fun main(args: Array<String>){ //declaring a hash set of integers val seta = hashSetOf(1,2,3,3); //printing first set println(seta) //declaring a hash set of strings val setb = hashSetOf("Geeks","for","geeks"); println(setb); } Output: [1, 2, 3] [Geeks, for, geeks] We can add elements in a hashset using add() and addAll() functions. We can remove an element using remove() function. Kotlin program of using the add() and remove() method – Kotlin fun main(args: Array<String>){ //declaring a hash set of integers val seta = hashSetOf<Int>(); println(seta) //adding elements seta.add(1) seta.add(2) //making an extra set to add it in seta val newset = setOf(4,5,6) seta.addAll(newset) println(seta) //removing 2 from the set seta.remove(2) println(seta) } Output: [] [1, 2, 4, 5, 6] [1, 4, 5, 6] We can traverse a hashSet using an iterator in a loop. Kotlin fun main(args: Array<String>){ //declaring a hash set of integers val seta = hashSetOf(1,2,3,5); //traversing in a set using a for loop for(item in seta) println(item)} Output: 1 2 3 5 Using index functions indexOf() , lastIndexOf() we can get the index of the specified element. And we can also find the elements at some specific index using elementAt() function. Kotlin program of using index – Kotlin fun main(args: Array<String>) { val captains = hashSetOf("Kohli","Smith","Root","Malinga","Rohit","Dhawan") println("The element at index 2 is: "+captains.elementAt(3)) println("The index of element is: "+captains.indexOf("Smith")) println("The last index of element is: "+captains.lastIndexOf("Rohit"))} Output: The element at index 2 is: Malinga The index of element is: 4 The last index of element is: 0 Both the methods are used to check whether an element is present in the Hashset or not? Kotlin program of using contains() and containsAll() function – Kotlin fun main(args: Array<String>){ val captains = hashSetOf(1,2,3,4,"Kohli","Smith", "Root","Malinga","Rohit","Dhawan") var name = "Rohit" println("The set contains the element $name or not?" + " "+captains.contains(name)) var num = 5 println("The set contains the element $num or not?" + " "+captains.contains(num)) println("The set contains the given elements or not?" + " "+captains.containsAll(setOf(1,3,"Dhawan","Warner")))} Output: The set contains the element Rohit or not? true The set contains the element 5 or not? false The set contains the given elements or not? false fun <T> hashSetOf(): hashSet<T> This syntax returns an empty hash set of a specific type.Kotlin program of using isEmpty() function – Kotlin fun main(args: Array<String>) { //creating an empty hash set of strings val seta = hashSetOf<String>() //creating an empty hashset of integers val setb =hashSetOf<Int>() //checking if set is empty or not println("seta.isEmpty() is ${seta.isEmpty()}") // Since Empty hashsets are equal //checking if two hash sets are equal or not println("seta == setb is ${seta == setb}")} Output : seta.isEmpty() is true seta == setb is true singghakshay arorakashish0911 Kotlin Collections Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example Android RecyclerView in Kotlin Android UI Layouts Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android How to Change the Color of Status Bar in an Android App? Kotlin Setters and Getters Android Menus ImageView in Android with Example How to Get Current Location in Android?
[ { "code": null, "e": 23587, "s": 23559, "text": "\n18 Aug, 2021" }, { "code": null, "e": 23886, "s": 23587, "text": "Kotlin HashSet is a generic unordered collection of elements and it does not contain duplicate elements. It implements the set interface. hashSetOf() is a function which returns a mutable hashSet, which can be both read and written. The HashSet class store all the elements using hashing mechanism." }, { "code": null, "e": 23895, "s": 23886, "text": "Syntax: " }, { "code": null, "e": 23945, "s": 23895, "text": "fun <T> hashSetOf(vararg elements: T): HashSet<T>" }, { "code": null, "e": 24073, "s": 23945, "text": "It returns a new HashSet with the given elements but does not guarantee about the order sequence specified at the storing time." }, { "code": null, "e": 24098, "s": 24073, "text": "Example of hashSetOf() " }, { "code": null, "e": 24105, "s": 24098, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ //declaring a hash set of integers val seta = hashSetOf(1,2,3,3); //printing first set println(seta) //declaring a hash set of strings val setb = hashSetOf(\"Geeks\",\"for\",\"geeks\"); println(setb); }", "e": 24367, "s": 24105, "text": null }, { "code": null, "e": 24376, "s": 24367, "text": "Output: " }, { "code": null, "e": 24407, "s": 24376, "text": "[1, 2, 3]\n[Geeks, for, geeks] " }, { "code": null, "e": 24476, "s": 24407, "text": "We can add elements in a hashset using add() and addAll() functions." }, { "code": null, "e": 24526, "s": 24476, "text": "We can remove an element using remove() function." }, { "code": null, "e": 24584, "s": 24526, "text": "Kotlin program of using the add() and remove() method – " }, { "code": null, "e": 24591, "s": 24584, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ //declaring a hash set of integers val seta = hashSetOf<Int>(); println(seta) //adding elements seta.add(1) seta.add(2) //making an extra set to add it in seta val newset = setOf(4,5,6) seta.addAll(newset) println(seta) //removing 2 from the set seta.remove(2) println(seta) }", "e": 24949, "s": 24591, "text": null }, { "code": null, "e": 24958, "s": 24949, "text": "Output: " }, { "code": null, "e": 24991, "s": 24958, "text": "[]\n[1, 2, 4, 5, 6]\n[1, 4, 5, 6] " }, { "code": null, "e": 25046, "s": 24991, "text": "We can traverse a hashSet using an iterator in a loop." }, { "code": null, "e": 25053, "s": 25046, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ //declaring a hash set of integers val seta = hashSetOf(1,2,3,5); //traversing in a set using a for loop for(item in seta) println(item)}", "e": 25247, "s": 25053, "text": null }, { "code": null, "e": 25256, "s": 25247, "text": "Output: " }, { "code": null, "e": 25264, "s": 25256, "text": "1\n2\n3\n5" }, { "code": null, "e": 25444, "s": 25264, "text": "Using index functions indexOf() , lastIndexOf() we can get the index of the specified element. And we can also find the elements at some specific index using elementAt() function." }, { "code": null, "e": 25478, "s": 25444, "text": "Kotlin program of using index – " }, { "code": null, "e": 25485, "s": 25478, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { val captains = hashSetOf(\"Kohli\",\"Smith\",\"Root\",\"Malinga\",\"Rohit\",\"Dhawan\") println(\"The element at index 2 is: \"+captains.elementAt(3)) println(\"The index of element is: \"+captains.indexOf(\"Smith\")) println(\"The last index of element is: \"+captains.lastIndexOf(\"Rohit\"))}", "e": 25806, "s": 25485, "text": null }, { "code": null, "e": 25815, "s": 25806, "text": "Output: " }, { "code": null, "e": 25910, "s": 25815, "text": "The element at index 2 is: Malinga\nThe index of element is: 4\nThe last index of element is: 0 " }, { "code": null, "e": 26063, "s": 25910, "text": "Both the methods are used to check whether an element is present in the Hashset or not? Kotlin program of using contains() and containsAll() function – " }, { "code": null, "e": 26070, "s": 26063, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ val captains = hashSetOf(1,2,3,4,\"Kohli\",\"Smith\", \"Root\",\"Malinga\",\"Rohit\",\"Dhawan\") var name = \"Rohit\" println(\"The set contains the element $name or not?\" + \" \"+captains.contains(name)) var num = 5 println(\"The set contains the element $num or not?\" + \" \"+captains.contains(num)) println(\"The set contains the given elements or not?\" + \" \"+captains.containsAll(setOf(1,3,\"Dhawan\",\"Warner\")))}", "e": 26564, "s": 26070, "text": null }, { "code": null, "e": 26573, "s": 26564, "text": "Output: " }, { "code": null, "e": 26723, "s": 26573, "text": "The set contains the element Rohit or not? true\nThe set contains the element 5 or not? false\nThe set contains the given elements or not? false " }, { "code": null, "e": 26755, "s": 26723, "text": "fun <T> hashSetOf(): hashSet<T>" }, { "code": null, "e": 26858, "s": 26755, "text": "This syntax returns an empty hash set of a specific type.Kotlin program of using isEmpty() function – " }, { "code": null, "e": 26865, "s": 26858, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { //creating an empty hash set of strings val seta = hashSetOf<String>() //creating an empty hashset of integers val setb =hashSetOf<Int>() //checking if set is empty or not println(\"seta.isEmpty() is ${seta.isEmpty()}\") // Since Empty hashsets are equal //checking if two hash sets are equal or not println(\"seta == setb is ${seta == setb}\")}", "e": 27270, "s": 26865, "text": null }, { "code": null, "e": 27280, "s": 27270, "text": "Output : " }, { "code": null, "e": 27324, "s": 27280, "text": "seta.isEmpty() is true\nseta == setb is true" }, { "code": null, "e": 27339, "s": 27326, "text": "singghakshay" }, { "code": null, "e": 27356, "s": 27339, "text": "arorakashish0911" }, { "code": null, "e": 27375, "s": 27356, "text": "Kotlin Collections" }, { "code": null, "e": 27382, "s": 27375, "text": "Picked" }, { "code": null, "e": 27389, "s": 27382, "text": "Kotlin" }, { "code": null, "e": 27487, "s": 27389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27496, "s": 27487, "text": "Comments" }, { "code": null, "e": 27509, "s": 27496, "text": "Old Comments" }, { "code": null, "e": 27552, "s": 27509, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 27583, "s": 27552, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 27602, "s": 27583, "text": "Android UI Layouts" }, { "code": null, "e": 27644, "s": 27602, "text": "Content Providers in Android with Example" }, { "code": null, "e": 27686, "s": 27644, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 27743, "s": 27686, "text": "How to Change the Color of Status Bar in an Android App?" }, { "code": null, "e": 27770, "s": 27743, "text": "Kotlin Setters and Getters" }, { "code": null, "e": 27784, "s": 27770, "text": "Android Menus" }, { "code": null, "e": 27818, "s": 27784, "text": "ImageView in Android with Example" } ]
Batch Script - DRIVERQUERY
This batch command shows all installed device drivers and their properties. driverquery @echo off driverquery The above command will display the information of all the device drivers installed on the current system. Following is an example of a subset of the information displayed. WacomPen Wacom Serial Pen HID D Kernel 8/22/2013 4:39:15 AM Wanarp Remote Access IP ARP D Kernel 8/22/2013 4:35:45 AM Wanarpv6 Remote Access IPv6 ARP Kernel 8/22/2013 4:35:45 AM Wdf01000 Kernel Mode Driver Fra Kernel 8/22/2013 4:38:56 AM WFPLWFS Microsoft Windows Filt Kernel 11/9/2014 6:57:28 PM WIMMount WIMMount File System 8/22/2013 4:39:34 AM WinMad WinMad Service Kernel 5/9/2013 9:14:27 AM WinNat Windows NAT Driver Kernel 1/22/2014 1:10:49 AM WinUsb WinUsb Driver Kernel 8/22/2013 4:37:55 AM WinVerbs WinVerbs Service Kernel 5/9/2013 9:14:30 AM WmiAcpi Microsoft Windows Mana Kernel 8/22/2013 4:40:04 AM WpdUpFltr WPD Upper Class Filter Kernel 8/22/2013 4:38:45 AM ws2ifsl Windows Socket 2.0 Non Kernel 8/22/2013 4:40:03 AM wtlmdrv Microsoft iSCSI Target Kernel 8/22/2013 4:39:19 AM WudfPf User Mode Driver Frame Kernel 8/22/2013 4:37:21 AM WUDFWpdFs WUDFWpdFs Kernel 8/22/2013 4:36:50 AM WUDFWpdMtp WUDFWpdMtp Kernel 8/22/2013 4:36:50 AM Print Add Notes Bookmark this page
[ { "code": null, "e": 2245, "s": 2169, "text": "This batch command shows all installed device drivers and their properties." }, { "code": null, "e": 2258, "s": 2245, "text": "driverquery\n" }, { "code": null, "e": 2281, "s": 2258, "text": "@echo off \ndriverquery" }, { "code": null, "e": 2453, "s": 2281, "text": "The above command will display the information of all the device drivers installed on the current system. Following is an example of a subset of the information displayed." }, { "code": null, "e": 3691, "s": 2453, "text": "WacomPen Wacom Serial Pen HID D Kernel 8/22/2013 4:39:15 AM \nWanarp Remote Access IP ARP D Kernel 8/22/2013 4:35:45 AM \nWanarpv6 Remote Access IPv6 ARP Kernel 8/22/2013 4:35:45 AM \nWdf01000 Kernel Mode Driver Fra Kernel 8/22/2013 4:38:56 AM \nWFPLWFS Microsoft Windows Filt Kernel 11/9/2014 6:57:28 PM \nWIMMount WIMMount File System 8/22/2013 4:39:34 AM\nWinMad WinMad Service Kernel 5/9/2013 9:14:27 AM \nWinNat Windows NAT Driver Kernel 1/22/2014 1:10:49 AM \nWinUsb WinUsb Driver Kernel 8/22/2013 4:37:55 AM \nWinVerbs WinVerbs Service Kernel 5/9/2013 9:14:30 AM \nWmiAcpi Microsoft Windows Mana Kernel 8/22/2013 4:40:04 AM \nWpdUpFltr WPD Upper Class Filter Kernel 8/22/2013 4:38:45 AM \nws2ifsl Windows Socket 2.0 Non Kernel 8/22/2013 4:40:03 AM\nwtlmdrv Microsoft iSCSI Target Kernel 8/22/2013 4:39:19 AM \nWudfPf User Mode Driver Frame Kernel 8/22/2013 4:37:21 AM \nWUDFWpdFs WUDFWpdFs Kernel 8/22/2013 4:36:50 AM \nWUDFWpdMtp WUDFWpdMtp Kernel 8/22/2013 4:36:50 AM\n" }, { "code": null, "e": 3698, "s": 3691, "text": " Print" }, { "code": null, "e": 3709, "s": 3698, "text": " Add Notes" } ]
Should I store a field PRICE as an int or as a float in the database?
You do not need to store a field PRICE as an int or as float in the database. For this, you can set the DECIMAL().. Most of the time integers can be used to represent the float point numbers and these integers are internally cast into DECIMAL() data type. Therefore, if you have field PRICE then always use DECIMAL() data type. The syntax is as follows − DECIMAL(M,D); Here, M represents the ‘TotalNumberOfDigit’ and D represents the ‘Number OfDigitAfterDecimalPoint’. To understand the above concept, let us create a table with field PRICE as DECIMAL data type. The query is as follows − mysql> create table Decimal_Demo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> PRICE DECIMAL(18,2), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.63 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into Decimal_Demo(PRICE) values(99999999999999.99); Query OK, 1 row affected (0.11 sec) mysql> insert into Decimal_Demo(PRICE) values(10000000000000.99); Query OK, 1 row affected (0.36 sec) Now you can display all records from the table using a select statement. The query is as follows − mysql> select *from Decimal_Demo; The following is the output − +----+-------------------+ | Id | PRICE | +----+-------------------+ | 1 | 99999999999999.99 | | 2 | 10000000000000.99 | +----+-------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1178, "s": 1062, "text": "You do not need to store a field PRICE as an int or as float in the database. For this, you can set the DECIMAL().." }, { "code": null, "e": 1417, "s": 1178, "text": "Most of the time integers can be used to represent the float point numbers and these integers are internally cast into DECIMAL() data type. Therefore, if you have field PRICE then always use DECIMAL() data type. The syntax is as follows −" }, { "code": null, "e": 1431, "s": 1417, "text": "DECIMAL(M,D);" }, { "code": null, "e": 1531, "s": 1431, "text": "Here, M represents the ‘TotalNumberOfDigit’ and D represents the ‘Number OfDigitAfterDecimalPoint’." }, { "code": null, "e": 1651, "s": 1531, "text": "To understand the above concept, let us create a table with field PRICE as DECIMAL data type. The query is as follows −" }, { "code": null, "e": 1825, "s": 1651, "text": "mysql> create table Decimal_Demo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> PRICE DECIMAL(18,2),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (1.63 sec)" }, { "code": null, "e": 1906, "s": 1825, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2110, "s": 1906, "text": "mysql> insert into Decimal_Demo(PRICE) values(99999999999999.99);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into Decimal_Demo(PRICE) values(10000000000000.99);\nQuery OK, 1 row affected (0.36 sec)" }, { "code": null, "e": 2209, "s": 2110, "text": "Now you can display all records from the table using a select statement. The query is as follows −" }, { "code": null, "e": 2243, "s": 2209, "text": "mysql> select *from Decimal_Demo;" }, { "code": null, "e": 2273, "s": 2243, "text": "The following is the output −" }, { "code": null, "e": 2460, "s": 2273, "text": "+----+-------------------+\n| Id | PRICE |\n+----+-------------------+\n| 1 | 99999999999999.99 |\n| 2 | 10000000000000.99 |\n+----+-------------------+\n2 rows in set (0.00 sec)" } ]
Wondering how to build an anomaly detection model? | by Abhishek Kumar | Towards Data Science
Hey guys! Have you ever given a thought about how banks identify the fraudulent accounts? or how can you detect some faulty servers in your network? or how do you tackle problems in machine learning where you don’t have enough knowledge about your positive examples? Well, you’ve landed in the right place. Anomaly detection is a technique used to identify unusual patterns that do not conform to expected behaviour, called outliers. It has many applications in business, from intrusion detection (identifying strange patterns in network traffic that could signal a hack) to system health monitoring (spotting a malignant tumour in an MRI scan), and from fraud detection in credit card transactions to fault detection in operating environments. You would understand to use numpy and how to do matrix multiplication using it. You would use the matplot library to plot and visualize the anomalies. You would use a Gaussian Distribution to find the probabilties of the dataset. You would be able to apply Vectorization to make your code more efficient. You would learn the concept of F1 score and use it to calculate precision and recall to make your predictions more accurate. You would get to learn error handling in python using try-except. Hmm...excited? Let’s get started. So, we are making an anomaly detection model and apply it to detect failing servers on a network. Before going into the original dataset let’s first visualize how to proceed and carry out different functions. Let’s start by importing a few libraries. We’ll be using a dummy dataset to check whether all the functions are working properly and we would then use these functions on our original dataset. Are we good? Now, we’ll import the dataset and one thing to note here is that the dataset should be in the same directory where your script is present. sio.loadmat() loads our dataset(‘anomalyData.mat’) into the variable dataset. The variable ‘X’ contains the training dataset, ‘Xval’ the cross-validation set and ‘yval’ the corresponding output for the ‘Xval’. Let’s see the array ‘X’ that we are going to use to fit it in a Gaussian model to detect anomalous examples. print(X.shape)(307, 2) As you can see there are 307 training examples and each having 2 features. The features measure the throughput (mb/s) and latency (ms) of response of each server. While your servers were operating, you collected m = 307 examples of how they were behaving, and thus have an unlabeled dataset {x(1), . . . , x(m)}. You suspect that the vast majority of these examples are “normal” (non-anomalous) examples of the servers operating normally, but there might also be some examples of servers acting anomalously within this dataset. Now, let’s visualize the dataset to have a clear picture. To perform anomaly detection, you will first need to fit a model to the data’s distribution. Given a training set {x(1), ..., x(m)} (where x(i) ∈ R^n, here n = 2), you want to estimate the Gaussian distribution for each of the features. For each feature (i = 1 . . . n), you need to find parameters mean and variance(mu, sigma2). For doing that let’s write down the function that calculates the mean and variance of the array(or you can call it matrix) X. The mathematical expression goes something like this: We’ve got to calculate the mean for each feature and with the help of that, we calculate the variance of the corresponding features. Let’s put it into code. mu, sigma2 = estimateGaussian(X)print('mean: ',mu,' variance: ',sigma2) mean: [[14.11222578 14.99771051]] variance: [[1.83263141 1.70974533]] Now that we have the mean and variance we need to calculate the probability of the training examples in order to decide which examples are anomalous. We can do it by using the Multivariate Gaussian model. The multivariate Gaussian is used to find the probability of each example and based on some threshold value we decide whether to flag an anomaly or not. The expression for calculating the parameters for the Gaussian model are: Here, mu is the mean of each feature and the variable sigma calculates the covariance matrix. These two parameters are used to calculate the probability p(x). ‘e’ is the threshold value that we are going to discuss in detail further. Once you understand the expression, the code is very simple to implement. Let’s see how to put it into code. Inside the function, first, we convert the sigma2 vector into a covariance matrix and then we simply apply the formula for the multivariate distribution to get the probability vector. If you’ve passed a vector in sigma2 you’ve to convert it into a matrix with the vector as the diagonal and rest of the element as zero(line 6). p = multivariateGaussian(X, mu, sigma2)print(p.shape)(307, 1) Thus, you’ve successfully calculated the probabilities. Next, you’ve to calculate to the threshold value using some labelled data. Let’s see how to do this. pval = multivariateGaussian(Xval, mu, sigma2) We find the probabilities of ‘Xval’ to compare it with ‘yval’ for determining the threshold. Let’s find the threshold value. First, we find the stepsize to have a wide range of threshold values to decide the best one. We use the F1 score method to determine the best parameters i.e bestepsilon and bestF1. Predict anomaly if pval<epsilon that gives a vector of binary values in the variable predict. F1 score takes into consideration precision and recall. In line number 19 I’ve implemented a for loop to calculate the tp, fp, and fn. I’d love to hear from you if you could come out with some vectorised implementation for the Logic. Precision = true positive/(true positive + false positive) Recall = true positive /(true positive + false negative) Best parameters are the ones in which the F1 score value is maximum. Note: We are going to need a try-except block because there can be cases where we divide by zero to calculate precision and recall. F1, epsilon = selectThreshHold(yval, pval)print('Epsilon and F1 are:',epsilon, F1)Output:Warning dividing by zero!!Epsilon and F1 are: 8.990852779269493e-05 0.8750000000000001 Now, we have the best epsilon value and we are now in a position to calculate the anomalies on the training data’s probability. We also call the anomalies as outliers. outl = (p < epsilon) We need to return the indices of the outliers to identify the faulty servers. This gives us a vector with binary entries where 1 means anomaly and 0 means normal. Output:Number of outliers: 6 [300, 301, 303, 304, 305, 306] So, the faulty servers were as mentioned above. We can also graphically spot the outliers. Congratulations !! We’ve successfully tested all our functions and we can use them on some real dataset to find out the anomalies. Let’s finish what we’ve started. Output:(1000, 11)(100, 11)(100, 1) The newDatset has 1000 examples each having 11 features. The ‘Xvaltest’ is the cross-validation set for the test samples and ‘yvaltest’ the corresponding labels. Now, do the same thing that you did for the dummy dataset. Output:Warning dividing by zero!!Best epsilon and F1 are 1.3772288907613575e-18 0.6153846153846154 Ptest contains the prediction for the test samples and pvaltest for the cross-validation set. The best epsilon value comes out to be the order of exp(-18). Check for the Outliers: Output: Outliers are: [9, 20, 21, 30, 39, 56, 62, 63, 69, 70, 77, 79, 86, 103, 130, 147, 154, 166, 175, 176, 198, 209, 212, 218, 222, 227, 229, 233, 244, 262, 266, 271, 276, 284, 285, 288, 289, 290, 297, 303, 307, 308, 320, 324, 338, 341, 342, 344, 350, 351, 353, 365, 369, 371, 378, 398, 407, 420, 421, 424, 429, 438, 452, 455, 456, 462, 478, 497, 518, 527, 530, 539, 541, 551, 574, 583, 587, 602, 613, 614, 628, 648, 674, 678, 682, 685, 700, 702, 705, 713, 721, 741, 750, 757, 758, 787, 831, 834, 836, 839, 846, 870, 885, 887, 890, 901, 911, 930, 939, 940, 943, 951, 952, 970, 975, 992, 996]Number of outliers are: 117 Thus, there are 117 outliers and their corresponding indices are given as above. I know that starting from scratch could be a messy thing sometimes but you would get to learn a lot of details if you do it from scratch. You could find the notebook here for the above project. I hope I could teach you something new and make sure you check out my repository I’ve made other projects like Minimizing the cost of a data centres(using Deep-Reinforcement Learning), DigitRecognition, Clustering a bird’s image etc. References: Machine learning by Andrew Ng
[ { "code": null, "e": 439, "s": 172, "text": "Hey guys! Have you ever given a thought about how banks identify the fraudulent accounts? or how can you detect some faulty servers in your network? or how do you tackle problems in machine learning where you don’t have enough knowledge about your positive examples?" }, { "code": null, "e": 917, "s": 439, "text": "Well, you’ve landed in the right place. Anomaly detection is a technique used to identify unusual patterns that do not conform to expected behaviour, called outliers. It has many applications in business, from intrusion detection (identifying strange patterns in network traffic that could signal a hack) to system health monitoring (spotting a malignant tumour in an MRI scan), and from fraud detection in credit card transactions to fault detection in operating environments." }, { "code": null, "e": 997, "s": 917, "text": "You would understand to use numpy and how to do matrix multiplication using it." }, { "code": null, "e": 1068, "s": 997, "text": "You would use the matplot library to plot and visualize the anomalies." }, { "code": null, "e": 1147, "s": 1068, "text": "You would use a Gaussian Distribution to find the probabilties of the dataset." }, { "code": null, "e": 1222, "s": 1147, "text": "You would be able to apply Vectorization to make your code more efficient." }, { "code": null, "e": 1347, "s": 1222, "text": "You would learn the concept of F1 score and use it to calculate precision and recall to make your predictions more accurate." }, { "code": null, "e": 1413, "s": 1347, "text": "You would get to learn error handling in python using try-except." }, { "code": null, "e": 1447, "s": 1413, "text": "Hmm...excited? Let’s get started." }, { "code": null, "e": 1698, "s": 1447, "text": "So, we are making an anomaly detection model and apply it to detect failing servers on a network. Before going into the original dataset let’s first visualize how to proceed and carry out different functions. Let’s start by importing a few libraries." }, { "code": null, "e": 2000, "s": 1698, "text": "We’ll be using a dummy dataset to check whether all the functions are working properly and we would then use these functions on our original dataset. Are we good? Now, we’ll import the dataset and one thing to note here is that the dataset should be in the same directory where your script is present." }, { "code": null, "e": 2319, "s": 2000, "text": "sio.loadmat() loads our dataset(‘anomalyData.mat’) into the variable dataset. The variable ‘X’ contains the training dataset, ‘Xval’ the cross-validation set and ‘yval’ the corresponding output for the ‘Xval’. Let’s see the array ‘X’ that we are going to use to fit it in a Gaussian model to detect anomalous examples." }, { "code": null, "e": 2342, "s": 2319, "text": "print(X.shape)(307, 2)" }, { "code": null, "e": 2928, "s": 2342, "text": "As you can see there are 307 training examples and each having 2 features. The features measure the throughput (mb/s) and latency (ms) of response of each server. While your servers were operating, you collected m = 307 examples of how they were behaving, and thus have an unlabeled dataset {x(1), . . . , x(m)}. You suspect that the vast majority of these examples are “normal” (non-anomalous) examples of the servers operating normally, but there might also be some examples of servers acting anomalously within this dataset. Now, let’s visualize the dataset to have a clear picture." }, { "code": null, "e": 3384, "s": 2928, "text": "To perform anomaly detection, you will first need to fit a model to the data’s distribution. Given a training set {x(1), ..., x(m)} (where x(i) ∈ R^n, here n = 2), you want to estimate the Gaussian distribution for each of the features. For each feature (i = 1 . . . n), you need to find parameters mean and variance(mu, sigma2). For doing that let’s write down the function that calculates the mean and variance of the array(or you can call it matrix) X." }, { "code": null, "e": 3438, "s": 3384, "text": "The mathematical expression goes something like this:" }, { "code": null, "e": 3595, "s": 3438, "text": "We’ve got to calculate the mean for each feature and with the help of that, we calculate the variance of the corresponding features. Let’s put it into code." }, { "code": null, "e": 3740, "s": 3595, "text": "mu, sigma2 = estimateGaussian(X)print('mean: ',mu,' variance: ',sigma2) mean: [[14.11222578 14.99771051]] variance: [[1.83263141 1.70974533]]" }, { "code": null, "e": 3945, "s": 3740, "text": "Now that we have the mean and variance we need to calculate the probability of the training examples in order to decide which examples are anomalous. We can do it by using the Multivariate Gaussian model." }, { "code": null, "e": 4172, "s": 3945, "text": "The multivariate Gaussian is used to find the probability of each example and based on some threshold value we decide whether to flag an anomaly or not. The expression for calculating the parameters for the Gaussian model are:" }, { "code": null, "e": 4515, "s": 4172, "text": "Here, mu is the mean of each feature and the variable sigma calculates the covariance matrix. These two parameters are used to calculate the probability p(x). ‘e’ is the threshold value that we are going to discuss in detail further. Once you understand the expression, the code is very simple to implement. Let’s see how to put it into code." }, { "code": null, "e": 4843, "s": 4515, "text": "Inside the function, first, we convert the sigma2 vector into a covariance matrix and then we simply apply the formula for the multivariate distribution to get the probability vector. If you’ve passed a vector in sigma2 you’ve to convert it into a matrix with the vector as the diagonal and rest of the element as zero(line 6)." }, { "code": null, "e": 4905, "s": 4843, "text": "p = multivariateGaussian(X, mu, sigma2)print(p.shape)(307, 1)" }, { "code": null, "e": 5062, "s": 4905, "text": "Thus, you’ve successfully calculated the probabilities. Next, you’ve to calculate to the threshold value using some labelled data. Let’s see how to do this." }, { "code": null, "e": 5108, "s": 5062, "text": "pval = multivariateGaussian(Xval, mu, sigma2)" }, { "code": null, "e": 5233, "s": 5108, "text": "We find the probabilities of ‘Xval’ to compare it with ‘yval’ for determining the threshold. Let’s find the threshold value." }, { "code": null, "e": 5564, "s": 5233, "text": "First, we find the stepsize to have a wide range of threshold values to decide the best one. We use the F1 score method to determine the best parameters i.e bestepsilon and bestF1. Predict anomaly if pval<epsilon that gives a vector of binary values in the variable predict. F1 score takes into consideration precision and recall." }, { "code": null, "e": 5742, "s": 5564, "text": "In line number 19 I’ve implemented a for loop to calculate the tp, fp, and fn. I’d love to hear from you if you could come out with some vectorised implementation for the Logic." }, { "code": null, "e": 5801, "s": 5742, "text": "Precision = true positive/(true positive + false positive)" }, { "code": null, "e": 5858, "s": 5801, "text": "Recall = true positive /(true positive + false negative)" }, { "code": null, "e": 5927, "s": 5858, "text": "Best parameters are the ones in which the F1 score value is maximum." }, { "code": null, "e": 6059, "s": 5927, "text": "Note: We are going to need a try-except block because there can be cases where we divide by zero to calculate precision and recall." }, { "code": null, "e": 6235, "s": 6059, "text": "F1, epsilon = selectThreshHold(yval, pval)print('Epsilon and F1 are:',epsilon, F1)Output:Warning dividing by zero!!Epsilon and F1 are: 8.990852779269493e-05 0.8750000000000001" }, { "code": null, "e": 6403, "s": 6235, "text": "Now, we have the best epsilon value and we are now in a position to calculate the anomalies on the training data’s probability. We also call the anomalies as outliers." }, { "code": null, "e": 6424, "s": 6403, "text": "outl = (p < epsilon)" }, { "code": null, "e": 6587, "s": 6424, "text": "We need to return the indices of the outliers to identify the faulty servers. This gives us a vector with binary entries where 1 means anomaly and 0 means normal." }, { "code": null, "e": 6647, "s": 6587, "text": "Output:Number of outliers: 6 [300, 301, 303, 304, 305, 306]" }, { "code": null, "e": 6738, "s": 6647, "text": "So, the faulty servers were as mentioned above. We can also graphically spot the outliers." }, { "code": null, "e": 6902, "s": 6738, "text": "Congratulations !! We’ve successfully tested all our functions and we can use them on some real dataset to find out the anomalies. Let’s finish what we’ve started." }, { "code": null, "e": 6937, "s": 6902, "text": "Output:(1000, 11)(100, 11)(100, 1)" }, { "code": null, "e": 7158, "s": 6937, "text": "The newDatset has 1000 examples each having 11 features. The ‘Xvaltest’ is the cross-validation set for the test samples and ‘yvaltest’ the corresponding labels. Now, do the same thing that you did for the dummy dataset." }, { "code": null, "e": 7257, "s": 7158, "text": "Output:Warning dividing by zero!!Best epsilon and F1 are 1.3772288907613575e-18 0.6153846153846154" }, { "code": null, "e": 7413, "s": 7257, "text": "Ptest contains the prediction for the test samples and pvaltest for the cross-validation set. The best epsilon value comes out to be the order of exp(-18)." }, { "code": null, "e": 7437, "s": 7413, "text": "Check for the Outliers:" }, { "code": null, "e": 7445, "s": 7437, "text": "Output:" }, { "code": null, "e": 8059, "s": 7445, "text": "Outliers are: [9, 20, 21, 30, 39, 56, 62, 63, 69, 70, 77, 79, 86, 103, 130, 147, 154, 166, 175, 176, 198, 209, 212, 218, 222, 227, 229, 233, 244, 262, 266, 271, 276, 284, 285, 288, 289, 290, 297, 303, 307, 308, 320, 324, 338, 341, 342, 344, 350, 351, 353, 365, 369, 371, 378, 398, 407, 420, 421, 424, 429, 438, 452, 455, 456, 462, 478, 497, 518, 527, 530, 539, 541, 551, 574, 583, 587, 602, 613, 614, 628, 648, 674, 678, 682, 685, 700, 702, 705, 713, 721, 741, 750, 757, 758, 787, 831, 834, 836, 839, 846, 870, 885, 887, 890, 901, 911, 930, 939, 940, 943, 951, 952, 970, 975, 992, 996]Number of outliers are: 117" }, { "code": null, "e": 8140, "s": 8059, "text": "Thus, there are 117 outliers and their corresponding indices are given as above." }, { "code": null, "e": 8568, "s": 8140, "text": "I know that starting from scratch could be a messy thing sometimes but you would get to learn a lot of details if you do it from scratch. You could find the notebook here for the above project. I hope I could teach you something new and make sure you check out my repository I’ve made other projects like Minimizing the cost of a data centres(using Deep-Reinforcement Learning), DigitRecognition, Clustering a bird’s image etc." } ]
HTML | <option> selected Attribute - GeeksforGeeks
31 Mar, 2021 The HTML <option> selected Attribute is used to specify which option should be by default selected when the page loads. This is a boolean attribute. The option that is having the selected attribute will be displayed by default.Syntax: <option selected> Example-1: This Example illustrates the use of selected attribute in option Element. html <!-- HTML program to illustrate selected Attribute --> <!DOCTYPE html><html> <head> <title>HTML selected Attribute</title></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <h2>HTML Option selected Attribute</h2> <!-- List of Options --> <select> <option value="merge">Merge Sort</option> <option value="bubble">Bubble Sort</option> <option value="insertion">Insertion Sort</option> <!-- Option element with selected attribute --> <option value="quick" selected>Quick Sort</option> </select></body> </html> Output: Example-2: html <!-- HTML program to illustrate selected Attribute --> <!DOCTYPE html><html> <head> <title>HTML selected Attribute</title></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <h2>HTML Option selected Attribute</h2> <!-- List of Options --> <select> <option value="c">C</option> <option value="cpp">C++</option><!-- Option element with selected attribute --> <option value="python" selected>Python</option> <option value="java" >JAVA</option> </select></body> </html> Output: Supported Browsers: The browser supported by HTML Option Selected Attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. simranarora5sos HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24503, "s": 24475, "text": "\n31 Mar, 2021" }, { "code": null, "e": 24740, "s": 24503, "text": "The HTML <option> selected Attribute is used to specify which option should be by default selected when the page loads. This is a boolean attribute. The option that is having the selected attribute will be displayed by default.Syntax: " }, { "code": null, "e": 24759, "s": 24740, "text": "<option selected> " }, { "code": null, "e": 24846, "s": 24759, "text": "Example-1: This Example illustrates the use of selected attribute in option Element. " }, { "code": null, "e": 24851, "s": 24846, "text": "html" }, { "code": "<!-- HTML program to illustrate selected Attribute --> <!DOCTYPE html><html> <head> <title>HTML selected Attribute</title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h2>HTML Option selected Attribute</h2> <!-- List of Options --> <select> <option value=\"merge\">Merge Sort</option> <option value=\"bubble\">Bubble Sort</option> <option value=\"insertion\">Insertion Sort</option> <!-- Option element with selected attribute --> <option value=\"quick\" selected>Quick Sort</option> </select></body> </html>", "e": 25450, "s": 24851, "text": null }, { "code": null, "e": 25460, "s": 25450, "text": "Output: " }, { "code": null, "e": 25473, "s": 25460, "text": "Example-2: " }, { "code": null, "e": 25478, "s": 25473, "text": "html" }, { "code": "<!-- HTML program to illustrate selected Attribute --> <!DOCTYPE html><html> <head> <title>HTML selected Attribute</title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h2>HTML Option selected Attribute</h2> <!-- List of Options --> <select> <option value=\"c\">C</option> <option value=\"cpp\">C++</option><!-- Option element with selected attribute --> <option value=\"python\" selected>Python</option> <option value=\"java\" >JAVA</option> </select></body> </html> ", "e": 26046, "s": 25478, "text": null }, { "code": null, "e": 26056, "s": 26046, "text": "Output: " }, { "code": null, "e": 26152, "s": 26056, "text": "Supported Browsers: The browser supported by HTML Option Selected Attribute are listed below: " }, { "code": null, "e": 26166, "s": 26152, "text": "Google Chrome" }, { "code": null, "e": 26184, "s": 26166, "text": "Internet Explorer" }, { "code": null, "e": 26192, "s": 26184, "text": "Firefox" }, { "code": null, "e": 26198, "s": 26192, "text": "Opera" }, { "code": null, "e": 26205, "s": 26198, "text": "Safari" }, { "code": null, "e": 26344, "s": 26207, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26360, "s": 26344, "text": "simranarora5sos" }, { "code": null, "e": 26376, "s": 26360, "text": "HTML-Attributes" }, { "code": null, "e": 26381, "s": 26376, "text": "HTML" }, { "code": null, "e": 26398, "s": 26381, "text": "Web Technologies" }, { "code": null, "e": 26403, "s": 26398, "text": "HTML" }, { "code": null, "e": 26501, "s": 26403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26510, "s": 26501, "text": "Comments" }, { "code": null, "e": 26523, "s": 26510, "text": "Old Comments" }, { "code": null, "e": 26547, "s": 26523, "text": "REST API (Introduction)" }, { "code": null, "e": 26584, "s": 26547, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26613, "s": 26584, "text": "Form validation using jQuery" }, { "code": null, "e": 26660, "s": 26613, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 26722, "s": 26660, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 26778, "s": 26722, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26811, "s": 26778, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26854, "s": 26811, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26915, "s": 26854, "text": "Difference between var, let and const keywords in JavaScript" } ]
How To Create a Countdown Timer Using Python? - GeeksforGeeks
29 Jul, 2020 In this article, we will see how to create a countdown timer using Python. The code will take input from the user regarding the length of the countdown in seconds. After that, a countdown will begin on the screen of the format ‘minutes: seconds’. We will use the time module here. In this project, we will be using the time module and its sleep() function. Follow the below steps to create a countdown timer: Step 1: Import the time module. Step 2: Then ask the user to input the length of the countdown in seconds. Step 3: This value is sent as a parameter ‘t’ to the user-defined function countdown(). Any variable read using the input function is a string. So, convert this parameter to ‘int’ as it is of string type. Step 4: In this function, a while loop runs until time becomes 0. Step 5: Use divmod() to calculate the number of minutes and seconds. You can read more about it here. Step 6: Now print the minutes and seconds on the screen using the variable timeformat. Step 7: Using end = ‘\r’ we force the cursor to go back to the start of the screen (carriage return) so that the next line printed will overwrite the previous one. Step 8: The time.sleep() is used to make the code wait for one sec. Step 9: Now decrement time so that the while loop can converge. Step 10: After the completion of the loop, we will print “Fire in the hole” to signify the end of the countdown. Below is the implementation of the above approach Python3 # import the time moduleimport time # define the countdown func.def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end="\r") time.sleep(1) t -= 1 print('Fire in the hole!!') # input time in secondst = input("Enter the time in seconds: ") # function callcountdown(int(t)) Output: Python time-module python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23779, "s": 23751, "text": "\n29 Jul, 2020" }, { "code": null, "e": 24060, "s": 23779, "text": "In this article, we will see how to create a countdown timer using Python. The code will take input from the user regarding the length of the countdown in seconds. After that, a countdown will begin on the screen of the format ‘minutes: seconds’. We will use the time module here." }, { "code": null, "e": 24188, "s": 24060, "text": "In this project, we will be using the time module and its sleep() function. Follow the below steps to create a countdown timer:" }, { "code": null, "e": 24220, "s": 24188, "text": "Step 1: Import the time module." }, { "code": null, "e": 24295, "s": 24220, "text": "Step 2: Then ask the user to input the length of the countdown in seconds." }, { "code": null, "e": 24500, "s": 24295, "text": "Step 3: This value is sent as a parameter ‘t’ to the user-defined function countdown(). Any variable read using the input function is a string. So, convert this parameter to ‘int’ as it is of string type." }, { "code": null, "e": 24566, "s": 24500, "text": "Step 4: In this function, a while loop runs until time becomes 0." }, { "code": null, "e": 24668, "s": 24566, "text": "Step 5: Use divmod() to calculate the number of minutes and seconds. You can read more about it here." }, { "code": null, "e": 24755, "s": 24668, "text": "Step 6: Now print the minutes and seconds on the screen using the variable timeformat." }, { "code": null, "e": 24919, "s": 24755, "text": "Step 7: Using end = ‘\\r’ we force the cursor to go back to the start of the screen (carriage return) so that the next line printed will overwrite the previous one." }, { "code": null, "e": 24987, "s": 24919, "text": "Step 8: The time.sleep() is used to make the code wait for one sec." }, { "code": null, "e": 25051, "s": 24987, "text": "Step 9: Now decrement time so that the while loop can converge." }, { "code": null, "e": 25164, "s": 25051, "text": "Step 10: After the completion of the loop, we will print “Fire in the hole” to signify the end of the countdown." }, { "code": null, "e": 25214, "s": 25164, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 25222, "s": 25214, "text": "Python3" }, { "code": "# import the time moduleimport time # define the countdown func.def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end=\"\\r\") time.sleep(1) t -= 1 print('Fire in the hole!!') # input time in secondst = input(\"Enter the time in seconds: \") # function callcountdown(int(t))", "e": 25608, "s": 25222, "text": null }, { "code": null, "e": 25618, "s": 25608, "text": "Output: " }, { "code": null, "e": 25639, "s": 25620, "text": "Python time-module" }, { "code": null, "e": 25654, "s": 25639, "text": "python-utility" }, { "code": null, "e": 25661, "s": 25654, "text": "Python" }, { "code": null, "e": 25759, "s": 25661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25768, "s": 25759, "text": "Comments" }, { "code": null, "e": 25781, "s": 25768, "text": "Old Comments" }, { "code": null, "e": 25799, "s": 25781, "text": "Python Dictionary" }, { "code": null, "e": 25834, "s": 25799, "text": "Read a file line by line in Python" }, { "code": null, "e": 25856, "s": 25834, "text": "Enumerate() in Python" }, { "code": null, "e": 25888, "s": 25856, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25918, "s": 25888, "text": "Iterate over a list in Python" }, { "code": null, "e": 25960, "s": 25918, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26003, "s": 25960, "text": "Python program to convert a list to string" }, { "code": null, "e": 26029, "s": 26003, "text": "Python String | replace()" }, { "code": null, "e": 26073, "s": 26029, "text": "Reading and Writing to text files in Python" } ]
Pandas Join vs. Merge. What Do They Do And When Should We Use... | by Tony Yiu | Towards Data Science
I write a lot about statistics and algorithms, but getting your data ready for modeling is a huge part of data science as well. In fact, it’s highly likely that you will spend significantly more time staring at your data, checking it, and fixing its holes than on training and tweaking your models. So the better we get at collecting, cleaning, and performing quick “sanity check” analyses on data, the more time we can spend on modeling (which most folks find more entertaining). To that end, let’s go over how we can quickly combine data from different dataframes and get it ready for analysis. Let’s pretend that we’re analysts for a company that manufactures and sells paper clips. We need to run some reports on our firm’s sales department to see how they are doing and are given the data in the following dictionaries: import numpy as npimport pandas as pd# Dataframe of number of sales made by an employeesales = {'Tony': 103, 'Sally': 202, 'Randy': 380, 'Ellen': 101, 'Fred': 82 }# Dataframe of all employees and the region they work inregion = {'Tony': 'West', 'Sally': 'South', 'Carl': 'West', 'Archie': 'North', 'Randy': 'East', 'Ellen': 'South', 'Fred': np.nan, 'Mo': 'East', 'HanWei': np.nan, } We can create two separate dataframes from the dictionaries like so: # Make dataframessales_df = pd.DataFrame.from_dict(sales, orient='index', columns=['sales'])region_df = pd.DataFrame.from_dict(region, orient='index', columns=['region']) The dataframe, sales_df, now looks like this: salesTony 103Sally 202Randy 380Ellen 101Fred 82 And region_df looks like this: regionTony WestSally SouthCarl WestArchie NorthRandy EastEllen SouthFred NaNMo EastHanWei NaN Now let’s combine all of our data into a single dataframe. But how do we do that? Pandas dataframes have a lot of SQL like functionality. In fact I much prefer them to SQL tables (data analysts around the world are staring daggers at me). But when I first started doing a lot of SQL-like stuff with Pandas, I found myself perpetually unsure whether to use join or merge, and often I just used them interchangeably (picking whichever came to mind first). So when should we be using each of these methods, and how exactly are they different from each other? Well, it’s time to be confused no more! (If you are unfamiliar with what it means to join tables, I wrote this post about it, and I highly recommend that you read it first) Let’s start with join because it’s the simplest one. Dataframes have this thing called an index. It’s the key to your table and if we know the index, then we can easily grab the row that holds our data using .loc. If you print your dataframe, you can see what the index is by looking at the leftmost column, or we can be more direct and just use .index: In: sales_df.indexOut: Index(['Tony', 'Sally', 'Randy', 'Ellen', 'Fred'], dtype='object') So the index of sales_df is the name of our salespeople. By the way, unlike the primary key of a SQL table, a dataframe’s index does not have to be unique. But a unique index makes our lives easier and the time it takes to search our dataframe shorter, so it’s definitely a nice to have. Given an index, we can find the row data like so: In: sales_df.loc['Tony']Out: sales 103 Name: Tony, dtype: int64 OK, back to join. The join method takes two dataframes and joins them on their indexes (technically, you can pick the column to join on for the left dataframe). Let’s see what happens when we combine our two dataframes together via the join method: In: joined_df = region_df.join(sales_df, how='left') print(joined_df)Out: region salesTony West 103.0Sally South 202.0Carl West NaNArchie North NaNRandy East 380.0Ellen South 101.0Fred NaN 82.0Mo East NaNHanWei NaN NaN The result looks like the output of a SQL join, which it more or less is. The join method uses the index or a specified column from the dataframe that it’s called on, a.k.a. the left dataframe, as the join key. So the column that we match on for the left dataframe doesn’t have to be its index. But for the right dataframe, the join key must be its index. I personally find it easier to think of the join method as joining based on the index, and to use merge (coming up) if I don’t want to join on the indexes. In the combined dataframe there were some NaNs. That’s because not all of the employees had sales. The ones that did not have sales are not present in sales_df, but we still display them because we executed a left join (by specifying “how=left”), which returns all the rows from the left dataframe, region_df, regardless of whether there is a match. If we do not want to display any NaNs in our join result, we would do an inner join instead (by specifying “how=inner”). At a basic level, merge more or less does the same thing as join. Both methods are used to combine two dataframes together, but merge is more versatile at the cost of requiring more detailed inputs. Let’s take a look at how we can create the same combined dataframe with merge as we did with join: In: joined_df_merge = region_df.merge(sales_df, how='left', left_index=True, right_index=True) print(joined_df_merge)Out: region salesTony West 103.0Sally South 202.0Carl West NaNArchie North NaNRandy East 380.0Ellen South 101.0Fred NaN 82.0Mo East NaNHanWei NaN NaN Not that different from when we used join. But merge allows us to specify what columns to join on for both the left and right dataframes. Here by setting “left_index” and “right_index” equal to True, we let merge know that we want to join on the indexes. And we get the same combined dataframe as we obtained before when we used join. Merge is useful when we don’t want to join on the index. For example, let’s say we want to know, in percentage terms, how much each employee contributed to their region. We can use groupby to sum up all the sales within each unique region. In the code below, the reset_index is used to shift region from being the dataframe’s (grouped_df’s) index to being just a normal column — and yes, we could just keep it as the index and join on it, but I want to demonstrate how to use merge on columns. In: grouped_df = joined_df_merge.groupby(by='region').sum() grouped_df.reset_index(inplace=True) print(grouped_df)Out: region sales0 East 380.01 North 0.02 South 303.03 West 103.0 Now let’s merge joined_df_merge with grouped_df using the region column. We have to specify a suffix because both of our dataframes (that we are merging) contain a column called sales. The suffixes input appends the specified strings to the labels of columns that have identical names in both dataframes. In our case, since the second dataframe’s sales column is actually sales for the entire region, we can append “_region” to its label to make clear. In:employee_contrib = joined_df_merge.merge(grouped_df, how='left', left_on='region', right_on='region', suffixes=('','_region'))print(employee_contrib)Out: region sales sales_region0 West 103.0 103.01 South 202.0 303.02 West NaN 103.03 North NaN 0.04 East 380.0 380.05 South 101.0 303.06 NaN 82.0 NaN7 East NaN 380.08 NaN NaN NaN Oh no, our index disappeared! But we can use set_index to get it back (otherwise we won’t know which employee each row corresponds to): In:employee_contrib = employee_contrib.set_index(joined_df_merge.index)print(employee_contrib)Out: region sales sales_regionTony West 103.0 103.0Sally South 202.0 303.0Carl West NaN 103.0Archie North NaN 0.0Randy East 380.0 380.0Ellen South 101.0 303.0Fred NaN 82.0 NaNMo East NaN 380.0HanWei NaN NaN NaN We now have our original sales column and a new column sales_region that tells us the total sales made in a region. Let’s calculate each employees percentage of sales and then clean up our dataframe by dropping observations that have no region (Fred and HanWei) and filling the NaNs in the sales column with zeros:n In:# Drop NAs in region columnemployee_contrib = employee_contrib.dropna(subset=['region'])# Fill NAs in sales column with 0employee_contrib = employee_contrib.fillna({'sales': 0})employee_contrib['%_of_sales'] = employee_contrib['sales']/employee_contrib['sales_region']print(employee_contrib[['region','sales','%_of_sales']]\ .sort_values(by=['region','%_of_sales']))Out: region sales %_of_salesMo East 0.0 0.000000Randy East 380.0 1.000000Archie North 0.0 NaNEllen South 101.0 0.333333Sally South 202.0 0.666667Carl West 0.0 0.000000Tony West 103.0 1.000000 All done! Notice that the North region has no sales hence the NaN (can’t divide by zero). Let’s do a quick review: We can use join and merge to combine 2 dataframes. The join method works best when we are joining dataframes on their indexes (though you can specify another column to join on for the left dataframe). The merge method is more versatile and allows us to specify columns besides the index to join on for both dataframes. If the index gets reset to a counter post merge, we can use set_index to change it back. Next time, we will check out how to add new data rows via Pandas’ concatenate function (and much more). Cheers! If you liked this article and my writing in general, please consider supporting my writing by signing up for Medium via my referral link here. Thanks!
[ { "code": null, "e": 471, "s": 172, "text": "I write a lot about statistics and algorithms, but getting your data ready for modeling is a huge part of data science as well. In fact, it’s highly likely that you will spend significantly more time staring at your data, checking it, and fixing its holes than on training and tweaking your models." }, { "code": null, "e": 769, "s": 471, "text": "So the better we get at collecting, cleaning, and performing quick “sanity check” analyses on data, the more time we can spend on modeling (which most folks find more entertaining). To that end, let’s go over how we can quickly combine data from different dataframes and get it ready for analysis." }, { "code": null, "e": 997, "s": 769, "text": "Let’s pretend that we’re analysts for a company that manufactures and sells paper clips. We need to run some reports on our firm’s sales department to see how they are doing and are given the data in the following dictionaries:" }, { "code": null, "e": 1499, "s": 997, "text": "import numpy as npimport pandas as pd# Dataframe of number of sales made by an employeesales = {'Tony': 103, 'Sally': 202, 'Randy': 380, 'Ellen': 101, 'Fred': 82 }# Dataframe of all employees and the region they work inregion = {'Tony': 'West', 'Sally': 'South', 'Carl': 'West', 'Archie': 'North', 'Randy': 'East', 'Ellen': 'South', 'Fred': np.nan, 'Mo': 'East', 'HanWei': np.nan, }" }, { "code": null, "e": 1568, "s": 1499, "text": "We can create two separate dataframes from the dictionaries like so:" }, { "code": null, "e": 1808, "s": 1568, "text": "# Make dataframessales_df = pd.DataFrame.from_dict(sales, orient='index', columns=['sales'])region_df = pd.DataFrame.from_dict(region, orient='index', columns=['region'])" }, { "code": null, "e": 1854, "s": 1808, "text": "The dataframe, sales_df, now looks like this:" }, { "code": null, "e": 1920, "s": 1854, "text": "salesTony 103Sally 202Randy 380Ellen 101Fred 82" }, { "code": null, "e": 1951, "s": 1920, "text": "And region_df looks like this:" }, { "code": null, "e": 2082, "s": 1951, "text": " regionTony WestSally SouthCarl WestArchie NorthRandy EastEllen SouthFred NaNMo EastHanWei NaN" }, { "code": null, "e": 2164, "s": 2082, "text": "Now let’s combine all of our data into a single dataframe. But how do we do that?" }, { "code": null, "e": 2678, "s": 2164, "text": "Pandas dataframes have a lot of SQL like functionality. In fact I much prefer them to SQL tables (data analysts around the world are staring daggers at me). But when I first started doing a lot of SQL-like stuff with Pandas, I found myself perpetually unsure whether to use join or merge, and often I just used them interchangeably (picking whichever came to mind first). So when should we be using each of these methods, and how exactly are they different from each other? Well, it’s time to be confused no more!" }, { "code": null, "e": 2811, "s": 2678, "text": "(If you are unfamiliar with what it means to join tables, I wrote this post about it, and I highly recommend that you read it first)" }, { "code": null, "e": 3165, "s": 2811, "text": "Let’s start with join because it’s the simplest one. Dataframes have this thing called an index. It’s the key to your table and if we know the index, then we can easily grab the row that holds our data using .loc. If you print your dataframe, you can see what the index is by looking at the leftmost column, or we can be more direct and just use .index:" }, { "code": null, "e": 3267, "s": 3165, "text": "In: sales_df.indexOut: Index(['Tony', 'Sally', 'Randy', 'Ellen', 'Fred'], dtype='object')" }, { "code": null, "e": 3605, "s": 3267, "text": "So the index of sales_df is the name of our salespeople. By the way, unlike the primary key of a SQL table, a dataframe’s index does not have to be unique. But a unique index makes our lives easier and the time it takes to search our dataframe shorter, so it’s definitely a nice to have. Given an index, we can find the row data like so:" }, { "code": null, "e": 3677, "s": 3605, "text": "In: sales_df.loc['Tony']Out: sales 103 Name: Tony, dtype: int64" }, { "code": null, "e": 3926, "s": 3677, "text": "OK, back to join. The join method takes two dataframes and joins them on their indexes (technically, you can pick the column to join on for the left dataframe). Let’s see what happens when we combine our two dataframes together via the join method:" }, { "code": null, "e": 4206, "s": 3926, "text": "In: joined_df = region_df.join(sales_df, how='left') print(joined_df)Out: region salesTony West 103.0Sally South 202.0Carl West NaNArchie North NaNRandy East 380.0Ellen South 101.0Fred NaN 82.0Mo East NaNHanWei NaN NaN" }, { "code": null, "e": 4718, "s": 4206, "text": "The result looks like the output of a SQL join, which it more or less is. The join method uses the index or a specified column from the dataframe that it’s called on, a.k.a. the left dataframe, as the join key. So the column that we match on for the left dataframe doesn’t have to be its index. But for the right dataframe, the join key must be its index. I personally find it easier to think of the join method as joining based on the index, and to use merge (coming up) if I don’t want to join on the indexes." }, { "code": null, "e": 5189, "s": 4718, "text": "In the combined dataframe there were some NaNs. That’s because not all of the employees had sales. The ones that did not have sales are not present in sales_df, but we still display them because we executed a left join (by specifying “how=left”), which returns all the rows from the left dataframe, region_df, regardless of whether there is a match. If we do not want to display any NaNs in our join result, we would do an inner join instead (by specifying “how=inner”)." }, { "code": null, "e": 5487, "s": 5189, "text": "At a basic level, merge more or less does the same thing as join. Both methods are used to combine two dataframes together, but merge is more versatile at the cost of requiring more detailed inputs. Let’s take a look at how we can create the same combined dataframe with merge as we did with join:" }, { "code": null, "e": 5889, "s": 5487, "text": "In: joined_df_merge = region_df.merge(sales_df, how='left', left_index=True, right_index=True) print(joined_df_merge)Out: region salesTony West 103.0Sally South 202.0Carl West NaNArchie North NaNRandy East 380.0Ellen South 101.0Fred NaN 82.0Mo East NaNHanWei NaN NaN" }, { "code": null, "e": 6224, "s": 5889, "text": "Not that different from when we used join. But merge allows us to specify what columns to join on for both the left and right dataframes. Here by setting “left_index” and “right_index” equal to True, we let merge know that we want to join on the indexes. And we get the same combined dataframe as we obtained before when we used join." }, { "code": null, "e": 6718, "s": 6224, "text": "Merge is useful when we don’t want to join on the index. For example, let’s say we want to know, in percentage terms, how much each employee contributed to their region. We can use groupby to sum up all the sales within each unique region. In the code below, the reset_index is used to shift region from being the dataframe’s (grouped_df’s) index to being just a normal column — and yes, we could just keep it as the index and join on it, but I want to demonstrate how to use merge on columns." }, { "code": null, "e": 6921, "s": 6718, "text": "In: grouped_df = joined_df_merge.groupby(by='region').sum() grouped_df.reset_index(inplace=True) print(grouped_df)Out: region sales0 East 380.01 North 0.02 South 303.03 West 103.0" }, { "code": null, "e": 7374, "s": 6921, "text": "Now let’s merge joined_df_merge with grouped_df using the region column. We have to specify a suffix because both of our dataframes (that we are merging) contain a column called sales. The suffixes input appends the specified strings to the labels of columns that have identical names in both dataframes. In our case, since the second dataframe’s sales column is actually sales for the entire region, we can append “_region” to its label to make clear." }, { "code": null, "e": 7943, "s": 7374, "text": "In:employee_contrib = joined_df_merge.merge(grouped_df, how='left', left_on='region', right_on='region', suffixes=('','_region'))print(employee_contrib)Out: region sales sales_region0 West 103.0 103.01 South 202.0 303.02 West NaN 103.03 North NaN 0.04 East 380.0 380.05 South 101.0 303.06 NaN 82.0 NaN7 East NaN 380.08 NaN NaN NaN" }, { "code": null, "e": 8079, "s": 7943, "text": "Oh no, our index disappeared! But we can use set_index to get it back (otherwise we won’t know which employee each row corresponds to):" }, { "code": null, "e": 8518, "s": 8079, "text": "In:employee_contrib = employee_contrib.set_index(joined_df_merge.index)print(employee_contrib)Out: region sales sales_regionTony West 103.0 103.0Sally South 202.0 303.0Carl West NaN 103.0Archie North NaN 0.0Randy East 380.0 380.0Ellen South 101.0 303.0Fred NaN 82.0 NaNMo East NaN 380.0HanWei NaN NaN NaN" }, { "code": null, "e": 8834, "s": 8518, "text": "We now have our original sales column and a new column sales_region that tells us the total sales made in a region. Let’s calculate each employees percentage of sales and then clean up our dataframe by dropping observations that have no region (Fred and HanWei) and filling the NaNs in the sales column with zeros:n" }, { "code": null, "e": 9469, "s": 8834, "text": "In:# Drop NAs in region columnemployee_contrib = employee_contrib.dropna(subset=['region'])# Fill NAs in sales column with 0employee_contrib = employee_contrib.fillna({'sales': 0})employee_contrib['%_of_sales'] = employee_contrib['sales']/employee_contrib['sales_region']print(employee_contrib[['region','sales','%_of_sales']]\\ .sort_values(by=['region','%_of_sales']))Out: region sales %_of_salesMo East 0.0 0.000000Randy East 380.0 1.000000Archie North 0.0 NaNEllen South 101.0 0.333333Sally South 202.0 0.666667Carl West 0.0 0.000000Tony West 103.0 1.000000" }, { "code": null, "e": 9559, "s": 9469, "text": "All done! Notice that the North region has no sales hence the NaN (can’t divide by zero)." }, { "code": null, "e": 9584, "s": 9559, "text": "Let’s do a quick review:" }, { "code": null, "e": 9635, "s": 9584, "text": "We can use join and merge to combine 2 dataframes." }, { "code": null, "e": 9785, "s": 9635, "text": "The join method works best when we are joining dataframes on their indexes (though you can specify another column to join on for the left dataframe)." }, { "code": null, "e": 9992, "s": 9785, "text": "The merge method is more versatile and allows us to specify columns besides the index to join on for both dataframes. If the index gets reset to a counter post merge, we can use set_index to change it back." }, { "code": null, "e": 10104, "s": 9992, "text": "Next time, we will check out how to add new data rows via Pandas’ concatenate function (and much more). Cheers!" } ]
K-th Element of Two Sorted Arrays - GeeksforGeeks
25 Jan, 2022 Given two sorted arrays of size m and n respectively, you are tasked with finding the element that would be at the k’th position of the final sorted array. Examples: Input : Array 1 - 2 3 6 7 9 Array 2 - 1 4 8 10 k = 5 Output : 6 Explanation: The final sorted array would be - 1, 2, 3, 4, 6, 7, 8, 9, 10 The 5th element of this array is 6. Input : Array 1 - 100 112 256 349 770 Array 2 - 72 86 113 119 265 445 892 k = 7 Output : 256 Explanation: Final sorted array is - 72, 86, 100, 112, 113, 119, 256, 265, 349, 445, 770, 892 7th element of this array is 256. Basic Approach Since we are given two sorted arrays, we can use the merging technique to get the final merged array. From this, we simply go to the k’th index. C++ Java Python3 C# PHP Javascript // Program to find kth element from two sorted arrays#include <iostream>using namespace std; int kth(int arr1[], int arr2[], int m, int n, int k){ int sorted1[m + n]; int i = 0, j = 0, d = 0; while (i < m && j < n) { if (arr1[i] < arr2[j]) sorted1[d++] = arr1[i++]; else sorted1[d++] = arr2[j++]; } while (i < m) sorted1[d++] = arr1[i++]; while (j < n) sorted1[d++] = arr2[j++]; return sorted1[k - 1];} // Driver Codeint main(){ int arr1[5] = {2, 3, 6, 7, 9}; int arr2[4] = {1, 4, 8, 10}; int k = 5; cout << kth(arr1, arr2, 5, 4, k); return 0;} // Java Program to find kth element// from two sorted arrays class Main{ static int kth(int arr1[], int arr2[], int m, int n, int k) { int[] sorted1 = new int[m + n]; int i = 0, j = 0, d = 0; while (i < m && j < n) { if (arr1[i] < arr2[j]) sorted1[d++] = arr1[i++]; else sorted1[d++] = arr2[j++]; } while (i < m) sorted1[d++] = arr1[i++]; while (j < n) sorted1[d++] = arr2[j++]; return sorted1[k - 1]; } // Driver Code public static void main (String[] args) { int arr1[] = {2, 3, 6, 7, 9}; int arr2[] = {1, 4, 8, 10}; int k = 5; System.out.print(kth(arr1, arr2, 5, 4, k)); }} /* This code is contributed by Harsh Agarwal */ # Program to find kth element# from two sorted arrays def kth(arr1, arr2, m, n, k): sorted1 = [0] * (m + n) i = 0 j = 0 d = 0 while (i < m and j < n): if (arr1[i] < arr2[j]): sorted1[d] = arr1[i] i += 1 else: sorted1[d] = arr2[j] j += 1 d += 1 while (i < m): sorted1[d] = arr1[i] d += 1 i += 1 while (j < n): sorted1[d] = arr2[j] d += 1 j += 1 return sorted1[k - 1] # Driver codearr1 = [2, 3, 6, 7, 9]arr2 = [1, 4, 8, 10]k = 5print(kth(arr1, arr2, 5, 4, k)) # This code is contributed by Smitha Dinesh Semwal // C# Program to find kth element// from two sorted arraysclass GFG { static int kth(int[] arr1, int[] arr2, int m, int n, int k) { int[] sorted1 = new int[m + n]; int i = 0, j = 0, d = 0; while (i < m && j < n) { if (arr1[i] < arr2[j]) sorted1[d++] = arr1[i++]; else sorted1[d++] = arr2[j++]; } while (i < m) sorted1[d++] = arr1[i++]; while (j < n) sorted1[d++] = arr2[j++]; return sorted1[k - 1]; } // Driver Code static void Main() { int[] arr1 = { 2, 3, 6, 7, 9 }; int[] arr2 = { 1, 4, 8, 10 }; int k = 5; System.Console.WriteLine(kth(arr1, arr2, 5, 4, k)); }} // This code is contributed by mits <?php// Program to find kth// element from two// sorted arrays function kth($arr1, $arr2, $m, $n, $k){ $sorted1[$m + $n] = 0; $i = 0; $j = 0; $d = 0; while ($i < $m && $j < $n) { if ($arr1[$i] < $arr2[$j]) $sorted1[$d++] = $arr1[$i++]; else $sorted1[$d++] = $arr2[$j++]; } while ($i < $m) $sorted1[$d++] = $arr1[$i++]; while ($j < $n) $sorted1[$d++] = $arr2[$j++]; return $sorted1[$k - 1];} // Driver Code$arr1 = array(2, 3, 6, 7, 9);$arr2 = array(1, 4, 8, 10);$k = 5;echo kth($arr1, $arr2, 5, 4, $k); // This code is contributed// by ChitraNayal?> <script> // JavaScript Program to find kth element// from two sorted arrays function kth(arr1 , arr2 , m , n , k) { var sorted1 = Array(m + n).fill(0); var i = 0, j = 0, d = 0; while (i < m && j < n) { if (arr1[i] < arr2[j]) sorted1[d++] = arr1[i++]; else sorted1[d++] = arr2[j++]; } while (i < m) sorted1[d++] = arr1[i++]; while (j < n) sorted1[d++] = arr2[j++]; return sorted1[k - 1]; } // Driver Code var arr1 = [ 2, 3, 6, 7, 9 ]; var arr2 = [ 1, 4, 8, 10 ]; var k = 5; document.write(kth(arr1, arr2, 5, 4, k)); // This code contributed by umadevi9616 </script> 6 Time Complexity: O(n) Auxiliary Space : O(m + n) Space Optimized Version of above approach: We can avoid the use of extra array. C++ Java Python3 C# Javascript // C++ program to find kth element// from two sorted arrays#include <bits/stdc++.h>using namespace std; int find(int A[], int B[], int m, int n, int k_req){ int k = 0, i = 0, j = 0; // Keep taking smaller of the current // elements of two sorted arrays and // keep incrementing k while(i < m && j < n) { if(A[i] < B[j]) { k++; if(k == k_req) return A[i]; i++; } else { k++; if(k == k_req) return B[j]; j++; } } // If array B[] is completely traversed while(i < m) { k++; if(k == k_req) return A[i]; i++; } // If array A[] is completely traversed while(j < n) { k++; if(k == k_req) return B[j]; j++; }} // Driver Codeint main(){ int A[5] = { 2, 3, 6, 7, 9 }; int B[4] = { 1, 4, 8, 10 }; int k = 5; cout << find(A, B, 5, 4, k); return 0;} // This code is contributed by Sreejith S import java.io.*; class GFG { public static int find(int A[], int B[], int m, int n, int k_req) { int k = 0, i = 0, j = 0; // Keep taking smaller of the current // elements of two sorted arrays and // keep incrementing k while (i < m && j < n) { if (A[i] < B[j]) { k++; if (k == k_req) return A[i]; i++; } else { k++; if (k == k_req) return B[j]; j++; } } // If array B[] is completely traversed while (i < m) { k++; if (k == k_req) return A[i]; i++; } // If array A[] is completely traversed while (j < n) { k++; if (k == k_req) return B[j]; j++; } return -1; } // Driver Code public static void main(String[] args) { int[] A = { 2, 3, 6, 7, 9 }; int[] B = { 1, 4, 8, 10 }; int k = 5; System.out.println(find(A, B, 5, 4, k)); }} # Python3 Program to find kth element# from two sorted arrays def find(A, B, m, n, k_req): i, j, k = 0, 0, 0 # Keep taking smaller of the current # elements of two sorted arrays and # keep incrementing k while i < len(A) and j < len(B): if A[i] < B[j]: k += 1 if k == k_req: return A[i] i += 1 else: k += 1 if k == k_req: return B[j] j += 1 # If array B[] is completely traversed while i < len(A): k += 1 if k == k_req: return A[i] i += 1 # If array A[] is completely traversed while j < len(B): k += 1 if k == k_req: return B[j] j += 1 # driver codeA = [2, 3, 6, 7, 9]B = [1, 4, 8, 10]k = 5;print(find(A, B, 5, 4, k))# time complexity of O(k) // C# program to find kth element// from two sorted arraysusing System;public class GFG{ public static int find(int[] A, int[] B, int m, int n,int k_req) { int k = 0, i = 0, j = 0; // Keep taking smaller of the current // elements of two sorted arrays and // keep incrementing k while (i < m && j < n) { if (A[i] < B[j]) { k++; if (k == k_req) return A[i]; i++; } else { k++; if (k == k_req) return B[j]; j++; } } // If array B[] is completely traversed while (i < m) { k++; if (k == k_req) return A[i]; i++; } // If array A[] is completely traversed while (j < n) { k++; if (k == k_req) return B[j]; j++; } return -1; } // Driver Code static public void Main (){ int[] A = { 2, 3, 6, 7, 9 }; int[] B = { 1, 4, 8, 10 }; int k = 5; Console.WriteLine(find(A, B, 5, 4, k)); }} // This code is contributed by rag2127 <script> function find(A, B, m, n, k_req) { let k = 0, i = 0, j = 0; // Keep taking smaller of the current // elements of two sorted arrays and // keep incrementing k while (i < m && j < n) { if (A[i] < B[j]) { k++; if (k == k_req) return A[i]; i++; } else { k++; if (k == k_req) return B[j]; j++; } } // If array B[] is completely traversed while (i < m) { k++; if (k == k_req) return A[i]; i++; } // If array A[] is completely traversed while (j < n) { k++; if (k == k_req) return B[j]; j++; } return -1; } // Driver Code let A = [ 2, 3, 6, 7, 9 ]; let B = [ 1, 4, 8, 10 ]; let k = 5; document.write(find(A, B, 5, 4, k)); // This code is contributed by Dharanendra L V. </script> 6 Time Complexity: O(k) Auxiliary Space: O(1) Divide And Conquer Approach 1 While the previous method works, can we make our algorithm more efficient? The answer is yes. By using a divide and conquer approach, similar to the one used in binary search, we can attempt to find the k’th element in a more efficient way.Compare the middle elements of arrays arr1 and arr2, let us call these indices mid1 and mid2 respectively. Let us assume arr1[mid1] k, then clearly the elements after mid2 cannot be the required element. Set the last element of arr2 to be arr2[mid2].In this way, define a new subproblem with half the size of one of the arrays. Divide And Conquer Approach 1 While the previous method works, can we make our algorithm more efficient? The answer is yes. By using a divide and conquer approach, similar to the one used in binary search, we can attempt to find the k’th element in a more efficient way. Compare the middle elements of arrays arr1 and arr2, let us call these indices mid1 and mid2 respectively. Let us assume arr1[mid1] k, then clearly the elements after mid2 cannot be the required element. Set the last element of arr2 to be arr2[mid2]. In this way, define a new subproblem with half the size of one of the arrays. C++ Python3 // Program to find k-th element from two sorted arrays#include <iostream>using namespace std; int kth(int *arr1, int *arr2, int *end1, int *end2, int k){ if (arr1 == end1) return arr2[k]; if (arr2 == end2) return arr1[k]; int mid1 = (end1 - arr1) / 2; int mid2 = (end2 - arr2) / 2; if (mid1 + mid2 < k) { if (arr1[mid1] > arr2[mid2]) return kth(arr1, arr2 + mid2 + 1, end1, end2, k - mid2 - 1); else return kth(arr1 + mid1 + 1, arr2, end1, end2, k - mid1 - 1); } else { if (arr1[mid1] > arr2[mid2]) return kth(arr1, arr2, arr1 + mid1, end2, k); else return kth(arr1, arr2, end1, arr2 + mid2, k); }} int main(){ int arr1[5] = {2, 3, 6, 7, 9}; int arr2[4] = {1, 4, 8, 10}; int k = 5; cout << kth(arr1, arr2, arr1 + 5, arr2 + 4, k - 1); return 0;} # Python program to find k-th element from two sorted arraysdef kth(arr1, arr2, n, m, k): if n == 1 or m == 1: if m == 1: arr2, arr1 = arr1, arr2 m = n if k == 1: return min(arr1[0], arr2[0]) elif k == m + 1: return max(arr1[0], arr2[0]) else: if arr2[k - 1] < arr1[0]: return arr2[k - 1] else: return max(arr1[0], arr2[k - 2]) mid1 = (n - 1)//2 mid2 = (m - 1)//2 if mid1+mid2+1 < k: if arr1[mid1] < arr2[mid2]: return kth(arr1[mid1 + 1:], arr2, n - mid1 - 1, m, k - mid1 - 1) else: return kth(arr1, arr2[mid2 + 1:], n, m - mid2 - 1, k - mid2 - 1) else: if arr1[mid1] < arr2[mid2]: return kth(arr1, arr2[:mid2 + 1], n, mid2 + 1, k) else: return kth(arr1[:mid1 + 1], arr2, mid1 + 1, m, k) if __name__ == "__main__": arr1 = [2, 3, 6, 7, 9] arr2 = [1, 4, 8, 10] k = 5 print(kth(arr1, arr2, 5, 4, k)) # This code is contributed by harshitkap00r 6 Note that in the above code, k is 0 indexed, which means if we want a k that’s 1 indexed, we have to subtract 1 when passing it to the function. Time Complexity: O(log n + log m) Divide And Conquer Approach 2 While the above implementation is very efficient, we can still get away with making it more efficient. Instead of dividing the array into segments of n / 2 and m / 2 then recursing, we can divide them both by k / 2 and recurse. The below implementation displays this. Explanation: Instead of comparing the middle element of the arrays, we compare the k / 2nd element. Let arr1 and arr2 be the arrays. Now, if arr1[k / 2] arr1[1] New subproblem: Array 1 - 6 7 9 Array 2 - 1 4 8 10 k = 5 - 2 = 3 floor(k / 2) = 1 arr1[1] = 6 arr2[1] = 1 arr1[1] > arr2[1] New subproblem: Array 1 - 6 7 9 Array 2 - 4 8 10 k = 3 - 1 = 2 floor(k / 2) = 1 arr1[1] = 6 arr2[1] = 4 arr1[1] > arr2[1] New subproblem: Array 1 - 6 7 9 Array 2 - 8 10 k = 2 - 1 = 1 Now, we directly compare first elements, since k = 1. arr1[1] < arr2[1] Hence, arr1[1] = 6 is the answer. C++ Java Python3 C# Javascript // C++ Program to find kth element from two sorted arrays#include <iostream>using namespace std; int kth(int arr1[], int arr2[], int m, int n, int k, int st1 = 0, int st2 = 0){ // In case we have reached end of array 1 if (st1 == m) return arr2[st2 + k - 1]; // In case we have reached end of array 2 if (st2 == n) return arr1[st1 + k - 1]; // k should never reach 0 or exceed sizes // of arrays if (k == 0 || k > (m - st1) + (n - st2)) return -1; // Compare first elements of arrays and return if (k == 1) return (arr1[st1] < arr2[st2]) ? arr1[st1] : arr2[st2]; int curr = k / 2; // Size of array 1 is less than k / 2 if (curr - 1 >= m - st1) { // Last element of array 1 is not kth // We can directly return the (k - m)th // element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]) return arr2[st2 + (k - (m - st1) - 1)]; else return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } // Size of array 2 is less than k / 2 if (curr-1 >= n-st2) { if (arr2[n - 1] < arr1[st1 + curr - 1]) return arr1[st1 + (k - (n - st2) - 1)]; else return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } else { // Normal comparison, move starting index // of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]) return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); else return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); }} // Driver codeint main(){ int arr1[5] = {2, 3, 6, 7, 9}; int arr2[4] = {1, 4, 8, 10}; int k = 5; cout << kth(arr1, arr2, 5, 4, k); return 0;} // Java Program to find kth element from two sorted arraysclass GFG{ static int kth(int arr1[], int arr2[], int m, int n, int k, int st1, int st2) { // In case we have reached end of array 1 if (st1 == m) { return arr2[st2 + k - 1]; } // In case we have reached end of array 2 if (st2 == n) { return arr1[st1 + k - 1]; } // k should never reach 0 or exceed sizes // of arrays if (k == 0 || k > (m - st1) + (n - st2)) { return -1; } // Compare first elements of arrays and return if (k == 1) { return (arr1[st1] < arr2[st2]) ? arr1[st1] : arr2[st2]; } int curr = k / 2; // Size of array 1 is less than k / 2 if (curr - 1 >= m - st1) { // Last element of array 1 is not kth // We can directly return the (k - m)th // element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]) { return arr2[st2 + (k - (m - st1) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Size of array 2 is less than k / 2 if (curr - 1 >= n - st2) { if (arr2[n - 1] < arr1[st1 + curr - 1]) { return arr1[st1 + (k - (n - st2) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } } else // Normal comparison, move starting index // of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]) { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Driver code public static void main(String[] args) { int arr1[] = {2, 3, 6, 7, 9}; int arr2[] = {1, 4, 8, 10}; int k = 5; int st1 = 0, st2 = 0; System.out.println(kth(arr1, arr2, 5, 4, k, st1, st2)); }} // This code is contributed by 29AjayKumar # Python3 program to find kth element from# two sorted arraysdef kth(arr1, arr2, m, n, k, st1 = 0, st2 = 0): # In case we have reached end of array 1 if (st1 == m): return arr2[st2 + k - 1] # In case we have reached end of array 2 if (st2 == n): return arr1[st1 + k - 1] # k should never reach 0 or exceed sizes # of arrays if (k == 0 or k > (m - st1) + (n - st2)): return -1 # Compare first elements of arrays and return if (k == 1): if(arr1[st1] < arr2[st2]): return arr1[st1] else: return arr2[st2] curr = int(k / 2) # Size of array 1 is less than k / 2 if(curr - 1 >= m - st1): # Last element of array 1 is not kth # We can directly return the (k - m)th # element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]): return arr2[st2 + (k - (m - st1) - 1)] else: return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr) # Size of array 2 is less than k / 2 if (curr - 1 >= n - st2): if (arr2[n - 1] < arr1[st1 + curr - 1]): return arr1[st1 + (k - (n - st2) - 1)] else: return kth(arr1, arr2, m, n, k - curr,st1 + curr, st2) else: # Normal comparison, move starting index # of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]): return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2) else: return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr) # Driver codearr1 = [ 2, 3, 6, 7, 9 ]arr2 = [ 1, 4, 8, 10 ]k = 5 print(kth(arr1, arr2, 5, 4, k)) # This code is contributed by avanitrachhadiya2155 // C# Program to find kth element from two sorted arraysusing System; class GFG{ static int kth(int []arr1, int []arr2, int m, int n, int k, int st1, int st2) { // In case we have reached end of array 1 if (st1 == m) { return arr2[st2 + k - 1]; } // In case we have reached end of array 2 if (st2 == n) { return arr1[st1 + k - 1]; } // k should never reach 0 or exceed sizes // of arrays if (k == 0 || k > (m - st1) + (n - st2)) { return -1; } // Compare first elements of arrays and return if (k == 1) { return (arr1[st1] < arr2[st2]) ? arr1[st1] : arr2[st2]; } int curr = k / 2; // Size of array 1 is less than k / 2 if (curr - 1 >= m - st1) { // Last element of array 1 is not kth // We can directly return the (k - m)th // element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]) { return arr2[st2 + (k - (m - st1) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Size of array 2 is less than k / 2 if (curr - 1 >= n - st2) { if (arr2[n - 1] < arr1[st1 + curr - 1]) { return arr1[st1 + (k - (n - st2) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } } else // Normal comparison, move starting index // of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]) { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Driver code public static void Main(String[] args) { int []arr1 = {2, 3, 6, 7, 9}; int []arr2 = {1, 4, 8, 10}; int k = 5; int st1 = 0, st2 = 0; Console.WriteLine(kth(arr1, arr2, 5, 4, k, st1, st2)); }} // This code is contributed by PrinciRaj1992 <script>// javascript Program to find kth element from two sorted arrays function kth(arr1 , arr2 , m , n , k , st1 , st2){ // In case we have reached end of array 1 if (st1 == m) { return arr2[st2 + k - 1]; } // In case we have reached end of array 2 if (st2 == n) { return arr1[st1 + k - 1]; } // k should never reach 0 or exceed sizes // of arrays if (k == 0 || k > (m - st1) + (n - st2)) { return -1; } // Compare first elements of arrays and return if (k == 1) { return (arr1[st1] < arr2[st2]) ? arr1[st1] : arr2[st2]; } var curr = parseInt(k / 2); // Size of array 1 is less than k / 2 if (curr - 1 >= m - st1) { // Last element of array 1 is not kth // We can directly return the (k - m)th // element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]) { return arr2[st2 + (k - (m - st1) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Size of array 2 is less than k / 2 if (curr - 1 >= n - st2) { if (arr2[n - 1] < arr1[st1 + curr - 1]) { return arr1[st1 + (k - (n - st2) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } } else // Normal comparison, move starting index // of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]) { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Driver code var arr1 = [ 2, 3, 6, 7, 9 ]; var arr2 = [ 1, 4, 8, 10 ]; var k = 5; var st1 = 0, st2 = 0; document.write(kth(arr1, arr2, 5, 4, k, st1, st2)); // This code is contributed by gauravrajput1</script> 6 Time Complexity: O(log k) Now, k can take a maximum value of m + n. This means that log k can be in the worst case, log(m + n). Logm + logn = log(mn) by properties of logarithms, and when m, n > 2, log(m + n) < log(mn). Thus this algorithm slightly outperforms the previous algorithm. Also, see another simple implemented log k approach suggested by Raj Kumar. C++ Java Python3 C# Javascript // C++ Program to find kth// element from two sorted arrays// Time Complexity: O(log k) #include <iostream>using namespace std; int kth(int arr1[], int m, int arr2[], int n, int k){ if (k > (m + n) || k < 1) return -1; // let m <= n if (m > n) return kth(arr2, n, arr1, m, k); // Check if arr1 is empty returning // k-th element of arr2 if (m == 0) return arr2[k - 1]; // Check if k = 1 return minimum of // first two elements of both // arrays if (k == 1) return min(arr1[0], arr2[0]); // Now the divide and conquer part int i = min(m, k / 2), j = min(n, k / 2); if (arr1[i - 1] > arr2[j - 1]) // Now we need to find only // k-j th element since we // have found out the lowest j return kth(arr1, m, arr2 + j, n - j, k - j); else // Now we need to find only // k-i th element since we // have found out the lowest i return kth(arr1 + i, m - i, arr2, n, k - i);} // Driver codeint main(){ int arr1[5] = { 2, 3, 6, 7, 9 }; int arr2[4] = { 1, 4, 8, 10 }; int m = sizeof(arr1) / sizeof(arr1[0]); int n = sizeof(arr2) / sizeof(arr2[0]); int k = 5; int ans = kth(arr1, m, arr2, n, k); if (ans == -1) cout << "Invalid query"; else cout << ans; return 0;}// This code is contributed by Raj Kumar // Java Program to find kth element// from two sorted arrays// Time Complexity: O(log k)import java.util.Arrays; class Gfg { static int kth(int arr1[], int m, int arr2[], int n, int k) { if (k > (m + n) || k < 1) return -1; // let m > n if (m > n) return kth(arr2, n, arr1, m, k); // Check if arr1 is empty returning // k-th element of arr2 if (m == 0) return arr2[k - 1]; // Check if k = 1 return minimum of first // two elements of both arrays if (k == 1) return Math.min(arr1[0], arr2[0]); // Now the divide and conquer part int i = Math.min(m, k / 2); int j = Math.min(n, k / 2); if (arr1[i - 1] > arr2[j - 1]) { // Now we need to find only k-j th element // since we have found out the lowest j int temp[] = Arrays.copyOfRange(arr2, j, n); return kth(arr1, m, temp, n - j, k - j); } // Now we need to find only k-i th element // since we have found out the lowest i int temp[] = Arrays.copyOfRange(arr1, i, m); return kth(temp, m - i, arr2, n, k - i); } // Driver code public static void main(String[] args) { int arr1[] = { 2, 3, 6, 7, 9 }; int arr2[] = { 1, 4, 8, 10 }; int m = arr1.length; int n = arr2.length; int k = 5; int ans = kth(arr1, m, arr2, n, k); if (ans == -1) System.out.println("Invalid query"); else System.out.println(ans); }} // This code is contributed by Vivek Kumar Singh # Python3 Program to find kth element from two# sorted arrays. Time Complexity: O(log k)def kth(arr1, m, arr2, n, k): if (k > (m + n) or k < 1): return -1 # Let m <= n if (m > n): return kth(arr2, n, arr1, m, k) # Check if arr1 is empty returning # k-th element of arr2 if (m == 0): return arr2[k - 1] # Check if k = 1 return minimum of # first two elements of both # arrays if (k == 1): return min(arr1[0], arr2[0]) # Now the divide and conquer part i = min(m, k // 2) j = min(n, k // 2) if (arr1[i - 1] > arr2[j - 1]): # Now we need to find only # k-j th element since we # have found out the lowest j return kth(arr1, m, arr2[j:], n - j, k - j) else: # Now we need to find only # k-i th element since we # have found out the lowest i return kth(arr1[i:], m - i, arr2, n, k - i) # Driver codearr1 = [ 2, 3, 6, 7, 9 ]arr2 = [ 1, 4, 8, 10 ]m = len(arr1)n = len(arr2)k = 5 ans = kth(arr1, m, arr2, n, k) if (ans == -1): print("Invalid query")else: print(ans) # This code is contributed by Shubham Singh // C# Program to find kth element// from two sorted arrays// Time Complexity: O(log k)using System;using System.Collections.Generic; public class GFG{ static int kth(int[] arr1, int m, int[] arr2, int n, int k) { if (k > (m + n) || k < 1) return -1; // let m > n if (m > n) return kth(arr2, n, arr1, m, k); // Check if arr1 is empty returning // k-th element of arr2 if (m == 0) return arr2[k - 1]; // Check if k = 1 return minimum of first // two elements of both arrays if (k == 1) return Math.Min(arr1[0], arr2[0]); // Now the divide and conquer part int i = Math.Min(m, k / 2); int j = Math.Min(n, k / 2); if (arr1[i - 1] > arr2[j - 1]) { // Now we need to find only k-j th element // since we have found out the lowest j int[] temp = new int[n - j]; Array.Copy(arr2, j, temp, 0, n-j); return kth(arr1, m, temp, n - j, k - j); } // Now we need to find only k-i th element // since we have found out the lowest i int[] temp1 = new int[m-i]; Array.Copy(arr1, i, temp1, 0, m-i); return kth(temp1, m - i, arr2, n, k - i); } // Driver code public static void Main() { int[] arr1 = { 2, 3, 6, 7, 9 }; int[] arr2 = { 1, 4, 8, 10 }; int m = arr1.Length; int n = arr2.Length; int k = 5; int ans = kth(arr1, m, arr2, n, k); if (ans == -1) Console.WriteLine("Invalid query"); else Console.WriteLine(ans); }} // This code is contributed by Shubham Singh <script>// Javascript program to illustrate time// complexity for Nested loops function kth(arr1, m, arr2, n, k){ if (k > (m + n) || k < 1){ return -1; } // let m <= n if (m > n){ return kth(arr2, n, arr1, m, k); } // Check if arr1 is empty returning // k-th element of arr2 if (m == 0){ return arr2[k - 1]; } // Check if k = 1 return minimum of // first two elements of both // arrays if (k == 1){ return Math.min(arr1[0], arr2[0]); } // Now the divide and conquer part let i = Math.min(m, parseInt(k / 2)); let j = Math.min(n, parseInt(k / 2)); if (arr1[i - 1] > arr2[j - 1]){ // Now we need to find only // k-j th element since we // have found out the lowest j let temp = arr2.slice(j,n) return kth(arr1, m, temp, n - j, k - j); } else{ // Now we need to find only // k-i th element since we // have found out the lowest i let temp = arr1.slice(i,m) return kth( temp, m - i, arr2, n, k - i); }} // Driver code let arr1 = [ 2, 3, 6, 7, 9 ];let arr2 = [ 1, 4, 8, 10 ];let m = 5;let n = 4;let k = 5; let ans = kth(arr1, m, arr2, n, k); if (ans == -1){ document.write("Invalid query");}else{ document.write(ans);} // This code is contributed by Shubham Singh</script> 6 Time Complexity:O(log k) Another Approach: (Using Min Heap) Push the elements of both arrays to a priority queue (min-heap).Pop-out k-1 elements from the front.Element at the front of the priority queue is the required answer. Push the elements of both arrays to a priority queue (min-heap). Pop-out k-1 elements from the front. Element at the front of the priority queue is the required answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to find kth// element from two sorted arrays#include <bits/stdc++.h>using namespace std; // Function to find K-th minint kth(int* a, int* b, int n, int m, int k){ // Declaring a min heap priority_queue<int, vector<int>, greater<int> > pq; // Pushing elements for // array a to min-heap for (int i = 0; i < n; i++) { pq.push(a[i]); } // Pushing elements for // array b to min-heap for (int i = 0; i < m; i++) { pq.push(b[i]); } // Popping-out K-1 elements while (k-- > 1) { pq.pop(); } return pq.top();} //Driver Codeint main(){ int arr1[5] = {2, 3, 6, 7, 9}; int arr2[4] = {1, 4, 8, 10}; int k = 5; cout << kth(arr1, arr2, 5, 4, k); return 0;} // This code is contributed by yashbeersingh42 // Java Program to find kth element// from two sorted arraysimport java.util.*; class GFG { // Function to find K-th min static int kth(int a[], int b[], int n, int m, int k) { // Declaring a min heap PriorityQueue<Integer> pq = new PriorityQueue<>(); // Pushing elements for // array a to min-heap for (int i = 0; i < n; i++) { pq.offer(a[i]); } // Pushing elements for // array b to min-heap for (int i = 0; i < m; i++) { pq.offer(b[i]); } // Popping-out K-1 elements while (k-- > 1) { pq.remove(); } return pq.peek(); } // Driver Code public static void main(String[] args) { int arr1[] = { 2, 3, 6, 7, 9 }; int arr2[] = { 1, 4, 8, 10 }; int k = 5; System.out.print(kth(arr1, arr2, 5, 4, k)); }} // This code is contributed by yashbeersingh42 # Python Program to find kth element# from two sorted arrays # Function to find K-th mindef kth(a , b , n , m , k): # Declaring a min heap pq = []; # Pushing elements for # array a to min-heap for i in range(n): pq.append(a[i]); # Pushing elements for # array b to min-heap for i in range(m): pq.append(b[i]); pq = sorted(pq, reverse = True) # Popping-out K-1 elements while (k > 1): k -= 1; pq.pop(); return pq.pop(); # Driver Codearr1 = [ 2, 3, 6, 7, 9 ];arr2 = [ 1, 4, 8, 10 ];k = 5;print(kth(arr1, arr2, 5, 4, k)); # This code is contributed by Saurabh Jaiswal // C# Program to find kth element// from two sorted arraysusing System;using System.Collections.Generic; public class GFG { // Function to find K-th min static int kth(int []a, int []b, int n, int m, int k) { // Declaring a min heap List<int> pq = new List<int>(); // Pushing elements for // array a to min-heap for (int i = 0; i < n; i++) { pq.Add(a[i]); } // Pushing elements for // array b to min-heap for (int i = 0; i < m; i++) { pq.Add(b[i]); } pq.Sort(); // Popping-out K-1 elements while (k-- > 1) { pq.RemoveAt(0); } return pq[0]; } // Driver Code public static void Main(String[] args) { int []arr1 = { 2, 3, 6, 7, 9 }; int []arr2 = { 1, 4, 8, 10 }; int k = 5; Console.Write(kth(arr1, arr2, 5, 4, k)); }} // This code is contributed by gauravrajput1 <script>// javascript Program to find kth element// from two sorted arrays // Function to find K-th min function kth(a , b , n , m , k) { // Declaring a min heap var pq = []; // Pushing elements for // array a to min-heap for (i = 0; i < n; i++) { pq.push(a[i]); } // Pushing elements for // array b to min-heap for (i = 0; i < m; i++) { pq.push(b[i]); } pq.sort((a,b)=>b-a); // Popping-out K-1 elements while (k-- > 1) { pq.pop(); } return pq.pop(); } // Driver Code var arr1 = [ 2, 3, 6, 7, 9 ]; var arr2 = [ 1, 4, 8, 10 ]; var k = 5; document.write(kth(arr1, arr2, 5, 4, k)); // This code is contributed by gauravrajput1</script> 6 Time Complexity: O(NlogN) Space Complexity: O(m+n) Another Approach : (Using Upper Bound STL) Given two sorted arrays of size m and n respectively, you are tasked with finding the element that would be at the k’th position of the final sorted array. Examples : Input : Array 1 – 2 3 6 7 9 Array 2 – 1 4 8 10 k = 5 Output : 6 Explanation: The final sorted array would be – 1, 2, 3, 4, 6, 7, 8, 9, 10 The 5th element of this array is 6, The 1st element of this array is 1. The thing to notice here is upper_bound(6) gives 5, upper_bound(4) gives 4 that is number of element equal to or less than the number we are giving as input to upper_bound(). Here is another example Input : Array 1 – 100 112 256 349 770 Array 2 – 72 86 113 119 265 445 892 k = 7 Output : 256 Explanation: Final sorted array is – 72, 86, 100, 112, 113, 119, 256, 265, 349, 445, 770, 892 7th element of this array is 256. Observation required : The simplest method to solve this question is using upper_bound to check what is the position of a element in the sorted array. The upper_bound function return the pointer to element which is greater than the element we searched. So to find the kth element we need to just find the element whose upper_bound() is 4. So again now we now what upper_bound() gives us we need 1 last observation to solve this question. If we have been given 2 arrays, We just need to the sum of upper_bound for the 2 arrays Input : Array 1 – 2 3 6 7 9 Array 2 – 1 4 8 10 k = 5 Value of upper_bound for value(6) in array1 is 3 and for array 2 is 2. This give us a total of 5. which is the answer. Algorithm : We take a mid between [L,R] using the formula mid = (L+R)/2. Check if the middle can be the kth element using upper_bound() function Find the sum of upper_bound() for both the arrays and if the sum is >= K, It’s a possible value of kth element. If sum is >= K then we assign R = mid – 1. else if sum <k then the current mid is too small and we assign L = mid+1. Repeat from top Return the smallest value found. Here is the implementation for the optimized method : C++ Java Python3 C# Javascript // C++ program to find the kth element#include <bits/stdc++.h>using namespace std; long long int maxN = 1e10; // the maximum value in the array possible. long long int kthElement(int arr1[], int arr2[], int n, int m, int k){ long long int left = 1, right = maxN; // The range of where ans can lie. long long int ans = 1e15; // We have to find min of all // the ans so take . // using binary search to check all possible values of // kth element while (left <= right) { long long int mid = (left + right) / 2; long long int up_cnt = upper_bound(arr1, arr1 + n, mid) - arr1; up_cnt += upper_bound(arr2, arr2 + m, mid) - arr2; if (up_cnt >= k) { ans = min(ans, mid); // find the min of all answers. right = mid - 1; // Try to find a smaller answer. } else left = mid + 1; // Current mid is too small so // shift right. } return ans;} // Driver codeint main(){ // Example 1 int n = 5, m = 7, k = 7; int arr1[n] = { 100, 112, 256, 349, 770 }; int arr2[m] = { 72, 86, 113, 119, 265, 445, 892 }; cout << kthElement(arr1, arr2, n, m, k) << endl; return 0;} // Java program to find the kth elementimport java.util.*;class GFG{ static long maxN = (long)1e10; // the maximum value in the array possible. static int upperBound(int[] a, int low, int high, long element){ while(low < high){ int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} static long kthElement(int arr1[], int arr2[], int n, int m, int k){ long left = 1, right = maxN; // The range of where ans can lie. long ans = (long)1e15; // We have to find min of all // the ans so take . // using binary search to check all possible values of // kth element while (left <= right) { long mid = (left + right) / 2; long up_cnt = upperBound(arr1,0, n, mid); up_cnt += upperBound(arr2, 0, m, mid); if (up_cnt >= k) { ans = Math.min(ans, mid); // find the min of all answers. right = mid - 1; // Try to find a smaller answer. } else left = mid + 1; // Current mid is too small so // shift right. } return ans;} // Driver codepublic static void main(String[] args){ // Example 1 int n = 5, m = 7, k = 7; int arr1[] = { 100, 112, 256, 349, 770 }; int arr2[] = { 72, 86, 113, 119, 265, 445, 892 }; System.out.print(kthElement(arr1, arr2, n, m, k) +"\n");}} // This code is contributed by gauravrajput1 # Python program to find the kth elementmaxN = 10**10 # the maximum value in the array possible. def upperBound(a, low, high, element): while(low < high): middle = low + (high - low)//2 if(a[middle] > element): high = middle else: low = middle + 1 return low def kthElement(arr1, arr2, n, m, k): left = 1 right = maxN # The range of where ans can lie. ans = 10**15 # We have to find min of all # the ans so take . # using binary search to check all possible values of # kth element while (left <= right): mid = (left + right) // 2 up_cnt = upperBound(arr1,0, n, mid) up_cnt += upperBound(arr2, 0, m, mid) if (up_cnt >= k): ans = min(ans, mid) # find the min of all answers. right= mid - 1 # Try to find a smaller answer. else: left = mid + 1 # Current mid is too small so # shift right. return ans # Driver code# Example 1n = 5m = 7k = 7arr1 = [100, 112, 256, 349, 770]arr2 = [72, 86, 113, 119, 265, 445, 892]print(kthElement(arr1, arr2, n, m, k)) # This code is contributed by Shubham Singh // C# program to find the kth element using System; public class GFG{ static long maxN = (long)1e10; // the maximum value in the array possible. static int upperBound(int[] a, int low, int high, long element) { while(low < high){ int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low; } static long kthElement(int[] arr1, int[] arr2, int n, int m, int k) { long left = 1, right = maxN; // The range of where ans can lie. long ans = (long)1e15; // We have to find min of all // the ans so take . // using binary search to check all possible values of // kth element while (left <= right) { long mid = (left + right) / 2; long up_cnt = upperBound(arr1,0, n, mid); up_cnt += upperBound(arr2, 0, m, mid); if (up_cnt >= k) { ans = Math.Min(ans, mid); // find the min of all answers. right = mid - 1; // Try to find a smaller answer. } else left = mid + 1; // Current mid is too small so // shift right. } return ans; } // Driver code static public void Main (){ // Example 1 int n = 5, m = 7, k = 7; int[] arr1 = { 100, 112, 256, 349, 770 }; int[] arr2 = { 72, 86, 113, 119, 265, 445, 892 }; Console.Write(kthElement(arr1, arr2, n, m, k) +"\n"); }} // This code is contributed by SHubham Singh <script>// Javascript program to find the kth elementvar maxN = 10000000000; // the maximum value in the array possible. function upperBound(a, low, high, element){ while(low < high){ var middle = parseInt(low + (high - low)/2); if(a[middle] > element) high = middle; else low = middle + 1; } return low;} function kthElement(arr1, arr2, n, m, k){ var left = 1 var right = maxN; // The range of where ans can lie. var ans = 1000000000000000; // We have to find min of all // the ans so take . // using binary search to check all possible values of // kth element while (left <= right) { var mid = parseInt((left + right) / 2); var up_cnt = upperBound(arr1,0, n, mid); up_cnt += upperBound(arr2, 0, m, mid); if (up_cnt >= k) { ans = Math.min(ans, mid); // find the min of all answers. right = mid - 1; // Try to find a smaller answer. } else left = mid + 1; // Current mid is too small so // shift right. } return ans;} // Driver code // Example 1var n = 5, m = 7, k = 7;var arr1 = [ 100, 112, 256, 349, 770 ];var arr2 = [ 72, 86, 113, 119, 265, 445, 892 ];document.write(kthElement(arr1, arr2, n, m, k)); // This code is contributed by Shubham Singh</script> 256 Time Complexity : O( Log( maxN ).log( N+M ) )Auxiliary Space : O( 1 ) This article is contributed by Aditya Kamath. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp Mithun Kumar 29AjayKumar princiraj1992 gfg_sal_gfg Vivekkumar Singh Majorssn sreejithsankar55 RohitOberoi avanitrachhadiya2155 yashbeersingh42 neeruap2001 rag2127 harshitkap00r umadevi9616 kumarsamaksha dharanendralv23 GauravRajput1 SHUBHAMSINGH10 abhishek0719kadiyan _saurabh_jaiswal Amazon Binary Search Flipkart Arrays Divide and Conquer Flipkart Amazon Arrays Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search QuickSort Merge Sort Binary Search Maximum and minimum of an array using minimum number of comparisons Program for Tower of Hanoi
[ { "code": null, "e": 24831, "s": 24803, "text": "\n25 Jan, 2022" }, { "code": null, "e": 24987, "s": 24831, "text": "Given two sorted arrays of size m and n respectively, you are tasked with finding the element that would be at the k’th position of the final sorted array." }, { "code": null, "e": 24998, "s": 24987, "text": "Examples: " }, { "code": null, "e": 25426, "s": 24998, "text": "Input : Array 1 - 2 3 6 7 9\n Array 2 - 1 4 8 10\n k = 5\nOutput : 6\nExplanation: The final sorted array would be -\n1, 2, 3, 4, 6, 7, 8, 9, 10\nThe 5th element of this array is 6.\n\nInput : Array 1 - 100 112 256 349 770\n Array 2 - 72 86 113 119 265 445 892\n k = 7\nOutput : 256\nExplanation: Final sorted array is -\n72, 86, 100, 112, 113, 119, 256, 265, 349, 445, 770, 892\n7th element of this array is 256." }, { "code": null, "e": 25587, "s": 25426, "text": "Basic Approach Since we are given two sorted arrays, we can use the merging technique to get the final merged array. From this, we simply go to the k’th index. " }, { "code": null, "e": 25591, "s": 25587, "text": "C++" }, { "code": null, "e": 25596, "s": 25591, "text": "Java" }, { "code": null, "e": 25604, "s": 25596, "text": "Python3" }, { "code": null, "e": 25607, "s": 25604, "text": "C#" }, { "code": null, "e": 25611, "s": 25607, "text": "PHP" }, { "code": null, "e": 25622, "s": 25611, "text": "Javascript" }, { "code": "// Program to find kth element from two sorted arrays#include <iostream>using namespace std; int kth(int arr1[], int arr2[], int m, int n, int k){ int sorted1[m + n]; int i = 0, j = 0, d = 0; while (i < m && j < n) { if (arr1[i] < arr2[j]) sorted1[d++] = arr1[i++]; else sorted1[d++] = arr2[j++]; } while (i < m) sorted1[d++] = arr1[i++]; while (j < n) sorted1[d++] = arr2[j++]; return sorted1[k - 1];} // Driver Codeint main(){ int arr1[5] = {2, 3, 6, 7, 9}; int arr2[4] = {1, 4, 8, 10}; int k = 5; cout << kth(arr1, arr2, 5, 4, k); return 0;}", "e": 26256, "s": 25622, "text": null }, { "code": "// Java Program to find kth element// from two sorted arrays class Main{ static int kth(int arr1[], int arr2[], int m, int n, int k) { int[] sorted1 = new int[m + n]; int i = 0, j = 0, d = 0; while (i < m && j < n) { if (arr1[i] < arr2[j]) sorted1[d++] = arr1[i++]; else sorted1[d++] = arr2[j++]; } while (i < m) sorted1[d++] = arr1[i++]; while (j < n) sorted1[d++] = arr2[j++]; return sorted1[k - 1]; } // Driver Code public static void main (String[] args) { int arr1[] = {2, 3, 6, 7, 9}; int arr2[] = {1, 4, 8, 10}; int k = 5; System.out.print(kth(arr1, arr2, 5, 4, k)); }} /* This code is contributed by Harsh Agarwal */", "e": 27065, "s": 26256, "text": null }, { "code": "# Program to find kth element# from two sorted arrays def kth(arr1, arr2, m, n, k): sorted1 = [0] * (m + n) i = 0 j = 0 d = 0 while (i < m and j < n): if (arr1[i] < arr2[j]): sorted1[d] = arr1[i] i += 1 else: sorted1[d] = arr2[j] j += 1 d += 1 while (i < m): sorted1[d] = arr1[i] d += 1 i += 1 while (j < n): sorted1[d] = arr2[j] d += 1 j += 1 return sorted1[k - 1] # Driver codearr1 = [2, 3, 6, 7, 9]arr2 = [1, 4, 8, 10]k = 5print(kth(arr1, arr2, 5, 4, k)) # This code is contributed by Smitha Dinesh Semwal", "e": 27710, "s": 27065, "text": null }, { "code": "// C# Program to find kth element// from two sorted arraysclass GFG { static int kth(int[] arr1, int[] arr2, int m, int n, int k) { int[] sorted1 = new int[m + n]; int i = 0, j = 0, d = 0; while (i < m && j < n) { if (arr1[i] < arr2[j]) sorted1[d++] = arr1[i++]; else sorted1[d++] = arr2[j++]; } while (i < m) sorted1[d++] = arr1[i++]; while (j < n) sorted1[d++] = arr2[j++]; return sorted1[k - 1]; } // Driver Code static void Main() { int[] arr1 = { 2, 3, 6, 7, 9 }; int[] arr2 = { 1, 4, 8, 10 }; int k = 5; System.Console.WriteLine(kth(arr1, arr2, 5, 4, k)); }} // This code is contributed by mits", "e": 28502, "s": 27710, "text": null }, { "code": "<?php// Program to find kth// element from two// sorted arrays function kth($arr1, $arr2, $m, $n, $k){ $sorted1[$m + $n] = 0; $i = 0; $j = 0; $d = 0; while ($i < $m && $j < $n) { if ($arr1[$i] < $arr2[$j]) $sorted1[$d++] = $arr1[$i++]; else $sorted1[$d++] = $arr2[$j++]; } while ($i < $m) $sorted1[$d++] = $arr1[$i++]; while ($j < $n) $sorted1[$d++] = $arr2[$j++]; return $sorted1[$k - 1];} // Driver Code$arr1 = array(2, 3, 6, 7, 9);$arr2 = array(1, 4, 8, 10);$k = 5;echo kth($arr1, $arr2, 5, 4, $k); // This code is contributed// by ChitraNayal?>", "e": 29143, "s": 28502, "text": null }, { "code": "<script> // JavaScript Program to find kth element// from two sorted arrays function kth(arr1 , arr2 , m , n , k) { var sorted1 = Array(m + n).fill(0); var i = 0, j = 0, d = 0; while (i < m && j < n) { if (arr1[i] < arr2[j]) sorted1[d++] = arr1[i++]; else sorted1[d++] = arr2[j++]; } while (i < m) sorted1[d++] = arr1[i++]; while (j < n) sorted1[d++] = arr2[j++]; return sorted1[k - 1]; } // Driver Code var arr1 = [ 2, 3, 6, 7, 9 ]; var arr2 = [ 1, 4, 8, 10 ]; var k = 5; document.write(kth(arr1, arr2, 5, 4, k)); // This code contributed by umadevi9616 </script>", "e": 29875, "s": 29143, "text": null }, { "code": null, "e": 29877, "s": 29875, "text": "6" }, { "code": null, "e": 29927, "s": 29877, "text": "Time Complexity: O(n) Auxiliary Space : O(m + n) " }, { "code": null, "e": 30007, "s": 29927, "text": "Space Optimized Version of above approach: We can avoid the use of extra array." }, { "code": null, "e": 30011, "s": 30007, "text": "C++" }, { "code": null, "e": 30016, "s": 30011, "text": "Java" }, { "code": null, "e": 30024, "s": 30016, "text": "Python3" }, { "code": null, "e": 30027, "s": 30024, "text": "C#" }, { "code": null, "e": 30038, "s": 30027, "text": "Javascript" }, { "code": "// C++ program to find kth element// from two sorted arrays#include <bits/stdc++.h>using namespace std; int find(int A[], int B[], int m, int n, int k_req){ int k = 0, i = 0, j = 0; // Keep taking smaller of the current // elements of two sorted arrays and // keep incrementing k while(i < m && j < n) { if(A[i] < B[j]) { k++; if(k == k_req) return A[i]; i++; } else { k++; if(k == k_req) return B[j]; j++; } } // If array B[] is completely traversed while(i < m) { k++; if(k == k_req) return A[i]; i++; } // If array A[] is completely traversed while(j < n) { k++; if(k == k_req) return B[j]; j++; }} // Driver Codeint main(){ int A[5] = { 2, 3, 6, 7, 9 }; int B[4] = { 1, 4, 8, 10 }; int k = 5; cout << find(A, B, 5, 4, k); return 0;} // This code is contributed by Sreejith S", "e": 31100, "s": 30038, "text": null }, { "code": "import java.io.*; class GFG { public static int find(int A[], int B[], int m, int n, int k_req) { int k = 0, i = 0, j = 0; // Keep taking smaller of the current // elements of two sorted arrays and // keep incrementing k while (i < m && j < n) { if (A[i] < B[j]) { k++; if (k == k_req) return A[i]; i++; } else { k++; if (k == k_req) return B[j]; j++; } } // If array B[] is completely traversed while (i < m) { k++; if (k == k_req) return A[i]; i++; } // If array A[] is completely traversed while (j < n) { k++; if (k == k_req) return B[j]; j++; } return -1; } // Driver Code public static void main(String[] args) { int[] A = { 2, 3, 6, 7, 9 }; int[] B = { 1, 4, 8, 10 }; int k = 5; System.out.println(find(A, B, 5, 4, k)); }}", "e": 32269, "s": 31100, "text": null }, { "code": "# Python3 Program to find kth element# from two sorted arrays def find(A, B, m, n, k_req): i, j, k = 0, 0, 0 # Keep taking smaller of the current # elements of two sorted arrays and # keep incrementing k while i < len(A) and j < len(B): if A[i] < B[j]: k += 1 if k == k_req: return A[i] i += 1 else: k += 1 if k == k_req: return B[j] j += 1 # If array B[] is completely traversed while i < len(A): k += 1 if k == k_req: return A[i] i += 1 # If array A[] is completely traversed while j < len(B): k += 1 if k == k_req: return B[j] j += 1 # driver codeA = [2, 3, 6, 7, 9]B = [1, 4, 8, 10]k = 5;print(find(A, B, 5, 4, k))# time complexity of O(k)", "e": 33136, "s": 32269, "text": null }, { "code": "// C# program to find kth element// from two sorted arraysusing System;public class GFG{ public static int find(int[] A, int[] B, int m, int n,int k_req) { int k = 0, i = 0, j = 0; // Keep taking smaller of the current // elements of two sorted arrays and // keep incrementing k while (i < m && j < n) { if (A[i] < B[j]) { k++; if (k == k_req) return A[i]; i++; } else { k++; if (k == k_req) return B[j]; j++; } } // If array B[] is completely traversed while (i < m) { k++; if (k == k_req) return A[i]; i++; } // If array A[] is completely traversed while (j < n) { k++; if (k == k_req) return B[j]; j++; } return -1; } // Driver Code static public void Main (){ int[] A = { 2, 3, 6, 7, 9 }; int[] B = { 1, 4, 8, 10 }; int k = 5; Console.WriteLine(find(A, B, 5, 4, k)); }} // This code is contributed by rag2127", "e": 34165, "s": 33136, "text": null }, { "code": "<script> function find(A, B, m, n, k_req) { let k = 0, i = 0, j = 0; // Keep taking smaller of the current // elements of two sorted arrays and // keep incrementing k while (i < m && j < n) { if (A[i] < B[j]) { k++; if (k == k_req) return A[i]; i++; } else { k++; if (k == k_req) return B[j]; j++; } } // If array B[] is completely traversed while (i < m) { k++; if (k == k_req) return A[i]; i++; } // If array A[] is completely traversed while (j < n) { k++; if (k == k_req) return B[j]; j++; } return -1; } // Driver Code let A = [ 2, 3, 6, 7, 9 ]; let B = [ 1, 4, 8, 10 ]; let k = 5; document.write(find(A, B, 5, 4, k)); // This code is contributed by Dharanendra L V. </script>", "e": 35256, "s": 34165, "text": null }, { "code": null, "e": 35258, "s": 35256, "text": "6" }, { "code": null, "e": 35302, "s": 35258, "text": "Time Complexity: O(k) Auxiliary Space: O(1)" }, { "code": null, "e": 35901, "s": 35302, "text": "Divide And Conquer Approach 1 While the previous method works, can we make our algorithm more efficient? The answer is yes. By using a divide and conquer approach, similar to the one used in binary search, we can attempt to find the k’th element in a more efficient way.Compare the middle elements of arrays arr1 and arr2, let us call these indices mid1 and mid2 respectively. Let us assume arr1[mid1] k, then clearly the elements after mid2 cannot be the required element. Set the last element of arr2 to be arr2[mid2].In this way, define a new subproblem with half the size of one of the arrays." }, { "code": null, "e": 36172, "s": 35901, "text": "Divide And Conquer Approach 1 While the previous method works, can we make our algorithm more efficient? The answer is yes. By using a divide and conquer approach, similar to the one used in binary search, we can attempt to find the k’th element in a more efficient way." }, { "code": null, "e": 36424, "s": 36172, "text": "Compare the middle elements of arrays arr1 and arr2, let us call these indices mid1 and mid2 respectively. Let us assume arr1[mid1] k, then clearly the elements after mid2 cannot be the required element. Set the last element of arr2 to be arr2[mid2]." }, { "code": null, "e": 36502, "s": 36424, "text": "In this way, define a new subproblem with half the size of one of the arrays." }, { "code": null, "e": 36506, "s": 36502, "text": "C++" }, { "code": null, "e": 36514, "s": 36506, "text": "Python3" }, { "code": "// Program to find k-th element from two sorted arrays#include <iostream>using namespace std; int kth(int *arr1, int *arr2, int *end1, int *end2, int k){ if (arr1 == end1) return arr2[k]; if (arr2 == end2) return arr1[k]; int mid1 = (end1 - arr1) / 2; int mid2 = (end2 - arr2) / 2; if (mid1 + mid2 < k) { if (arr1[mid1] > arr2[mid2]) return kth(arr1, arr2 + mid2 + 1, end1, end2, k - mid2 - 1); else return kth(arr1 + mid1 + 1, arr2, end1, end2, k - mid1 - 1); } else { if (arr1[mid1] > arr2[mid2]) return kth(arr1, arr2, arr1 + mid1, end2, k); else return kth(arr1, arr2, end1, arr2 + mid2, k); }} int main(){ int arr1[5] = {2, 3, 6, 7, 9}; int arr2[4] = {1, 4, 8, 10}; int k = 5; cout << kth(arr1, arr2, arr1 + 5, arr2 + 4, k - 1); return 0;}", "e": 37422, "s": 36514, "text": null }, { "code": "# Python program to find k-th element from two sorted arraysdef kth(arr1, arr2, n, m, k): if n == 1 or m == 1: if m == 1: arr2, arr1 = arr1, arr2 m = n if k == 1: return min(arr1[0], arr2[0]) elif k == m + 1: return max(arr1[0], arr2[0]) else: if arr2[k - 1] < arr1[0]: return arr2[k - 1] else: return max(arr1[0], arr2[k - 2]) mid1 = (n - 1)//2 mid2 = (m - 1)//2 if mid1+mid2+1 < k: if arr1[mid1] < arr2[mid2]: return kth(arr1[mid1 + 1:], arr2, n - mid1 - 1, m, k - mid1 - 1) else: return kth(arr1, arr2[mid2 + 1:], n, m - mid2 - 1, k - mid2 - 1) else: if arr1[mid1] < arr2[mid2]: return kth(arr1, arr2[:mid2 + 1], n, mid2 + 1, k) else: return kth(arr1[:mid1 + 1], arr2, mid1 + 1, m, k) if __name__ == \"__main__\": arr1 = [2, 3, 6, 7, 9] arr2 = [1, 4, 8, 10] k = 5 print(kth(arr1, arr2, 5, 4, k)) # This code is contributed by harshitkap00r", "e": 38490, "s": 37422, "text": null }, { "code": null, "e": 38492, "s": 38490, "text": "6" }, { "code": null, "e": 38671, "s": 38492, "text": "Note that in the above code, k is 0 indexed, which means if we want a k that’s 1 indexed, we have to subtract 1 when passing it to the function. Time Complexity: O(log n + log m)" }, { "code": null, "e": 38970, "s": 38671, "text": "Divide And Conquer Approach 2 While the above implementation is very efficient, we can still get away with making it more efficient. Instead of dividing the array into segments of n / 2 and m / 2 then recursing, we can divide them both by k / 2 and recurse. The below implementation displays this. " }, { "code": null, "e": 39552, "s": 38970, "text": "Explanation:\nInstead of comparing the middle element of the arrays,\nwe compare the k / 2nd element.\nLet arr1 and arr2 be the arrays.\nNow, if arr1[k / 2] arr1[1]\n\nNew subproblem:\nArray 1 - 6 7 9\nArray 2 - 1 4 8 10\nk = 5 - 2 = 3\n\nfloor(k / 2) = 1\narr1[1] = 6\narr2[1] = 1\narr1[1] > arr2[1]\n\nNew subproblem:\nArray 1 - 6 7 9\nArray 2 - 4 8 10\nk = 3 - 1 = 2\n\nfloor(k / 2) = 1\narr1[1] = 6\narr2[1] = 4\narr1[1] > arr2[1]\n\nNew subproblem:\nArray 1 - 6 7 9\nArray 2 - 8 10\nk = 2 - 1 = 1\n\nNow, we directly compare first elements,\nsince k = 1. \narr1[1] < arr2[1]\nHence, arr1[1] = 6 is the answer." }, { "code": null, "e": 39556, "s": 39552, "text": "C++" }, { "code": null, "e": 39561, "s": 39556, "text": "Java" }, { "code": null, "e": 39569, "s": 39561, "text": "Python3" }, { "code": null, "e": 39572, "s": 39569, "text": "C#" }, { "code": null, "e": 39583, "s": 39572, "text": "Javascript" }, { "code": "// C++ Program to find kth element from two sorted arrays#include <iostream>using namespace std; int kth(int arr1[], int arr2[], int m, int n, int k, int st1 = 0, int st2 = 0){ // In case we have reached end of array 1 if (st1 == m) return arr2[st2 + k - 1]; // In case we have reached end of array 2 if (st2 == n) return arr1[st1 + k - 1]; // k should never reach 0 or exceed sizes // of arrays if (k == 0 || k > (m - st1) + (n - st2)) return -1; // Compare first elements of arrays and return if (k == 1) return (arr1[st1] < arr2[st2]) ? arr1[st1] : arr2[st2]; int curr = k / 2; // Size of array 1 is less than k / 2 if (curr - 1 >= m - st1) { // Last element of array 1 is not kth // We can directly return the (k - m)th // element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]) return arr2[st2 + (k - (m - st1) - 1)]; else return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } // Size of array 2 is less than k / 2 if (curr-1 >= n-st2) { if (arr2[n - 1] < arr1[st1 + curr - 1]) return arr1[st1 + (k - (n - st2) - 1)]; else return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } else { // Normal comparison, move starting index // of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]) return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); else return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); }} // Driver codeint main(){ int arr1[5] = {2, 3, 6, 7, 9}; int arr2[4] = {1, 4, 8, 10}; int k = 5; cout << kth(arr1, arr2, 5, 4, k); return 0;}", "e": 41428, "s": 39583, "text": null }, { "code": "// Java Program to find kth element from two sorted arraysclass GFG{ static int kth(int arr1[], int arr2[], int m, int n, int k, int st1, int st2) { // In case we have reached end of array 1 if (st1 == m) { return arr2[st2 + k - 1]; } // In case we have reached end of array 2 if (st2 == n) { return arr1[st1 + k - 1]; } // k should never reach 0 or exceed sizes // of arrays if (k == 0 || k > (m - st1) + (n - st2)) { return -1; } // Compare first elements of arrays and return if (k == 1) { return (arr1[st1] < arr2[st2]) ? arr1[st1] : arr2[st2]; } int curr = k / 2; // Size of array 1 is less than k / 2 if (curr - 1 >= m - st1) { // Last element of array 1 is not kth // We can directly return the (k - m)th // element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]) { return arr2[st2 + (k - (m - st1) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Size of array 2 is less than k / 2 if (curr - 1 >= n - st2) { if (arr2[n - 1] < arr1[st1 + curr - 1]) { return arr1[st1 + (k - (n - st2) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } } else // Normal comparison, move starting index // of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]) { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Driver code public static void main(String[] args) { int arr1[] = {2, 3, 6, 7, 9}; int arr2[] = {1, 4, 8, 10}; int k = 5; int st1 = 0, st2 = 0; System.out.println(kth(arr1, arr2, 5, 4, k, st1, st2)); }} // This code is contributed by 29AjayKumar", "e": 43782, "s": 41428, "text": null }, { "code": "# Python3 program to find kth element from# two sorted arraysdef kth(arr1, arr2, m, n, k, st1 = 0, st2 = 0): # In case we have reached end of array 1 if (st1 == m): return arr2[st2 + k - 1] # In case we have reached end of array 2 if (st2 == n): return arr1[st1 + k - 1] # k should never reach 0 or exceed sizes # of arrays if (k == 0 or k > (m - st1) + (n - st2)): return -1 # Compare first elements of arrays and return if (k == 1): if(arr1[st1] < arr2[st2]): return arr1[st1] else: return arr2[st2] curr = int(k / 2) # Size of array 1 is less than k / 2 if(curr - 1 >= m - st1): # Last element of array 1 is not kth # We can directly return the (k - m)th # element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]): return arr2[st2 + (k - (m - st1) - 1)] else: return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr) # Size of array 2 is less than k / 2 if (curr - 1 >= n - st2): if (arr2[n - 1] < arr1[st1 + curr - 1]): return arr1[st1 + (k - (n - st2) - 1)] else: return kth(arr1, arr2, m, n, k - curr,st1 + curr, st2) else: # Normal comparison, move starting index # of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]): return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2) else: return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr) # Driver codearr1 = [ 2, 3, 6, 7, 9 ]arr2 = [ 1, 4, 8, 10 ]k = 5 print(kth(arr1, arr2, 5, 4, k)) # This code is contributed by avanitrachhadiya2155", "e": 45566, "s": 43782, "text": null }, { "code": "// C# Program to find kth element from two sorted arraysusing System; class GFG{ static int kth(int []arr1, int []arr2, int m, int n, int k, int st1, int st2) { // In case we have reached end of array 1 if (st1 == m) { return arr2[st2 + k - 1]; } // In case we have reached end of array 2 if (st2 == n) { return arr1[st1 + k - 1]; } // k should never reach 0 or exceed sizes // of arrays if (k == 0 || k > (m - st1) + (n - st2)) { return -1; } // Compare first elements of arrays and return if (k == 1) { return (arr1[st1] < arr2[st2]) ? arr1[st1] : arr2[st2]; } int curr = k / 2; // Size of array 1 is less than k / 2 if (curr - 1 >= m - st1) { // Last element of array 1 is not kth // We can directly return the (k - m)th // element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]) { return arr2[st2 + (k - (m - st1) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Size of array 2 is less than k / 2 if (curr - 1 >= n - st2) { if (arr2[n - 1] < arr1[st1 + curr - 1]) { return arr1[st1 + (k - (n - st2) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } } else // Normal comparison, move starting index // of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]) { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Driver code public static void Main(String[] args) { int []arr1 = {2, 3, 6, 7, 9}; int []arr2 = {1, 4, 8, 10}; int k = 5; int st1 = 0, st2 = 0; Console.WriteLine(kth(arr1, arr2, 5, 4, k, st1, st2)); }} // This code is contributed by PrinciRaj1992", "e": 47930, "s": 45566, "text": null }, { "code": "<script>// javascript Program to find kth element from two sorted arrays function kth(arr1 , arr2 , m , n , k , st1 , st2){ // In case we have reached end of array 1 if (st1 == m) { return arr2[st2 + k - 1]; } // In case we have reached end of array 2 if (st2 == n) { return arr1[st1 + k - 1]; } // k should never reach 0 or exceed sizes // of arrays if (k == 0 || k > (m - st1) + (n - st2)) { return -1; } // Compare first elements of arrays and return if (k == 1) { return (arr1[st1] < arr2[st2]) ? arr1[st1] : arr2[st2]; } var curr = parseInt(k / 2); // Size of array 1 is less than k / 2 if (curr - 1 >= m - st1) { // Last element of array 1 is not kth // We can directly return the (k - m)th // element in array 2 if (arr1[m - 1] < arr2[st2 + curr - 1]) { return arr2[st2 + (k - (m - st1) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Size of array 2 is less than k / 2 if (curr - 1 >= n - st2) { if (arr2[n - 1] < arr1[st1 + curr - 1]) { return arr1[st1 + (k - (n - st2) - 1)]; } else { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } } else // Normal comparison, move starting index // of one array k / 2 to the right if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1]) { return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2); } else { return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr); } } // Driver code var arr1 = [ 2, 3, 6, 7, 9 ]; var arr2 = [ 1, 4, 8, 10 ]; var k = 5; var st1 = 0, st2 = 0; document.write(kth(arr1, arr2, 5, 4, k, st1, st2)); // This code is contributed by gauravrajput1</script>", "e": 49942, "s": 47930, "text": null }, { "code": null, "e": 49944, "s": 49942, "text": "6" }, { "code": null, "e": 49970, "s": 49944, "text": "Time Complexity: O(log k)" }, { "code": null, "e": 50305, "s": 49970, "text": "Now, k can take a maximum value of m + n. This means that log k can be in the worst case, log(m + n). Logm + logn = log(mn) by properties of logarithms, and when m, n > 2, log(m + n) < log(mn). Thus this algorithm slightly outperforms the previous algorithm. Also, see another simple implemented log k approach suggested by Raj Kumar." }, { "code": null, "e": 50309, "s": 50305, "text": "C++" }, { "code": null, "e": 50314, "s": 50309, "text": "Java" }, { "code": null, "e": 50322, "s": 50314, "text": "Python3" }, { "code": null, "e": 50325, "s": 50322, "text": "C#" }, { "code": null, "e": 50336, "s": 50325, "text": "Javascript" }, { "code": "// C++ Program to find kth// element from two sorted arrays// Time Complexity: O(log k) #include <iostream>using namespace std; int kth(int arr1[], int m, int arr2[], int n, int k){ if (k > (m + n) || k < 1) return -1; // let m <= n if (m > n) return kth(arr2, n, arr1, m, k); // Check if arr1 is empty returning // k-th element of arr2 if (m == 0) return arr2[k - 1]; // Check if k = 1 return minimum of // first two elements of both // arrays if (k == 1) return min(arr1[0], arr2[0]); // Now the divide and conquer part int i = min(m, k / 2), j = min(n, k / 2); if (arr1[i - 1] > arr2[j - 1]) // Now we need to find only // k-j th element since we // have found out the lowest j return kth(arr1, m, arr2 + j, n - j, k - j); else // Now we need to find only // k-i th element since we // have found out the lowest i return kth(arr1 + i, m - i, arr2, n, k - i);} // Driver codeint main(){ int arr1[5] = { 2, 3, 6, 7, 9 }; int arr2[4] = { 1, 4, 8, 10 }; int m = sizeof(arr1) / sizeof(arr1[0]); int n = sizeof(arr2) / sizeof(arr2[0]); int k = 5; int ans = kth(arr1, m, arr2, n, k); if (ans == -1) cout << \"Invalid query\"; else cout << ans; return 0;}// This code is contributed by Raj Kumar", "e": 51715, "s": 50336, "text": null }, { "code": "// Java Program to find kth element// from two sorted arrays// Time Complexity: O(log k)import java.util.Arrays; class Gfg { static int kth(int arr1[], int m, int arr2[], int n, int k) { if (k > (m + n) || k < 1) return -1; // let m > n if (m > n) return kth(arr2, n, arr1, m, k); // Check if arr1 is empty returning // k-th element of arr2 if (m == 0) return arr2[k - 1]; // Check if k = 1 return minimum of first // two elements of both arrays if (k == 1) return Math.min(arr1[0], arr2[0]); // Now the divide and conquer part int i = Math.min(m, k / 2); int j = Math.min(n, k / 2); if (arr1[i - 1] > arr2[j - 1]) { // Now we need to find only k-j th element // since we have found out the lowest j int temp[] = Arrays.copyOfRange(arr2, j, n); return kth(arr1, m, temp, n - j, k - j); } // Now we need to find only k-i th element // since we have found out the lowest i int temp[] = Arrays.copyOfRange(arr1, i, m); return kth(temp, m - i, arr2, n, k - i); } // Driver code public static void main(String[] args) { int arr1[] = { 2, 3, 6, 7, 9 }; int arr2[] = { 1, 4, 8, 10 }; int m = arr1.length; int n = arr2.length; int k = 5; int ans = kth(arr1, m, arr2, n, k); if (ans == -1) System.out.println(\"Invalid query\"); else System.out.println(ans); }} // This code is contributed by Vivek Kumar Singh", "e": 53365, "s": 51715, "text": null }, { "code": "# Python3 Program to find kth element from two# sorted arrays. Time Complexity: O(log k)def kth(arr1, m, arr2, n, k): if (k > (m + n) or k < 1): return -1 # Let m <= n if (m > n): return kth(arr2, n, arr1, m, k) # Check if arr1 is empty returning # k-th element of arr2 if (m == 0): return arr2[k - 1] # Check if k = 1 return minimum of # first two elements of both # arrays if (k == 1): return min(arr1[0], arr2[0]) # Now the divide and conquer part i = min(m, k // 2) j = min(n, k // 2) if (arr1[i - 1] > arr2[j - 1]): # Now we need to find only # k-j th element since we # have found out the lowest j return kth(arr1, m, arr2[j:], n - j, k - j) else: # Now we need to find only # k-i th element since we # have found out the lowest i return kth(arr1[i:], m - i, arr2, n, k - i) # Driver codearr1 = [ 2, 3, 6, 7, 9 ]arr2 = [ 1, 4, 8, 10 ]m = len(arr1)n = len(arr2)k = 5 ans = kth(arr1, m, arr2, n, k) if (ans == -1): print(\"Invalid query\")else: print(ans) # This code is contributed by Shubham Singh", "e": 54554, "s": 53365, "text": null }, { "code": "// C# Program to find kth element// from two sorted arrays// Time Complexity: O(log k)using System;using System.Collections.Generic; public class GFG{ static int kth(int[] arr1, int m, int[] arr2, int n, int k) { if (k > (m + n) || k < 1) return -1; // let m > n if (m > n) return kth(arr2, n, arr1, m, k); // Check if arr1 is empty returning // k-th element of arr2 if (m == 0) return arr2[k - 1]; // Check if k = 1 return minimum of first // two elements of both arrays if (k == 1) return Math.Min(arr1[0], arr2[0]); // Now the divide and conquer part int i = Math.Min(m, k / 2); int j = Math.Min(n, k / 2); if (arr1[i - 1] > arr2[j - 1]) { // Now we need to find only k-j th element // since we have found out the lowest j int[] temp = new int[n - j]; Array.Copy(arr2, j, temp, 0, n-j); return kth(arr1, m, temp, n - j, k - j); } // Now we need to find only k-i th element // since we have found out the lowest i int[] temp1 = new int[m-i]; Array.Copy(arr1, i, temp1, 0, m-i); return kth(temp1, m - i, arr2, n, k - i); } // Driver code public static void Main() { int[] arr1 = { 2, 3, 6, 7, 9 }; int[] arr2 = { 1, 4, 8, 10 }; int m = arr1.Length; int n = arr2.Length; int k = 5; int ans = kth(arr1, m, arr2, n, k); if (ans == -1) Console.WriteLine(\"Invalid query\"); else Console.WriteLine(ans); }} // This code is contributed by Shubham Singh", "e": 56071, "s": 54554, "text": null }, { "code": "<script>// Javascript program to illustrate time// complexity for Nested loops function kth(arr1, m, arr2, n, k){ if (k > (m + n) || k < 1){ return -1; } // let m <= n if (m > n){ return kth(arr2, n, arr1, m, k); } // Check if arr1 is empty returning // k-th element of arr2 if (m == 0){ return arr2[k - 1]; } // Check if k = 1 return minimum of // first two elements of both // arrays if (k == 1){ return Math.min(arr1[0], arr2[0]); } // Now the divide and conquer part let i = Math.min(m, parseInt(k / 2)); let j = Math.min(n, parseInt(k / 2)); if (arr1[i - 1] > arr2[j - 1]){ // Now we need to find only // k-j th element since we // have found out the lowest j let temp = arr2.slice(j,n) return kth(arr1, m, temp, n - j, k - j); } else{ // Now we need to find only // k-i th element since we // have found out the lowest i let temp = arr1.slice(i,m) return kth( temp, m - i, arr2, n, k - i); }} // Driver code let arr1 = [ 2, 3, 6, 7, 9 ];let arr2 = [ 1, 4, 8, 10 ];let m = 5;let n = 4;let k = 5; let ans = kth(arr1, m, arr2, n, k); if (ans == -1){ document.write(\"Invalid query\");}else{ document.write(ans);} // This code is contributed by Shubham Singh</script>", "e": 57431, "s": 56071, "text": null }, { "code": null, "e": 57433, "s": 57431, "text": "6" }, { "code": null, "e": 57458, "s": 57433, "text": "Time Complexity:O(log k)" }, { "code": null, "e": 57493, "s": 57458, "text": "Another Approach: (Using Min Heap)" }, { "code": null, "e": 57660, "s": 57493, "text": "Push the elements of both arrays to a priority queue (min-heap).Pop-out k-1 elements from the front.Element at the front of the priority queue is the required answer." }, { "code": null, "e": 57725, "s": 57660, "text": "Push the elements of both arrays to a priority queue (min-heap)." }, { "code": null, "e": 57762, "s": 57725, "text": "Pop-out k-1 elements from the front." }, { "code": null, "e": 57829, "s": 57762, "text": "Element at the front of the priority queue is the required answer." }, { "code": null, "e": 57880, "s": 57829, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 57884, "s": 57880, "text": "C++" }, { "code": null, "e": 57889, "s": 57884, "text": "Java" }, { "code": null, "e": 57897, "s": 57889, "text": "Python3" }, { "code": null, "e": 57900, "s": 57897, "text": "C#" }, { "code": null, "e": 57911, "s": 57900, "text": "Javascript" }, { "code": "// C++ Program to find kth// element from two sorted arrays#include <bits/stdc++.h>using namespace std; // Function to find K-th minint kth(int* a, int* b, int n, int m, int k){ // Declaring a min heap priority_queue<int, vector<int>, greater<int> > pq; // Pushing elements for // array a to min-heap for (int i = 0; i < n; i++) { pq.push(a[i]); } // Pushing elements for // array b to min-heap for (int i = 0; i < m; i++) { pq.push(b[i]); } // Popping-out K-1 elements while (k-- > 1) { pq.pop(); } return pq.top();} //Driver Codeint main(){ int arr1[5] = {2, 3, 6, 7, 9}; int arr2[4] = {1, 4, 8, 10}; int k = 5; cout << kth(arr1, arr2, 5, 4, k); return 0;} // This code is contributed by yashbeersingh42", "e": 58734, "s": 57911, "text": null }, { "code": "// Java Program to find kth element// from two sorted arraysimport java.util.*; class GFG { // Function to find K-th min static int kth(int a[], int b[], int n, int m, int k) { // Declaring a min heap PriorityQueue<Integer> pq = new PriorityQueue<>(); // Pushing elements for // array a to min-heap for (int i = 0; i < n; i++) { pq.offer(a[i]); } // Pushing elements for // array b to min-heap for (int i = 0; i < m; i++) { pq.offer(b[i]); } // Popping-out K-1 elements while (k-- > 1) { pq.remove(); } return pq.peek(); } // Driver Code public static void main(String[] args) { int arr1[] = { 2, 3, 6, 7, 9 }; int arr2[] = { 1, 4, 8, 10 }; int k = 5; System.out.print(kth(arr1, arr2, 5, 4, k)); }} // This code is contributed by yashbeersingh42", "e": 59722, "s": 58734, "text": null }, { "code": "# Python Program to find kth element# from two sorted arrays # Function to find K-th mindef kth(a , b , n , m , k): # Declaring a min heap pq = []; # Pushing elements for # array a to min-heap for i in range(n): pq.append(a[i]); # Pushing elements for # array b to min-heap for i in range(m): pq.append(b[i]); pq = sorted(pq, reverse = True) # Popping-out K-1 elements while (k > 1): k -= 1; pq.pop(); return pq.pop(); # Driver Codearr1 = [ 2, 3, 6, 7, 9 ];arr2 = [ 1, 4, 8, 10 ];k = 5;print(kth(arr1, arr2, 5, 4, k)); # This code is contributed by Saurabh Jaiswal", "e": 60360, "s": 59722, "text": null }, { "code": "// C# Program to find kth element// from two sorted arraysusing System;using System.Collections.Generic; public class GFG { // Function to find K-th min static int kth(int []a, int []b, int n, int m, int k) { // Declaring a min heap List<int> pq = new List<int>(); // Pushing elements for // array a to min-heap for (int i = 0; i < n; i++) { pq.Add(a[i]); } // Pushing elements for // array b to min-heap for (int i = 0; i < m; i++) { pq.Add(b[i]); } pq.Sort(); // Popping-out K-1 elements while (k-- > 1) { pq.RemoveAt(0); } return pq[0]; } // Driver Code public static void Main(String[] args) { int []arr1 = { 2, 3, 6, 7, 9 }; int []arr2 = { 1, 4, 8, 10 }; int k = 5; Console.Write(kth(arr1, arr2, 5, 4, k)); }} // This code is contributed by gauravrajput1", "e": 61203, "s": 60360, "text": null }, { "code": "<script>// javascript Program to find kth element// from two sorted arrays // Function to find K-th min function kth(a , b , n , m , k) { // Declaring a min heap var pq = []; // Pushing elements for // array a to min-heap for (i = 0; i < n; i++) { pq.push(a[i]); } // Pushing elements for // array b to min-heap for (i = 0; i < m; i++) { pq.push(b[i]); } pq.sort((a,b)=>b-a); // Popping-out K-1 elements while (k-- > 1) { pq.pop(); } return pq.pop(); } // Driver Code var arr1 = [ 2, 3, 6, 7, 9 ]; var arr2 = [ 1, 4, 8, 10 ]; var k = 5; document.write(kth(arr1, arr2, 5, 4, k)); // This code is contributed by gauravrajput1</script>", "e": 62028, "s": 61203, "text": null }, { "code": null, "e": 62030, "s": 62028, "text": "6" }, { "code": null, "e": 62056, "s": 62030, "text": "Time Complexity: O(NlogN)" }, { "code": null, "e": 62081, "s": 62056, "text": "Space Complexity: O(m+n)" }, { "code": null, "e": 62124, "s": 62081, "text": "Another Approach : (Using Upper Bound STL)" }, { "code": null, "e": 62280, "s": 62124, "text": "Given two sorted arrays of size m and n respectively, you are tasked with finding the element that would be at the k’th position of the final sorted array." }, { "code": null, "e": 62291, "s": 62280, "text": "Examples :" }, { "code": null, "e": 62319, "s": 62291, "text": "Input : Array 1 – 2 3 6 7 9" }, { "code": null, "e": 62348, "s": 62319, "text": " Array 2 – 1 4 8 10" }, { "code": null, "e": 62364, "s": 62348, "text": " k = 5" }, { "code": null, "e": 62375, "s": 62364, "text": "Output : 6" }, { "code": null, "e": 62422, "s": 62375, "text": "Explanation: The final sorted array would be –" }, { "code": null, "e": 62449, "s": 62422, "text": "1, 2, 3, 4, 6, 7, 8, 9, 10" }, { "code": null, "e": 62696, "s": 62449, "text": "The 5th element of this array is 6, The 1st element of this array is 1. The thing to notice here is upper_bound(6) gives 5, upper_bound(4) gives 4 that is number of element equal to or less than the number we are giving as input to upper_bound()." }, { "code": null, "e": 62720, "s": 62696, "text": "Here is another example" }, { "code": null, "e": 62758, "s": 62720, "text": "Input : Array 1 – 100 112 256 349 770" }, { "code": null, "e": 62800, "s": 62758, "text": " Array 2 – 72 86 113 119 265 445 892" }, { "code": null, "e": 62812, "s": 62800, "text": " k = 7" }, { "code": null, "e": 62825, "s": 62812, "text": "Output : 256" }, { "code": null, "e": 62862, "s": 62825, "text": "Explanation: Final sorted array is –" }, { "code": null, "e": 62919, "s": 62862, "text": "72, 86, 100, 112, 113, 119, 256, 265, 349, 445, 770, 892" }, { "code": null, "e": 62953, "s": 62919, "text": "7th element of this array is 256." }, { "code": null, "e": 62976, "s": 62953, "text": "Observation required :" }, { "code": null, "e": 63206, "s": 62976, "text": "The simplest method to solve this question is using upper_bound to check what is the position of a element in the sorted array. The upper_bound function return the pointer to element which is greater than the element we searched." }, { "code": null, "e": 63479, "s": 63206, "text": "So to find the kth element we need to just find the element whose upper_bound() is 4. So again now we now what upper_bound() gives us we need 1 last observation to solve this question. If we have been given 2 arrays, We just need to the sum of upper_bound for the 2 arrays" }, { "code": null, "e": 63507, "s": 63479, "text": "Input : Array 1 – 2 3 6 7 9" }, { "code": null, "e": 63531, "s": 63507, "text": " Array 2 – 1 4 8 10" }, { "code": null, "e": 63542, "s": 63531, "text": " k = 5" }, { "code": null, "e": 63661, "s": 63542, "text": "Value of upper_bound for value(6) in array1 is 3 and for array 2 is 2. This give us a total of 5. which is the answer." }, { "code": null, "e": 63673, "s": 63661, "text": "Algorithm :" }, { "code": null, "e": 63734, "s": 63673, "text": "We take a mid between [L,R] using the formula mid = (L+R)/2." }, { "code": null, "e": 63806, "s": 63734, "text": "Check if the middle can be the kth element using upper_bound() function" }, { "code": null, "e": 63918, "s": 63806, "text": "Find the sum of upper_bound() for both the arrays and if the sum is >= K, It’s a possible value of kth element." }, { "code": null, "e": 63961, "s": 63918, "text": "If sum is >= K then we assign R = mid – 1." }, { "code": null, "e": 64035, "s": 63961, "text": "else if sum <k then the current mid is too small and we assign L = mid+1." }, { "code": null, "e": 64051, "s": 64035, "text": "Repeat from top" }, { "code": null, "e": 64084, "s": 64051, "text": "Return the smallest value found." }, { "code": null, "e": 64138, "s": 64084, "text": "Here is the implementation for the optimized method :" }, { "code": null, "e": 64142, "s": 64138, "text": "C++" }, { "code": null, "e": 64147, "s": 64142, "text": "Java" }, { "code": null, "e": 64155, "s": 64147, "text": "Python3" }, { "code": null, "e": 64158, "s": 64155, "text": "C#" }, { "code": null, "e": 64169, "s": 64158, "text": "Javascript" }, { "code": "// C++ program to find the kth element#include <bits/stdc++.h>using namespace std; long long int maxN = 1e10; // the maximum value in the array possible. long long int kthElement(int arr1[], int arr2[], int n, int m, int k){ long long int left = 1, right = maxN; // The range of where ans can lie. long long int ans = 1e15; // We have to find min of all // the ans so take . // using binary search to check all possible values of // kth element while (left <= right) { long long int mid = (left + right) / 2; long long int up_cnt = upper_bound(arr1, arr1 + n, mid) - arr1; up_cnt += upper_bound(arr2, arr2 + m, mid) - arr2; if (up_cnt >= k) { ans = min(ans, mid); // find the min of all answers. right = mid - 1; // Try to find a smaller answer. } else left = mid + 1; // Current mid is too small so // shift right. } return ans;} // Driver codeint main(){ // Example 1 int n = 5, m = 7, k = 7; int arr1[n] = { 100, 112, 256, 349, 770 }; int arr2[m] = { 72, 86, 113, 119, 265, 445, 892 }; cout << kthElement(arr1, arr2, n, m, k) << endl; return 0;}", "e": 65499, "s": 64169, "text": null }, { "code": "// Java program to find the kth elementimport java.util.*;class GFG{ static long maxN = (long)1e10; // the maximum value in the array possible. static int upperBound(int[] a, int low, int high, long element){ while(low < high){ int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} static long kthElement(int arr1[], int arr2[], int n, int m, int k){ long left = 1, right = maxN; // The range of where ans can lie. long ans = (long)1e15; // We have to find min of all // the ans so take . // using binary search to check all possible values of // kth element while (left <= right) { long mid = (left + right) / 2; long up_cnt = upperBound(arr1,0, n, mid); up_cnt += upperBound(arr2, 0, m, mid); if (up_cnt >= k) { ans = Math.min(ans, mid); // find the min of all answers. right = mid - 1; // Try to find a smaller answer. } else left = mid + 1; // Current mid is too small so // shift right. } return ans;} // Driver codepublic static void main(String[] args){ // Example 1 int n = 5, m = 7, k = 7; int arr1[] = { 100, 112, 256, 349, 770 }; int arr2[] = { 72, 86, 113, 119, 265, 445, 892 }; System.out.print(kthElement(arr1, arr2, n, m, k) +\"\\n\");}} // This code is contributed by gauravrajput1", "e": 67061, "s": 65499, "text": null }, { "code": "# Python program to find the kth elementmaxN = 10**10 # the maximum value in the array possible. def upperBound(a, low, high, element): while(low < high): middle = low + (high - low)//2 if(a[middle] > element): high = middle else: low = middle + 1 return low def kthElement(arr1, arr2, n, m, k): left = 1 right = maxN # The range of where ans can lie. ans = 10**15 # We have to find min of all # the ans so take . # using binary search to check all possible values of # kth element while (left <= right): mid = (left + right) // 2 up_cnt = upperBound(arr1,0, n, mid) up_cnt += upperBound(arr2, 0, m, mid) if (up_cnt >= k): ans = min(ans, mid) # find the min of all answers. right= mid - 1 # Try to find a smaller answer. else: left = mid + 1 # Current mid is too small so # shift right. return ans # Driver code# Example 1n = 5m = 7k = 7arr1 = [100, 112, 256, 349, 770]arr2 = [72, 86, 113, 119, 265, 445, 892]print(kthElement(arr1, arr2, n, m, k)) # This code is contributed by Shubham Singh", "e": 68219, "s": 67061, "text": null }, { "code": "// C# program to find the kth element using System; public class GFG{ static long maxN = (long)1e10; // the maximum value in the array possible. static int upperBound(int[] a, int low, int high, long element) { while(low < high){ int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low; } static long kthElement(int[] arr1, int[] arr2, int n, int m, int k) { long left = 1, right = maxN; // The range of where ans can lie. long ans = (long)1e15; // We have to find min of all // the ans so take . // using binary search to check all possible values of // kth element while (left <= right) { long mid = (left + right) / 2; long up_cnt = upperBound(arr1,0, n, mid); up_cnt += upperBound(arr2, 0, m, mid); if (up_cnt >= k) { ans = Math.Min(ans, mid); // find the min of all answers. right = mid - 1; // Try to find a smaller answer. } else left = mid + 1; // Current mid is too small so // shift right. } return ans; } // Driver code static public void Main (){ // Example 1 int n = 5, m = 7, k = 7; int[] arr1 = { 100, 112, 256, 349, 770 }; int[] arr2 = { 72, 86, 113, 119, 265, 445, 892 }; Console.Write(kthElement(arr1, arr2, n, m, k) +\"\\n\"); }} // This code is contributed by SHubham Singh", "e": 69971, "s": 68219, "text": null }, { "code": "<script>// Javascript program to find the kth elementvar maxN = 10000000000; // the maximum value in the array possible. function upperBound(a, low, high, element){ while(low < high){ var middle = parseInt(low + (high - low)/2); if(a[middle] > element) high = middle; else low = middle + 1; } return low;} function kthElement(arr1, arr2, n, m, k){ var left = 1 var right = maxN; // The range of where ans can lie. var ans = 1000000000000000; // We have to find min of all // the ans so take . // using binary search to check all possible values of // kth element while (left <= right) { var mid = parseInt((left + right) / 2); var up_cnt = upperBound(arr1,0, n, mid); up_cnt += upperBound(arr2, 0, m, mid); if (up_cnt >= k) { ans = Math.min(ans, mid); // find the min of all answers. right = mid - 1; // Try to find a smaller answer. } else left = mid + 1; // Current mid is too small so // shift right. } return ans;} // Driver code // Example 1var n = 5, m = 7, k = 7;var arr1 = [ 100, 112, 256, 349, 770 ];var arr2 = [ 72, 86, 113, 119, 265, 445, 892 ];document.write(kthElement(arr1, arr2, n, m, k)); // This code is contributed by Shubham Singh</script>", "e": 71382, "s": 69971, "text": null }, { "code": null, "e": 71386, "s": 71382, "text": "256" }, { "code": null, "e": 71456, "s": 71386, "text": "Time Complexity : O( Log( maxN ).log( N+M ) )Auxiliary Space : O( 1 )" }, { "code": null, "e": 71876, "s": 71456, "text": "This article is contributed by Aditya Kamath. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 71882, "s": 71876, "text": "ukasp" }, { "code": null, "e": 71895, "s": 71882, "text": "Mithun Kumar" }, { "code": null, "e": 71907, "s": 71895, "text": "29AjayKumar" }, { "code": null, "e": 71921, "s": 71907, "text": "princiraj1992" }, { "code": null, "e": 71933, "s": 71921, "text": "gfg_sal_gfg" }, { "code": null, "e": 71950, "s": 71933, "text": "Vivekkumar Singh" }, { "code": null, "e": 71959, "s": 71950, "text": "Majorssn" }, { "code": null, "e": 71976, "s": 71959, "text": "sreejithsankar55" }, { "code": null, "e": 71988, "s": 71976, "text": "RohitOberoi" }, { "code": null, "e": 72009, "s": 71988, "text": "avanitrachhadiya2155" }, { "code": null, "e": 72025, "s": 72009, "text": "yashbeersingh42" }, { "code": null, "e": 72037, "s": 72025, "text": "neeruap2001" }, { "code": null, "e": 72045, "s": 72037, "text": "rag2127" }, { "code": null, "e": 72059, "s": 72045, "text": "harshitkap00r" }, { "code": null, "e": 72071, "s": 72059, "text": "umadevi9616" }, { "code": null, "e": 72085, "s": 72071, "text": "kumarsamaksha" }, { "code": null, "e": 72101, "s": 72085, "text": "dharanendralv23" }, { "code": null, "e": 72115, "s": 72101, "text": "GauravRajput1" }, { "code": null, "e": 72130, "s": 72115, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 72150, "s": 72130, "text": "abhishek0719kadiyan" }, { "code": null, "e": 72167, "s": 72150, "text": "_saurabh_jaiswal" }, { "code": null, "e": 72174, "s": 72167, "text": "Amazon" }, { "code": null, "e": 72188, "s": 72174, "text": "Binary Search" }, { "code": null, "e": 72197, "s": 72188, "text": "Flipkart" }, { "code": null, "e": 72204, "s": 72197, "text": "Arrays" }, { "code": null, "e": 72223, "s": 72204, "text": "Divide and Conquer" }, { "code": null, "e": 72232, "s": 72223, "text": "Flipkart" }, { "code": null, "e": 72239, "s": 72232, "text": "Amazon" }, { "code": null, "e": 72246, "s": 72239, "text": "Arrays" }, { "code": null, "e": 72265, "s": 72246, "text": "Divide and Conquer" }, { "code": null, "e": 72279, "s": 72265, "text": "Binary Search" }, { "code": null, "e": 72377, "s": 72279, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 72386, "s": 72377, "text": "Comments" }, { "code": null, "e": 72399, "s": 72386, "text": "Old Comments" }, { "code": null, "e": 72447, "s": 72399, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 72491, "s": 72447, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 72514, "s": 72491, "text": "Introduction to Arrays" }, { "code": null, "e": 72546, "s": 72514, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 72560, "s": 72546, "text": "Linear Search" }, { "code": null, "e": 72570, "s": 72560, "text": "QuickSort" }, { "code": null, "e": 72581, "s": 72570, "text": "Merge Sort" }, { "code": null, "e": 72595, "s": 72581, "text": "Binary Search" }, { "code": null, "e": 72663, "s": 72595, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
How to create an about / about us page for website with CSS?
To create an about page, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> html { box-sizing: border-box; } body { font-family: monospace, serif, sans-serif; margin: 0px; padding: 0px; } h1 { text-align: center; background-color: rgb(108, 18, 131); color: white; padding-top: 40px; padding-bottom: 40px; margin-top: 0px; } .teamContainer { margin-left: 10%; } img { width: 100%; height: 200px; } *, *:before, *:after { box-sizing: inherit; } .teamColumn { display: inline-block; width: 300px; height: 400px; margin-bottom: 16px; padding: 0 8px; } @media screen and (max-width: 650px) { .teamColumn { display: block; } } .teamCard { background-color: rgb(162, 162, 255); text-align: center; font-size: 20px; } .personContainer { padding: 0 16px; } .personContainer::after, .teamContainer::after { content: ""; clear: both; display: table; } .Designation { color: rgb(15, 0, 100); font-weight: bolder; font-size: 20px; } .contact { border: none; outline: 0; display: inline-block; padding: 12px; color: white; font-weight: bolder; background-color: rgb(78, 0, 102); text-align: center; cursor: pointer; width: 100%; } .contact:hover { background-color: #555; } </style> </head> <body> <h1>About Us</h1> <div class="teamContainer"> <div class="teamColumn"> <div class="teamCard"> <img src="https://images.pexels.com/photos/839011/pexels-photo839011.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> <div class="personContainer"> <h3>Jane Doe</h3> <p class="Designation">CTO</p> <p><button class="contact">Contact</button></p> </div> </div> </div> <div class="teamColumn"> <div class="teamCard"> <img src="https://images.pexels.com/photos/614810/pexels-photo614810.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> <div class="personContainer"> <h3>Mike Ross</h3> <p class="Designation">Front End Developer</p> <p><button class="contact">Contact</button></p> </div> </div> </div> <div class="teamColumn"> <div class="teamCard"> <img src="https://images.pexels.com/photos/736716/pexels-photo736716.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> <div class="personContainer"> <h3>John Doe</h3> <p class="Designation">FullStack Developer</p> <p><button class="contact">Contact</button></p> </div> </div> </div> </div> </body> </html> The above code will create the following output −
[ { "code": null, "e": 1112, "s": 1062, "text": "To create an about page, the code is as follows −" }, { "code": null, "e": 1123, "s": 1112, "text": " Live Demo" }, { "code": null, "e": 3720, "s": 1123, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n html {\n box-sizing: border-box;\n }\n body {\n font-family: monospace, serif, sans-serif;\n margin: 0px;\n padding: 0px;\n }\n h1 {\n text-align: center;\n background-color: rgb(108, 18, 131);\n color: white;\n padding-top: 40px;\n padding-bottom: 40px;\n margin-top: 0px;\n }\n .teamContainer {\n margin-left: 10%;\n }\n img {\n width: 100%;\n height: 200px;\n }\n *, *:before, *:after {\n box-sizing: inherit;\n }\n .teamColumn {\n display: inline-block;\n width: 300px;\n height: 400px;\n margin-bottom: 16px;\n padding: 0 8px;\n }\n @media screen and (max-width: 650px) {\n .teamColumn {\n display: block;\n }\n }\n .teamCard {\n background-color: rgb(162, 162, 255);\n text-align: center;\n font-size: 20px;\n }\n .personContainer {\n padding: 0 16px;\n }\n .personContainer::after, .teamContainer::after {\n content: \"\";\n clear: both;\n display: table;\n }\n .Designation {\n color: rgb(15, 0, 100);\n font-weight: bolder;\n font-size: 20px;\n }\n .contact {\n border: none;\n outline: 0;\n display: inline-block;\n padding: 12px;\n color: white;\n font-weight: bolder;\n background-color: rgb(78, 0, 102);\n text-align: center;\n cursor: pointer;\n width: 100%;\n }\n .contact:hover {\n background-color: #555;\n }\n</style>\n</head>\n<body>\n<h1>About Us</h1>\n<div class=\"teamContainer\">\n<div class=\"teamColumn\">\n<div class=\"teamCard\">\n<img src=\"https://images.pexels.com/photos/839011/pexels-photo839011.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n<div class=\"personContainer\">\n<h3>Jane Doe</h3>\n<p class=\"Designation\">CTO</p>\n<p><button class=\"contact\">Contact</button></p>\n</div>\n</div>\n</div>\n<div class=\"teamColumn\">\n<div class=\"teamCard\">\n<img\nsrc=\"https://images.pexels.com/photos/614810/pexels-photo614810.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n<div class=\"personContainer\">\n<h3>Mike Ross</h3>\n<p class=\"Designation\">Front End Developer</p>\n<p><button class=\"contact\">Contact</button></p>\n</div>\n</div>\n</div>\n<div class=\"teamColumn\">\n<div class=\"teamCard\">\n<img\nsrc=\"https://images.pexels.com/photos/736716/pexels-photo736716.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n<div class=\"personContainer\">\n<h3>John Doe</h3>\n<p class=\"Designation\">FullStack Developer</p>\n<p><button class=\"contact\">Contact</button></p>\n</div>\n</div>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 3770, "s": 3720, "text": "The above code will create the following output −" } ]
Index Constructor in C# - GeeksforGeeks
28 Nov, 2019 Index(Int32, Boolean) constructor of Index Struct in C# 8.0 is used to initialize a new index with the specified index position and a value which shows whether the index starts from the start or the end of the collection or sequence. If the specified index created from the end, then the index value of 1 will point to the last element and the index value of 0 will point beyond the last element. Syntax: public Index (int Value, bool FromEnd = false); Here, Value is of index value and it is of System.Int32 type. The value of the index should be equal to or greater than zero. FromEnd is the boolean value which indicates that if the index starts from the start or from the end of the collection or sequence. Below codes executed on C# 8.0 or above versions: Example 1: // C# program to illustrate// the use of Index constructorusing System; namespace example { class GFG { static void Main(string[] args) { // Creating and initializing an array string[] greetings = new string[] {"Hello", "Hola", "Namaste", "Bonjour", "Ohayo", "Ahnyounghaseyo"}; // Creating new indexes // Using Index() constructor var val1 = new Index(1, true); var val2 = new Index(2, true); var val3 = new Index(3, true); var val4 = new Index(1, false); var val5 = new Index(2, false); var val6 = new Index(3, false); // Getting the values of // the specified indexes var res1 = greetings[val1]; var res2 = greetings[val2]; var res3 = greetings[val3]; var res4 = greetings[val4]; var res5 = greetings[val5]; var res6 = greetings[val6]; // Display indexes and their values Console.WriteLine("Index:{0} Value: {1}", val1, res1); Console.WriteLine("Index:{0} Value: {1}", val2, res2); Console.WriteLine("Index:{0} Value: {1}", val3, res3); Console.WriteLine("Index:{0} Value: {1}", val4, res4); Console.WriteLine("Index:{0} Value: {1}", val5, res5); Console.WriteLine("Index:{0} Value: {1}", val6, res6); }}} Output: Index:^1 Value: Ahnyounghaseyo Index:^2 Value: Ohayo Index:^3 Value: Bonjour Index:1 Value: Hola Index:2 Value: Namaste Index:3 Value: Bonjour Example 2: // C# program to illustrate // the use of Index constructorusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating new indexes // Using Index() constructor var val1 = new Index(1, true); var val2 = new Index(2, true); var val3 = new Index(1, false); var val4 = new Index(2, false); // Checking if the specified // index start from end or not var res1 = val1.IsFromEnd; var res2 = val2.IsFromEnd; var res3 = val3.IsFromEnd; var res4 = val4.IsFromEnd; // Display indexes and their values Console.WriteLine("Index:{0} Start from end?: {1}", val1, res1); Console.WriteLine("Index:{0} Start from end?: {1}", val2, res2); Console.WriteLine("Index:{0} Start from end?: {1}", val3, res3); Console.WriteLine("Index:{0} Start from end?: {1}", val4, res4); }}} Output: Index:^1 Start from end?: True Index:^2 Start from end?: True Index:1 Start from end?: False Index:2 Start from end?: False CSharp-8.0 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to calculate Electricity Bill Linked List Implementation in C# C# | How to insert an element in an Array? HashSet in C# with Examples Lambda Expressions in C# Main Method in C# Difference between Hashtable and Dictionary in C# C# | Dictionary.Add() Method Collections in C# Different Ways to Convert Char Array to String in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n28 Nov, 2019" }, { "code": null, "e": 24308, "s": 23911, "text": "Index(Int32, Boolean) constructor of Index Struct in C# 8.0 is used to initialize a new index with the specified index position and a value which shows whether the index starts from the start or the end of the collection or sequence. If the specified index created from the end, then the index value of 1 will point to the last element and the index value of 0 will point beyond the last element." }, { "code": null, "e": 24316, "s": 24308, "text": "Syntax:" }, { "code": null, "e": 24364, "s": 24316, "text": "public Index (int Value, bool FromEnd = false);" }, { "code": null, "e": 24672, "s": 24364, "text": "Here, Value is of index value and it is of System.Int32 type. The value of the index should be equal to or greater than zero. FromEnd is the boolean value which indicates that if the index starts from the start or from the end of the collection or sequence. Below codes executed on C# 8.0 or above versions:" }, { "code": null, "e": 24683, "s": 24672, "text": "Example 1:" }, { "code": "// C# program to illustrate// the use of Index constructorusing System; namespace example { class GFG { static void Main(string[] args) { // Creating and initializing an array string[] greetings = new string[] {\"Hello\", \"Hola\", \"Namaste\", \"Bonjour\", \"Ohayo\", \"Ahnyounghaseyo\"}; // Creating new indexes // Using Index() constructor var val1 = new Index(1, true); var val2 = new Index(2, true); var val3 = new Index(3, true); var val4 = new Index(1, false); var val5 = new Index(2, false); var val6 = new Index(3, false); // Getting the values of // the specified indexes var res1 = greetings[val1]; var res2 = greetings[val2]; var res3 = greetings[val3]; var res4 = greetings[val4]; var res5 = greetings[val5]; var res6 = greetings[val6]; // Display indexes and their values Console.WriteLine(\"Index:{0} Value: {1}\", val1, res1); Console.WriteLine(\"Index:{0} Value: {1}\", val2, res2); Console.WriteLine(\"Index:{0} Value: {1}\", val3, res3); Console.WriteLine(\"Index:{0} Value: {1}\", val4, res4); Console.WriteLine(\"Index:{0} Value: {1}\", val5, res5); Console.WriteLine(\"Index:{0} Value: {1}\", val6, res6); }}}", "e": 26018, "s": 24683, "text": null }, { "code": null, "e": 26026, "s": 26018, "text": "Output:" }, { "code": null, "e": 26170, "s": 26026, "text": "Index:^1 Value: Ahnyounghaseyo\nIndex:^2 Value: Ohayo\nIndex:^3 Value: Bonjour\nIndex:1 Value: Hola\nIndex:2 Value: Namaste\nIndex:3 Value: Bonjour\n" }, { "code": null, "e": 26181, "s": 26170, "text": "Example 2:" }, { "code": "// C# program to illustrate // the use of Index constructorusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating new indexes // Using Index() constructor var val1 = new Index(1, true); var val2 = new Index(2, true); var val3 = new Index(1, false); var val4 = new Index(2, false); // Checking if the specified // index start from end or not var res1 = val1.IsFromEnd; var res2 = val2.IsFromEnd; var res3 = val3.IsFromEnd; var res4 = val4.IsFromEnd; // Display indexes and their values Console.WriteLine(\"Index:{0} Start from end?: {1}\", val1, res1); Console.WriteLine(\"Index:{0} Start from end?: {1}\", val2, res2); Console.WriteLine(\"Index:{0} Start from end?: {1}\", val3, res3); Console.WriteLine(\"Index:{0} Start from end?: {1}\", val4, res4); }}}", "e": 27124, "s": 26181, "text": null }, { "code": null, "e": 27132, "s": 27124, "text": "Output:" }, { "code": null, "e": 27257, "s": 27132, "text": "Index:^1 Start from end?: True\nIndex:^2 Start from end?: True\nIndex:1 Start from end?: False\nIndex:2 Start from end?: False\n" }, { "code": null, "e": 27268, "s": 27257, "text": "CSharp-8.0" }, { "code": null, "e": 27271, "s": 27268, "text": "C#" }, { "code": null, "e": 27369, "s": 27271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27378, "s": 27369, "text": "Comments" }, { "code": null, "e": 27391, "s": 27378, "text": "Old Comments" }, { "code": null, "e": 27429, "s": 27391, "text": "Program to calculate Electricity Bill" }, { "code": null, "e": 27462, "s": 27429, "text": "Linked List Implementation in C#" }, { "code": null, "e": 27505, "s": 27462, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27533, "s": 27505, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27558, "s": 27533, "text": "Lambda Expressions in C#" }, { "code": null, "e": 27576, "s": 27558, "text": "Main Method in C#" }, { "code": null, "e": 27626, "s": 27576, "text": "Difference between Hashtable and Dictionary in C#" }, { "code": null, "e": 27655, "s": 27626, "text": "C# | Dictionary.Add() Method" }, { "code": null, "e": 27673, "s": 27655, "text": "Collections in C#" } ]
Python | Download YouTube videos using youtube_dl module
26 May, 2019 Each and every day, you must be watching some video or another on YouTube which may be related to Music, Movies, Studies, Research, Leisure etc. You might want to store some video for future use where it will be required due to lack of internet or saving data or any other reason. What if we tell you that you can do this exact very thing using Python. Let’s see how to download Youtube videos using youtube_dl module in Python. Install the module with this command – pip install youtube_dl Now, suppose you are watching this video on YouTube. Below is the Python code – # importing moduleimport youtube_dl ydl_opts = {} def dwl_vid(): with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([zxt]) channel = 1while (channel == int(1)): link_of_the_video = input("Copy & paste the URL of the YouTube video you want to download:- ") zxt = link_of_the_video.strip() dwl_vid() channel = int(input("Enter 1 if you want to download more videos \nEnter 0 if you are done ")) Output: And it’s done. The video you want gets downloaded in the Python folder. python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2019" }, { "code": null, "e": 335, "s": 54, "text": "Each and every day, you must be watching some video or another on YouTube which may be related to Music, Movies, Studies, Research, Leisure etc. You might want to store some video for future use where it will be required due to lack of internet or saving data or any other reason." }, { "code": null, "e": 483, "s": 335, "text": "What if we tell you that you can do this exact very thing using Python. Let’s see how to download Youtube videos using youtube_dl module in Python." }, { "code": null, "e": 522, "s": 483, "text": "Install the module with this command –" }, { "code": null, "e": 546, "s": 522, "text": "pip install youtube_dl\n" }, { "code": null, "e": 599, "s": 546, "text": "Now, suppose you are watching this video on YouTube." }, { "code": null, "e": 626, "s": 599, "text": "Below is the Python code –" }, { "code": "# importing moduleimport youtube_dl ydl_opts = {} def dwl_vid(): with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([zxt]) channel = 1while (channel == int(1)): link_of_the_video = input(\"Copy & paste the URL of the YouTube video you want to download:- \") zxt = link_of_the_video.strip() dwl_vid() channel = int(input(\"Enter 1 if you want to download more videos \\nEnter 0 if you are done \"))", "e": 1052, "s": 626, "text": null }, { "code": null, "e": 1060, "s": 1052, "text": "Output:" }, { "code": null, "e": 1132, "s": 1060, "text": "And it’s done. The video you want gets downloaded in the Python folder." }, { "code": null, "e": 1147, "s": 1132, "text": "python-utility" }, { "code": null, "e": 1154, "s": 1147, "text": "Python" } ]
Frequency Measuring Techniques for Competitive Programming - GeeksforGeeks
07 Jul, 2021 Measuring the frequency of elements in an array is a really handy skill and is required a lot of competitive coding problems. We, in a lot of problems, are required to measure the frequency of various elements like numbers, alphabets, symbols, etc. as a part of our problem. Naive method Examples: Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20} Output : 10 3 20 4 5 1 Input : arr[] = {10, 20, 20} Output : 10 2 20 1 We run two loops. For every item count number of times it occurs. To avoid duplicate printing, keep track of processed items. C++ Java Python3 C# Javascript // C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ // Mark all array elements as not visited vector<int> visited(n, false); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } cout << arr[i] << " " << count << endl; }} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;} // Java program to count frequencies// of array itemsimport java.util.*; class GFG{static void countFreq(int arr[], int n){ // Mark all array elements as not visited boolean []visited = new boolean[n]; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } System.out.println(arr[i] + " " + count); }} // Driver Codepublic static void main(String[] args){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; countFreq(arr, n);}} // This code is contributed by 29AjayKumar # Python program to count frequencies# of array itemsdef countFreq(arr, n): # mark all array elements as not visited visited = [False for i in range(n)] # Traverse through array elements # and count frequencies for i in range(n): # Skip this element if already processed if visited[i] == True: continue # count frequency count = 1 for j in range(i + 1, n): if arr[i] == arr[j]: visited[j] = True count += 1 print(arr[i], count) # Driver codea = [10, 20, 20, 10, 10, 20, 5, 20] n = len(a) countFreq(a, n) # This code is contributed# by Mohit kumar 29 // C# program to count frequencies// of array itemsusing System; class GFG{static void countFreq(int []arr, int n){ // Mark all array elements as not visited Boolean []visited = new Boolean[n]; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } Console.WriteLine(arr[i] + " " + count); }} // Driver Codepublic static void Main(String[] args){ int []arr = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n);}} // This code is contributed by Rajput-Ji <script> // Javascript program to count frequencies of array items function countFreq(arr, n) { // Mark all array elements as not visited let visited = new Array(n); visited.fill(false); // Traverse through array elements and // count frequencies for (let i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency let count = 1; for (let j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } document.write(arr[i] + " " + count + "</br>"); } } let arr = [ 10, 20, 20, 10, 10, 20, 5, 20 ]; let n = arr.length; countFreq(arr, n); // This code is contributed by mukesh07.</script> 10 3 20 4 5 1 Optimized methods : Measuring frequencies when elements are limited by value If our input array has small values, we can use array elements as index in a count array and increment count. In below example, elements are maximum 10. Input : arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10} limit = 10 Output : 1 1 2 1 3 1 5 3 6 3 10 2 C++ Java Python3 C# Javascript // C++ program to count frequencies of array items// having small values.#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n, int limit){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 vector<int> count(limit+1, 0); // Traverse through array elements and // count frequencies (assuming that elements // are limited by limit) for (int i = 0; i < n; i++) count[arr[i]]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) cout << i << " " << count[i] << endl; } int main(){ int arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10}; int n = sizeof(arr) / sizeof(arr[0]); int limit = 10; countFreq(arr, n, limit); return 0;} // Java program to count frequencies of array items// having small values.class GFG{ static void countFreq(int arr[], int n, int limit){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 int []count = new int[limit + 1]; // Traverse through array elements and // count frequencies (assuming that elements // are limited by limit) for (int i = 0; i < n; i++) count[arr[i]]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) System.out.println(i + " " + count[i]);} // Driver Codepublic static void main(String[] args){ int arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10}; int n = arr.length; int limit = 10; countFreq(arr, n, limit);}} // This code is contributed by PrinciRaj1992 # Python3 program to count frequencies of# array items having small values.def countFreq(arr, n, limit): # Create an array to store counts. # The size of array is limit+1 and # all values are initially 0 count = [0 for i in range(limit + 1)] # Traverse through array elements and # count frequencies (assuming that # elements are limited by limit) for i in range(n): count[arr[i]] += 1 for i in range(limit + 1): if (count[i] > 0): print(i, count[i]) # Driver Codearr = [ 5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10 ]n = len(arr)limit = 10 countFreq(arr, n, limit) # This code is contributed by avanitrachhadiya2155 // C# program to count frequencies of// array items having small values.using System; class GFG{ static void countFreq(int []arr, int n, int limit){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 int []count = new int[limit + 1]; // Traverse through array elements and // count frequencies (assuming that // elements are limited by limit) for (int i = 0; i < n; i++) count[arr[i]]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) Console.WriteLine(i + " " + count[i]);} // Driver Codepublic static void Main(String[] args){ int []arr = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10}; int n = arr.Length; int limit = 10; countFreq(arr, n, limit);}} // This code is contributed// by Princi Singh <script> // Javascript program to count frequencies// of array items having small values.function countFreq(arr, n, limit){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 let count = new Array(limit + 1); count.fill(0); // Traverse through array elements and // count frequencies (assuming that // elements are limited by limit) for(let i = 0; i < n; i++) count[arr[i]]++; for(let i = 0; i <= limit; i++) if (count[i] > 0) document.write(i + " " + count[i] + "</br>");} // Driver codelet arr = [ 5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10 ];let n = arr.length;let limit = 10; countFreq(arr, n, limit); // This code is contributed by rameshtravel07 </script> 1 1 2 1 3 1 5 3 6 3 10 2 C++ Java Python3 C# Javascript // C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; const int limit = 255; void countFreq(string str){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 vector<int> count(limit+1, 0); // Traverse through string characters and // count frequencies for (int i = 0; i < str.length(); i++) count[str[i]]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) cout << (char)i << " " << count[i] << endl; } int main(){ string str = "GeeksforGeeks"; countFreq(str); return 0;} // Java program to count frequencies of array itemsclass GFG{static int limit = 255; static void countFreq(String str){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 int []count= new int[limit + 1]; // Traverse through string characters and // count frequencies for (int i = 0; i < str.length(); i++) count[str.charAt(i)]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) System.out.println((char)i + " " + count[i]);} // Driver Codepublic static void main(String[] args){ String str = "GeeksforGeeks"; countFreq(str);}} // This code is contributed by PrinciRaj1992 # Python3 program to count frequencies of array itemslimit = 255def countFreq(Str) : # Create an array to store counts. The size # of array is limit+1 and all values are # initially 0 count = [0] * (limit + 1) # Traverse through string characters and # count frequencies for i in range(len(Str)) : count[ord(Str[i])] += 1 for i in range(limit + 1) : if (count[i] > 0) : print(chr(i), count[i]) Str = "GeeksforGeeks"countFreq(Str) # This code is contributed by divyeshrabadiya07 // C# program to count frequencies// of array itemsusing System; class GFG{static int limit = 25; static void countFreq(String str){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 int []count = new int[limit + 1]; // Traverse through string characters // and count frequencies for (int i = 0; i < str.Length; i++) count[str[i] - 'A']++; for (int i = 0; i <= limit; i++) if (count[i] > 0) Console.WriteLine((char)(i + 'A') + " " + count[i]);} // Driver Codepublic static void Main(String[] args){ String str = "GEEKSFORGEEKS"; countFreq(str);}} // This code is contributed by PrinciRaj1992 <script> // Javascript program to count frequencies of array items let limit = 255; function countFreq(str){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 let count= new Array(limit + 1); for(let i=0;i<count.length;i++) { count[i]=0; } // Traverse through string characters and // count frequencies for (let i = 0; i < str.length; i++) count[str[i].charCodeAt(0)]++; for (let i = 0; i <= limit; i++) { if (count[i] > 0) document.write(String.fromCharCode(i) + " " + count[i]+"<br>"); }} // Driver Codelet str = "GeeksforGeeks";countFreq(str); // This code is contributed by unknown2108</script> G 2 e 4 f 1 k 2 o 1 r 1 s 2 Measuring frequencies when elements are in limited range For example consider a string containing only upper case alphabets. Elements of string are limited in range from ‘A’ to ‘Z’. The idea is to subtract smallest element (‘A’ in this example) to get index of the element. C++ Java Python3 C# Javascript // C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; const int limit = 25; void countFreq(string str){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 vector<int> count(limit+1, 0); // Traverse through string characters and // count frequencies for (int i = 0; i < str.length(); i++) count[str[i] - 'A']++; for (int i = 0; i <= limit; i++) if (count[i] > 0) cout << (char)(i + 'A') << " " << count[i] << endl; } int main(){ string str = "GEEKSFORGEEKS"; countFreq(str); return 0;} // Java program to count frequencies// of array itemsimport java.util.*; class GFG{static int limit = 25; static void countFreq(String str){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 int []count = new int[limit + 1]; // Traverse through string characters // and count frequencies for (int i = 0; i < str.length(); i++) count[str.charAt(i) - 'A']++; for (int i = 0; i <= limit; i++) if (count[i] > 0) System.out.println((char)(i + 'A') + " " + count[i]);} // Driver Codepublic static void main(String[] args){ String str = "GEEKSFORGEEKS"; countFreq(str);}} // This code is contributed by PrinciRaj1992 # Python3 program to count frequencies of array itemslimit = 25;def countFreq(str): # Create an array to store counts. The size # of array is limit+1 and all values are # initially 0 count = [0 for i in range(limit + 1)] # Traverse through string characters and # count frequencies for i in range(len(str)): count[ord(str[i]) - ord('A')] += 1 for i in range(limit + 1): if (count[i] > 0): print(chr(i + ord('A')), count[i]) # Driver codeif __name__=='__main__': str = "GEEKSFORGEEKS"; countFreq(str); # This code is contributed by Pratham76 // C# program to count frequencies// of array itemsusing System; class GFG{static int limit = 25; static void countFreq(String str){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 int []count = new int[limit + 1]; // Traverse through string characters // and count frequencies for (int i = 0; i < str.Length; i++) count[str[i] - 'A']++; for (int i = 0; i <= limit; i++) if (count[i] > 0) Console.WriteLine((char)(i + 'A') + " " + count[i]);} // Driver Codepublic static void Main(String[] args){ String str = "GEEKSFORGEEKS"; countFreq(str);}} // This code contributed by PrinciRaj1992 <script> // JavaScript program to count frequencies// of array items let limit = 25;function countFreq(str){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 let count = new Array(limit + 1); for(let i=0;i<limit+1;i++) { count[i]=0; } // Traverse through string characters // and count frequencies for (let i = 0; i < str.length; i++) count[str[i].charCodeAt(0) - 'A'.charCodeAt(0)]++; for (let i = 0; i <= limit; i++) if (count[i] > 0) document.write(String.fromCharCode(i + 'A'.charCodeAt(0)) + " " + count[i]+"<br>");} // Driver Codelet str = "GEEKSFORGEEKS";countFreq(str); // This code is contributed by rag2127 </script> E 4 F 1 G 2 K 2 O 1 R 1 S 2 Measuring frequencies if no range and no limit The idea is to use hashing (unordered_map in C++ and HashMap in Java) to get frequencies. C++ Java Python3 C# Javascript // C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ unordered_map<int, int> mp; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse through map and print frequencies for (auto x : mp) cout << x.first << " " << x.second << endl;} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;} // Java program to count frequencies of array itemsimport java.util.*;class GFG{static void countFreq(int arr[], int n){ HashMap<Integer, Integer>mp = new HashMap<Integer, Integer>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } // Traverse through map and print frequencies for (Map.Entry<Integer, Integer> entry : mp.entrySet()) System.out.println(entry.getKey() + " " + entry.getValue());} // Driver Codepublic static void main(String[] args){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; countFreq(arr, n); }} // This code is contributed by 29AjayKumar # Python3 program to count frequencies of array itemsdef countFreq(arr, n): mp = {} # Traverse through array elements and # count frequencies for i in range(n): if arr[i] in mp: mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Traverse through map and print frequencies for x in sorted(mp): print(x, mp[x]) # Driver Codearr = [ 10, 20, 20, 10, 10, 20, 5, 20 ]n = len(arr) countFreq(arr, n) # This code is contributed by divyesh072019 // C# program to count frequencies of array itemsusing System;using System.Collections.Generic; class GFG{static void countFreq(int []arr, int n){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // Traverse through map and print frequencies foreach(KeyValuePair<int, int> entry in mp) Console.WriteLine(entry.Key + " " + entry.Value);} // Driver Codepublic static void Main(String[] args){ int []arr = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n);}} // This code is contributed by Princi Singh <script>// Javascript program to count frequencies of array itemsfunction countFreq(arr, n){ let mp = new Map(); // Traverse through array elements and // count frequencies for (let i = 0 ; i < n; i++) { if(mp.has(arr[i])) { mp.set(arr[i], mp.get(arr[i]) + 1); } else { mp.set(arr[i], 1); } } // Traverse through map and print frequencies for (let [key, value] of mp.entries()) document.write(key + " " + value+"<br>");} // Driver Codelet arr=[10, 20, 20, 10, 10, 20, 5, 20];let n = arr.length;countFreq(arr, n); // This code is contributed by ab2127</script> 5 1 10 3 20 4 Time Complexity : O(n) Auxiliary Space : O(n) In above efficient solution, how to print elements in same order as they appear in input? C++ Java Python3 C# Javascript // C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ unordered_map<int, int> mp; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) mp[arr[i]]++; // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp[arr[i]] != -1) { cout << arr[i] << " " << mp[arr[i]] << endl; mp[arr[i]] = -1; } }} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;} // Java program to count frequencies of array itemsimport java.util.*; class GFG{static void countFreq(int arr[], int n){ HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp.get(arr[i]) != -1) { System.out.println(arr[i] + " " + mp.get(arr[i])); mp. put(arr[i], -1); } }} // Driver Codepublic static void main(String[] args){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; countFreq(arr, n);}} // This code is contributed by Princi Singh # Python3 program to count frequencies of array itemsdef countFreq(arr, n): mp = {} # Traverse through array elements and # count frequencies for i in range(n): if arr[i] not in mp: mp[arr[i]] = 1 else: mp[arr[i]] += 1 # To print elements according to first # occurrence, traverse array one more time # print frequencies of elements and mark # frequencies as -1 so that same element # is not printed multiple times. for i in range(n): if(mp[arr[i]] != -1): print(arr[i], mp[arr[i]]) mp[arr[i]] = -1 # Driver codearr = [10, 20, 20, 10, 10, 20, 5, 20 ]n = len(arr)countFreq(arr, n) # This code is contributed by rag2127 // C# program to count frequencies of array itemsusing System;using System.Collections.Generic; class GFG{static void countFreq(int []arr, int n){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { mp[arr[i]] = mp[arr[i]] + 1; } else { mp.Add(arr[i], 1); } } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp[arr[i]] != -1) { Console.WriteLine(arr[i] + " " + mp[arr[i]]); mp[arr[i]] = - 1; } }} // Driver Codepublic static void Main(String[] args){ int []arr = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n);}} // This code is contributed by Rajput-Ji <script> // Javascript program to count// frequencies of array itemsfunction countFreq(arr, n){ let mp = new Map(); // Traverse through array elements and // count frequencies for(let i = 0 ; i < n; i++) { if (mp.has(arr[i])) { mp.set(arr[i], mp.get(arr[i]) + 1); } else { mp.set(arr[i], 1); } } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for(let i = 0; i < n; i++) { if (mp.get(arr[i]) != -1) { document.write(arr[i] + " " + mp.get(arr[i]) + "<br>"); mp.set(arr[i], -1); } }} // Driver Codelet arr = [ 10, 20, 20, 10, 10, 20, 5, 20 ];let n = arr.length; countFreq(arr, n); // This code is contributed by patel2127 </script> 10 3 20 4 5 1 Time Complexity : O(n) Auxiliary Space : O(n) In Java, we can get elements in same order using LinkedHashMap. Therefore we do not need an extra loop.Lot of problems are based on frequency measurement and will be a cheesecake if we know how to calculate frequency of various elements in a given array. For example try the given below problems which are based on frequency measurement: AnagramsSorting Elements of an Array by FrequencySingle Number Anagrams Sorting Elements of an Array by Frequency Single Number This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. mohit kumar 29 29AjayKumar Rajput-Ji princiraj1992 princi singh rag2127 avanitrachhadiya2155 divyeshrabadiya07 divyesh072019 pratham76 mukesh07 rameshtravel07 unknown2108 ab2127 patel2127 cpp-unordered_map frequency-counting Arrays Competitive Programming Hash Strings Technical Scripter Arrays Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Competitive Programming - A Complete Guide Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics)
[ { "code": null, "e": 25132, "s": 25104, "text": "\n07 Jul, 2021" }, { "code": null, "e": 25407, "s": 25132, "text": "Measuring the frequency of elements in an array is a really handy skill and is required a lot of competitive coding problems. We, in a lot of problems, are required to measure the frequency of various elements like numbers, alphabets, symbols, etc. as a part of our problem." }, { "code": null, "e": 25420, "s": 25407, "text": "Naive method" }, { "code": null, "e": 25432, "s": 25420, "text": "Examples: " }, { "code": null, "e": 25581, "s": 25432, "text": "Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}\nOutput : 10 3\n 20 4\n 5 1\n\nInput : arr[] = {10, 20, 20}\nOutput : 10 2\n 20 1" }, { "code": null, "e": 25708, "s": 25581, "text": "We run two loops. For every item count number of times it occurs. To avoid duplicate printing, keep track of processed items. " }, { "code": null, "e": 25712, "s": 25708, "text": "C++" }, { "code": null, "e": 25717, "s": 25712, "text": "Java" }, { "code": null, "e": 25725, "s": 25717, "text": "Python3" }, { "code": null, "e": 25728, "s": 25725, "text": "C#" }, { "code": null, "e": 25739, "s": 25728, "text": "Javascript" }, { "code": "// C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ // Mark all array elements as not visited vector<int> visited(n, false); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } cout << arr[i] << \" \" << count << endl; }} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;}", "e": 26551, "s": 25739, "text": null }, { "code": "// Java program to count frequencies// of array itemsimport java.util.*; class GFG{static void countFreq(int arr[], int n){ // Mark all array elements as not visited boolean []visited = new boolean[n]; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } System.out.println(arr[i] + \" \" + count); }} // Driver Codepublic static void main(String[] args){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; countFreq(arr, n);}} // This code is contributed by 29AjayKumar", "e": 27436, "s": 26551, "text": null }, { "code": "# Python program to count frequencies# of array itemsdef countFreq(arr, n): # mark all array elements as not visited visited = [False for i in range(n)] # Traverse through array elements # and count frequencies for i in range(n): # Skip this element if already processed if visited[i] == True: continue # count frequency count = 1 for j in range(i + 1, n): if arr[i] == arr[j]: visited[j] = True count += 1 print(arr[i], count) # Driver codea = [10, 20, 20, 10, 10, 20, 5, 20] n = len(a) countFreq(a, n) # This code is contributed# by Mohit kumar 29", "e": 28140, "s": 27436, "text": null }, { "code": "// C# program to count frequencies// of array itemsusing System; class GFG{static void countFreq(int []arr, int n){ // Mark all array elements as not visited Boolean []visited = new Boolean[n]; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } Console.WriteLine(arr[i] + \" \" + count); }} // Driver Codepublic static void Main(String[] args){ int []arr = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n);}} // This code is contributed by Rajput-Ji", "e": 29035, "s": 28140, "text": null }, { "code": "<script> // Javascript program to count frequencies of array items function countFreq(arr, n) { // Mark all array elements as not visited let visited = new Array(n); visited.fill(false); // Traverse through array elements and // count frequencies for (let i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency let count = 1; for (let j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } document.write(arr[i] + \" \" + count + \"</br>\"); } } let arr = [ 10, 20, 20, 10, 10, 20, 5, 20 ]; let n = arr.length; countFreq(arr, n); // This code is contributed by mukesh07.</script>", "e": 29945, "s": 29035, "text": null }, { "code": null, "e": 29959, "s": 29945, "text": "10 3\n20 4\n5 1" }, { "code": null, "e": 29981, "s": 29961, "text": "Optimized methods :" }, { "code": null, "e": 30192, "s": 29981, "text": "Measuring frequencies when elements are limited by value If our input array has small values, we can use array elements as index in a count array and increment count. In below example, elements are maximum 10. " }, { "code": null, "e": 30344, "s": 30192, "text": "Input : arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10}\n limit = 10\nOutput : 1 1\n 2 1\n 3 1\n 5 3\n 6 3\n 10 2" }, { "code": null, "e": 30348, "s": 30344, "text": "C++" }, { "code": null, "e": 30353, "s": 30348, "text": "Java" }, { "code": null, "e": 30361, "s": 30353, "text": "Python3" }, { "code": null, "e": 30364, "s": 30361, "text": "C#" }, { "code": null, "e": 30375, "s": 30364, "text": "Javascript" }, { "code": "// C++ program to count frequencies of array items// having small values.#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n, int limit){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 vector<int> count(limit+1, 0); // Traverse through array elements and // count frequencies (assuming that elements // are limited by limit) for (int i = 0; i < n; i++) count[arr[i]]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) cout << i << \" \" << count[i] << endl; } int main(){ int arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10}; int n = sizeof(arr) / sizeof(arr[0]); int limit = 10; countFreq(arr, n, limit); return 0;}", "e": 31140, "s": 30375, "text": null }, { "code": "// Java program to count frequencies of array items// having small values.class GFG{ static void countFreq(int arr[], int n, int limit){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 int []count = new int[limit + 1]; // Traverse through array elements and // count frequencies (assuming that elements // are limited by limit) for (int i = 0; i < n; i++) count[arr[i]]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) System.out.println(i + \" \" + count[i]);} // Driver Codepublic static void main(String[] args){ int arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10}; int n = arr.length; int limit = 10; countFreq(arr, n, limit);}} // This code is contributed by PrinciRaj1992", "e": 31937, "s": 31140, "text": null }, { "code": "# Python3 program to count frequencies of# array items having small values.def countFreq(arr, n, limit): # Create an array to store counts. # The size of array is limit+1 and # all values are initially 0 count = [0 for i in range(limit + 1)] # Traverse through array elements and # count frequencies (assuming that # elements are limited by limit) for i in range(n): count[arr[i]] += 1 for i in range(limit + 1): if (count[i] > 0): print(i, count[i]) # Driver Codearr = [ 5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10 ]n = len(arr)limit = 10 countFreq(arr, n, limit) # This code is contributed by avanitrachhadiya2155", "e": 32609, "s": 31937, "text": null }, { "code": "// C# program to count frequencies of// array items having small values.using System; class GFG{ static void countFreq(int []arr, int n, int limit){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 int []count = new int[limit + 1]; // Traverse through array elements and // count frequencies (assuming that // elements are limited by limit) for (int i = 0; i < n; i++) count[arr[i]]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) Console.WriteLine(i + \" \" + count[i]);} // Driver Codepublic static void Main(String[] args){ int []arr = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10}; int n = arr.Length; int limit = 10; countFreq(arr, n, limit);}} // This code is contributed// by Princi Singh", "e": 33488, "s": 32609, "text": null }, { "code": "<script> // Javascript program to count frequencies// of array items having small values.function countFreq(arr, n, limit){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 let count = new Array(limit + 1); count.fill(0); // Traverse through array elements and // count frequencies (assuming that // elements are limited by limit) for(let i = 0; i < n; i++) count[arr[i]]++; for(let i = 0; i <= limit; i++) if (count[i] > 0) document.write(i + \" \" + count[i] + \"</br>\");} // Driver codelet arr = [ 5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10 ];let n = arr.length;let limit = 10; countFreq(arr, n, limit); // This code is contributed by rameshtravel07 </script>", "e": 34293, "s": 33488, "text": null }, { "code": null, "e": 34318, "s": 34293, "text": "1 1\n2 1\n3 1\n5 3\n6 3\n10 2" }, { "code": null, "e": 34324, "s": 34320, "text": "C++" }, { "code": null, "e": 34329, "s": 34324, "text": "Java" }, { "code": null, "e": 34337, "s": 34329, "text": "Python3" }, { "code": null, "e": 34340, "s": 34337, "text": "C#" }, { "code": null, "e": 34351, "s": 34340, "text": "Javascript" }, { "code": "// C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; const int limit = 255; void countFreq(string str){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 vector<int> count(limit+1, 0); // Traverse through string characters and // count frequencies for (int i = 0; i < str.length(); i++) count[str[i]]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) cout << (char)i << \" \" << count[i] << endl; } int main(){ string str = \"GeeksforGeeks\"; countFreq(str); return 0;}", "e": 34977, "s": 34351, "text": null }, { "code": "// Java program to count frequencies of array itemsclass GFG{static int limit = 255; static void countFreq(String str){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 int []count= new int[limit + 1]; // Traverse through string characters and // count frequencies for (int i = 0; i < str.length(); i++) count[str.charAt(i)]++; for (int i = 0; i <= limit; i++) if (count[i] > 0) System.out.println((char)i + \" \" + count[i]);} // Driver Codepublic static void main(String[] args){ String str = \"GeeksforGeeks\"; countFreq(str);}} // This code is contributed by PrinciRaj1992", "e": 35652, "s": 34977, "text": null }, { "code": "# Python3 program to count frequencies of array itemslimit = 255def countFreq(Str) : # Create an array to store counts. The size # of array is limit+1 and all values are # initially 0 count = [0] * (limit + 1) # Traverse through string characters and # count frequencies for i in range(len(Str)) : count[ord(Str[i])] += 1 for i in range(limit + 1) : if (count[i] > 0) : print(chr(i), count[i]) Str = \"GeeksforGeeks\"countFreq(Str) # This code is contributed by divyeshrabadiya07", "e": 36182, "s": 35652, "text": null }, { "code": "// C# program to count frequencies// of array itemsusing System; class GFG{static int limit = 25; static void countFreq(String str){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 int []count = new int[limit + 1]; // Traverse through string characters // and count frequencies for (int i = 0; i < str.Length; i++) count[str[i] - 'A']++; for (int i = 0; i <= limit; i++) if (count[i] > 0) Console.WriteLine((char)(i + 'A') + \" \" + count[i]);} // Driver Codepublic static void Main(String[] args){ String str = \"GEEKSFORGEEKS\"; countFreq(str);}} // This code is contributed by PrinciRaj1992", "e": 36904, "s": 36182, "text": null }, { "code": "<script> // Javascript program to count frequencies of array items let limit = 255; function countFreq(str){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 let count= new Array(limit + 1); for(let i=0;i<count.length;i++) { count[i]=0; } // Traverse through string characters and // count frequencies for (let i = 0; i < str.length; i++) count[str[i].charCodeAt(0)]++; for (let i = 0; i <= limit; i++) { if (count[i] > 0) document.write(String.fromCharCode(i) + \" \" + count[i]+\"<br>\"); }} // Driver Codelet str = \"GeeksforGeeks\";countFreq(str); // This code is contributed by unknown2108</script>", "e": 37655, "s": 36904, "text": null }, { "code": null, "e": 37683, "s": 37655, "text": "G 2\ne 4\nf 1\nk 2\no 1\nr 1\ns 2" }, { "code": null, "e": 37960, "s": 37685, "text": "Measuring frequencies when elements are in limited range For example consider a string containing only upper case alphabets. Elements of string are limited in range from ‘A’ to ‘Z’. The idea is to subtract smallest element (‘A’ in this example) to get index of the element. " }, { "code": null, "e": 37964, "s": 37960, "text": "C++" }, { "code": null, "e": 37969, "s": 37964, "text": "Java" }, { "code": null, "e": 37977, "s": 37969, "text": "Python3" }, { "code": null, "e": 37980, "s": 37977, "text": "C#" }, { "code": null, "e": 37991, "s": 37980, "text": "Javascript" }, { "code": "// C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; const int limit = 25; void countFreq(string str){ // Create an array to store counts. The size // of array is limit+1 and all values are // initially 0 vector<int> count(limit+1, 0); // Traverse through string characters and // count frequencies for (int i = 0; i < str.length(); i++) count[str[i] - 'A']++; for (int i = 0; i <= limit; i++) if (count[i] > 0) cout << (char)(i + 'A') << \" \" << count[i] << endl; } int main(){ string str = \"GEEKSFORGEEKS\"; countFreq(str); return 0;}", "e": 38630, "s": 37991, "text": null }, { "code": "// Java program to count frequencies// of array itemsimport java.util.*; class GFG{static int limit = 25; static void countFreq(String str){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 int []count = new int[limit + 1]; // Traverse through string characters // and count frequencies for (int i = 0; i < str.length(); i++) count[str.charAt(i) - 'A']++; for (int i = 0; i <= limit; i++) if (count[i] > 0) System.out.println((char)(i + 'A') + \" \" + count[i]);} // Driver Codepublic static void main(String[] args){ String str = \"GEEKSFORGEEKS\"; countFreq(str);}} // This code is contributed by PrinciRaj1992", "e": 39367, "s": 38630, "text": null }, { "code": "# Python3 program to count frequencies of array itemslimit = 25;def countFreq(str): # Create an array to store counts. The size # of array is limit+1 and all values are # initially 0 count = [0 for i in range(limit + 1)] # Traverse through string characters and # count frequencies for i in range(len(str)): count[ord(str[i]) - ord('A')] += 1 for i in range(limit + 1): if (count[i] > 0): print(chr(i + ord('A')), count[i]) # Driver codeif __name__=='__main__': str = \"GEEKSFORGEEKS\"; countFreq(str); # This code is contributed by Pratham76", "e": 39983, "s": 39367, "text": null }, { "code": "// C# program to count frequencies// of array itemsusing System; class GFG{static int limit = 25; static void countFreq(String str){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 int []count = new int[limit + 1]; // Traverse through string characters // and count frequencies for (int i = 0; i < str.Length; i++) count[str[i] - 'A']++; for (int i = 0; i <= limit; i++) if (count[i] > 0) Console.WriteLine((char)(i + 'A') + \" \" + count[i]);} // Driver Codepublic static void Main(String[] args){ String str = \"GEEKSFORGEEKS\"; countFreq(str);}} // This code contributed by PrinciRaj1992", "e": 40708, "s": 39983, "text": null }, { "code": "<script> // JavaScript program to count frequencies// of array items let limit = 25;function countFreq(str){ // Create an array to store counts. // The size of array is limit+1 and // all values are initially 0 let count = new Array(limit + 1); for(let i=0;i<limit+1;i++) { count[i]=0; } // Traverse through string characters // and count frequencies for (let i = 0; i < str.length; i++) count[str[i].charCodeAt(0) - 'A'.charCodeAt(0)]++; for (let i = 0; i <= limit; i++) if (count[i] > 0) document.write(String.fromCharCode(i + 'A'.charCodeAt(0)) + \" \" + count[i]+\"<br>\");} // Driver Codelet str = \"GEEKSFORGEEKS\";countFreq(str); // This code is contributed by rag2127 </script>", "e": 41475, "s": 40708, "text": null }, { "code": null, "e": 41503, "s": 41475, "text": "E 4\nF 1\nG 2\nK 2\nO 1\nR 1\nS 2" }, { "code": null, "e": 41643, "s": 41505, "text": "Measuring frequencies if no range and no limit The idea is to use hashing (unordered_map in C++ and HashMap in Java) to get frequencies. " }, { "code": null, "e": 41647, "s": 41643, "text": "C++" }, { "code": null, "e": 41652, "s": 41647, "text": "Java" }, { "code": null, "e": 41660, "s": 41652, "text": "Python3" }, { "code": null, "e": 41663, "s": 41660, "text": "C#" }, { "code": null, "e": 41674, "s": 41663, "text": "Javascript" }, { "code": "// C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ unordered_map<int, int> mp; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse through map and print frequencies for (auto x : mp) cout << x.first << \" \" << x.second << endl;} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;}", "e": 42215, "s": 41674, "text": null }, { "code": "// Java program to count frequencies of array itemsimport java.util.*;class GFG{static void countFreq(int arr[], int n){ HashMap<Integer, Integer>mp = new HashMap<Integer, Integer>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } // Traverse through map and print frequencies for (Map.Entry<Integer, Integer> entry : mp.entrySet()) System.out.println(entry.getKey() + \" \" + entry.getValue());} // Driver Codepublic static void main(String[] args){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; countFreq(arr, n); }} // This code is contributed by 29AjayKumar", "e": 43177, "s": 42215, "text": null }, { "code": "# Python3 program to count frequencies of array itemsdef countFreq(arr, n): mp = {} # Traverse through array elements and # count frequencies for i in range(n): if arr[i] in mp: mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Traverse through map and print frequencies for x in sorted(mp): print(x, mp[x]) # Driver Codearr = [ 10, 20, 20, 10, 10, 20, 5, 20 ]n = len(arr) countFreq(arr, n) # This code is contributed by divyesh072019", "e": 43667, "s": 43177, "text": null }, { "code": "// C# program to count frequencies of array itemsusing System;using System.Collections.Generic; class GFG{static void countFreq(int []arr, int n){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } // Traverse through map and print frequencies foreach(KeyValuePair<int, int> entry in mp) Console.WriteLine(entry.Key + \" \" + entry.Value);} // Driver Codepublic static void Main(String[] args){ int []arr = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n);}} // This code is contributed by Princi Singh", "e": 44676, "s": 43667, "text": null }, { "code": "<script>// Javascript program to count frequencies of array itemsfunction countFreq(arr, n){ let mp = new Map(); // Traverse through array elements and // count frequencies for (let i = 0 ; i < n; i++) { if(mp.has(arr[i])) { mp.set(arr[i], mp.get(arr[i]) + 1); } else { mp.set(arr[i], 1); } } // Traverse through map and print frequencies for (let [key, value] of mp.entries()) document.write(key + \" \" + value+\"<br>\");} // Driver Codelet arr=[10, 20, 20, 10, 10, 20, 5, 20];let n = arr.length;countFreq(arr, n); // This code is contributed by ab2127</script>", "e": 45405, "s": 44676, "text": null }, { "code": null, "e": 45419, "s": 45405, "text": "5 1\n10 3\n20 4" }, { "code": null, "e": 45467, "s": 45421, "text": "Time Complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 45559, "s": 45467, "text": "In above efficient solution, how to print elements in same order as they appear in input? " }, { "code": null, "e": 45563, "s": 45559, "text": "C++" }, { "code": null, "e": 45568, "s": 45563, "text": "Java" }, { "code": null, "e": 45576, "s": 45568, "text": "Python3" }, { "code": null, "e": 45579, "s": 45576, "text": "C#" }, { "code": null, "e": 45590, "s": 45579, "text": "Javascript" }, { "code": "// C++ program to count frequencies of array items#include <bits/stdc++.h>using namespace std; void countFreq(int arr[], int n){ unordered_map<int, int> mp; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) mp[arr[i]]++; // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp[arr[i]] != -1) { cout << arr[i] << \" \" << mp[arr[i]] << endl; mp[arr[i]] = -1; } }} int main(){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0;}", "e": 46386, "s": 45590, "text": null }, { "code": "// Java program to count frequencies of array itemsimport java.util.*; class GFG{static void countFreq(int arr[], int n){ HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp.get(arr[i]) != -1) { System.out.println(arr[i] + \" \" + mp.get(arr[i])); mp. put(arr[i], -1); } }} // Driver Codepublic static void main(String[] args){ int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; countFreq(arr, n);}} // This code is contributed by Princi Singh", "e": 47525, "s": 46386, "text": null }, { "code": "# Python3 program to count frequencies of array itemsdef countFreq(arr, n): mp = {} # Traverse through array elements and # count frequencies for i in range(n): if arr[i] not in mp: mp[arr[i]] = 1 else: mp[arr[i]] += 1 # To print elements according to first # occurrence, traverse array one more time # print frequencies of elements and mark # frequencies as -1 so that same element # is not printed multiple times. for i in range(n): if(mp[arr[i]] != -1): print(arr[i], mp[arr[i]]) mp[arr[i]] = -1 # Driver codearr = [10, 20, 20, 10, 10, 20, 5, 20 ]n = len(arr)countFreq(arr, n) # This code is contributed by rag2127", "e": 48244, "s": 47525, "text": null }, { "code": "// C# program to count frequencies of array itemsusing System;using System.Collections.Generic; class GFG{static void countFreq(int []arr, int n){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Traverse through array elements and // count frequencies for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(arr[i])) { mp[arr[i]] = mp[arr[i]] + 1; } else { mp.Add(arr[i], 1); } } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for (int i = 0; i < n; i++) { if (mp[arr[i]] != -1) { Console.WriteLine(arr[i] + \" \" + mp[arr[i]]); mp[arr[i]] = - 1; } }} // Driver Codepublic static void Main(String[] args){ int []arr = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n);}} // This code is contributed by Rajput-Ji", "e": 49401, "s": 48244, "text": null }, { "code": "<script> // Javascript program to count// frequencies of array itemsfunction countFreq(arr, n){ let mp = new Map(); // Traverse through array elements and // count frequencies for(let i = 0 ; i < n; i++) { if (mp.has(arr[i])) { mp.set(arr[i], mp.get(arr[i]) + 1); } else { mp.set(arr[i], 1); } } // To print elements according to first // occurrence, traverse array one more time // print frequencies of elements and mark // frequencies as -1 so that same element // is not printed multiple times. for(let i = 0; i < n; i++) { if (mp.get(arr[i]) != -1) { document.write(arr[i] + \" \" + mp.get(arr[i]) + \"<br>\"); mp.set(arr[i], -1); } }} // Driver Codelet arr = [ 10, 20, 20, 10, 10, 20, 5, 20 ];let n = arr.length; countFreq(arr, n); // This code is contributed by patel2127 </script>", "e": 50364, "s": 49401, "text": null }, { "code": null, "e": 50378, "s": 50364, "text": "10 3\n20 4\n5 1" }, { "code": null, "e": 50426, "s": 50380, "text": "Time Complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 50765, "s": 50426, "text": "In Java, we can get elements in same order using LinkedHashMap. Therefore we do not need an extra loop.Lot of problems are based on frequency measurement and will be a cheesecake if we know how to calculate frequency of various elements in a given array. For example try the given below problems which are based on frequency measurement: " }, { "code": null, "e": 50828, "s": 50765, "text": "AnagramsSorting Elements of an Array by FrequencySingle Number" }, { "code": null, "e": 50837, "s": 50828, "text": "Anagrams" }, { "code": null, "e": 50879, "s": 50837, "text": "Sorting Elements of an Array by Frequency" }, { "code": null, "e": 50893, "s": 50879, "text": "Single Number" }, { "code": null, "e": 51314, "s": 50893, "text": "This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 51329, "s": 51314, "text": "mohit kumar 29" }, { "code": null, "e": 51341, "s": 51329, "text": "29AjayKumar" }, { "code": null, "e": 51351, "s": 51341, "text": "Rajput-Ji" }, { "code": null, "e": 51365, "s": 51351, "text": "princiraj1992" }, { "code": null, "e": 51378, "s": 51365, "text": "princi singh" }, { "code": null, "e": 51386, "s": 51378, "text": "rag2127" }, { "code": null, "e": 51407, "s": 51386, "text": "avanitrachhadiya2155" }, { "code": null, "e": 51425, "s": 51407, "text": "divyeshrabadiya07" }, { "code": null, "e": 51439, "s": 51425, "text": "divyesh072019" }, { "code": null, "e": 51449, "s": 51439, "text": "pratham76" }, { "code": null, "e": 51458, "s": 51449, "text": "mukesh07" }, { "code": null, "e": 51473, "s": 51458, "text": "rameshtravel07" }, { "code": null, "e": 51485, "s": 51473, "text": "unknown2108" }, { "code": null, "e": 51492, "s": 51485, "text": "ab2127" }, { "code": null, "e": 51502, "s": 51492, "text": "patel2127" }, { "code": null, "e": 51520, "s": 51502, "text": "cpp-unordered_map" }, { "code": null, "e": 51539, "s": 51520, "text": "frequency-counting" }, { "code": null, "e": 51546, "s": 51539, "text": "Arrays" }, { "code": null, "e": 51570, "s": 51546, "text": "Competitive Programming" }, { "code": null, "e": 51575, "s": 51570, "text": "Hash" }, { "code": null, "e": 51583, "s": 51575, "text": "Strings" }, { "code": null, "e": 51602, "s": 51583, "text": "Technical Scripter" }, { "code": null, "e": 51609, "s": 51602, "text": "Arrays" }, { "code": null, "e": 51614, "s": 51609, "text": "Hash" }, { "code": null, "e": 51622, "s": 51614, "text": "Strings" }, { "code": null, "e": 51720, "s": 51622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51768, "s": 51720, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 51812, "s": 51768, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 51844, "s": 51812, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 51867, "s": 51844, "text": "Introduction to Arrays" }, { "code": null, "e": 51881, "s": 51867, "text": "Linear Search" }, { "code": null, "e": 51924, "s": 51881, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 51965, "s": 51924, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 51992, "s": 51965, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 52070, "s": 51992, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
How to list all the Collections in a MongoDB database using Java?
You can print a list of all the existing collections in a database using show collections. Assume we have created 3 collections in a MongoDB database as shown below − > use sampleDatabase switched to db sampleDatabase > db.createCollection("students") { "ok" : 1 } > db.createCollection("teachers") { "ok" : 1 } > db.createCollection("sample") { "ok" : 1 } Following query lists all the collections in the database − > use sampleDatabase switched to db sampleDatabase > show collections sample students teachers In Java, you can get the names of all collections in the current database using the listCollectionNames() method of the com.mongodb.client.MongoCollection interface. Therefore to list all the collections in a database in MongoDB using Java program − Make sure you have installed MongoDB in your system Make sure you have installed MongoDB in your system Add the following dependency to its pom.xml file of your Java project. Add the following dependency to its pom.xml file of your Java project. <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.2</version> </dependency> Create a MongoDB client by instantiating the MongoClient class. Create a MongoDB client by instantiating the MongoClient class. Connect to a database using the getDatabase() method. Connect to a database using the getDatabase() method. Get the list of the collections using the listCollectionNames() method. Get the list of the collections using the listCollectionNames() method. import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; import com.mongodb.MongoClient; public class ListOfCollection { public static void main( String args[] ) { // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); //Connecting to the database MongoDatabase database = mongo.getDatabase("mydatabase"); //Creating multiple collections database.createCollection("sampleCollection1"); database.createCollection("sampleCollection2"); database.createCollection("sampleCollection3"); database.createCollection("sampleCollection4"); //Retrieving the list of collections MongoIterable<String> list = database.listCollectionNames(); for (String name : list) { System.out.println(name); } } } sampleCollection3 sampleCollection2 sampleCollection4 sampleCollection1
[ { "code": null, "e": 1153, "s": 1062, "text": "You can print a list of all the existing collections in a database using show collections." }, { "code": null, "e": 1229, "s": 1153, "text": "Assume we have created 3 collections in a MongoDB database as shown below −" }, { "code": null, "e": 1419, "s": 1229, "text": "> use sampleDatabase\nswitched to db sampleDatabase\n> db.createCollection(\"students\")\n{ \"ok\" : 1 }\n> db.createCollection(\"teachers\")\n{ \"ok\" : 1 }\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }" }, { "code": null, "e": 1479, "s": 1419, "text": "Following query lists all the collections in the database −" }, { "code": null, "e": 1574, "s": 1479, "text": "> use sampleDatabase\nswitched to db sampleDatabase\n> show collections\nsample\nstudents\nteachers" }, { "code": null, "e": 1740, "s": 1574, "text": "In Java, you can get the names of all collections in the current database using the listCollectionNames() method of the com.mongodb.client.MongoCollection\ninterface." }, { "code": null, "e": 1824, "s": 1740, "text": "Therefore to list all the collections in a database in MongoDB using Java program −" }, { "code": null, "e": 1876, "s": 1824, "text": "Make sure you have installed MongoDB in your system" }, { "code": null, "e": 1928, "s": 1876, "text": "Make sure you have installed MongoDB in your system" }, { "code": null, "e": 1999, "s": 1928, "text": "Add the following dependency to its pom.xml file of your Java project." }, { "code": null, "e": 2070, "s": 1999, "text": "Add the following dependency to its pom.xml file of your Java project." }, { "code": null, "e": 2206, "s": 2070, "text": "<dependency>\n <groupId>org.mongodb</groupId>\n <artifactId>mongo-java-driver</artifactId>\n <version>3.12.2</version>\n</dependency>" }, { "code": null, "e": 2270, "s": 2206, "text": "Create a MongoDB client by instantiating the MongoClient class." }, { "code": null, "e": 2334, "s": 2270, "text": "Create a MongoDB client by instantiating the MongoClient class." }, { "code": null, "e": 2388, "s": 2334, "text": "Connect to a database using the getDatabase() method." }, { "code": null, "e": 2442, "s": 2388, "text": "Connect to a database using the getDatabase() method." }, { "code": null, "e": 2514, "s": 2442, "text": "Get the list of the collections using the listCollectionNames() method." }, { "code": null, "e": 2586, "s": 2514, "text": "Get the list of the collections using the listCollectionNames() method." }, { "code": null, "e": 3423, "s": 2586, "text": "import com.mongodb.client.MongoDatabase;\nimport com.mongodb.client.MongoIterable;\nimport com.mongodb.MongoClient;\npublic class ListOfCollection {\n public static void main( String args[] ) {\n // Creating a Mongo client\n MongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n //Connecting to the database\n MongoDatabase database = mongo.getDatabase(\"mydatabase\");\n //Creating multiple collections\n database.createCollection(\"sampleCollection1\");\n database.createCollection(\"sampleCollection2\");\n database.createCollection(\"sampleCollection3\");\n database.createCollection(\"sampleCollection4\");\n //Retrieving the list of collections\n MongoIterable<String> list = database.listCollectionNames();\n for (String name : list) {\n System.out.println(name);\n }\n }\n}" }, { "code": null, "e": 3495, "s": 3423, "text": "sampleCollection3\nsampleCollection2\nsampleCollection4\nsampleCollection1" } ]
How to create a scatterplot using ggplot2 with different shape and color of points based on a variable in R?
In general, the default shape of points in a scatterplot is circular but it can be changed to other shapes using integers or sequence or the variable. We just need to use the argument shape inside geom_point function and pass the variable name. For example, if we want to create the scatterplot with varying shapes of a variable x then we can use geom_point(shape=x). And if we want to change the size then integer values can be used. Consider the below data frame − Live Demo set.seed(151) x<-rnorm(20,5,1) y<-rnorm(20,5,2) df<-data.frame(x,y) df x y 1 4.948461 2.255857 2 5.765737 1.726474 3 4.853260 4.280697 4 4.886814 7.402230 5 4.604489 3.708252 6 5.782276 3.978782 7 3.602522 3.801754 8 3.981162 6.091206 9 5.229476 4.017412 10 5.672173 5.383071 11 4.515448 3.882945 12 5.560609 6.845399 13 5.066156 7.307996 14 3.650124 2.255179 15 4.757084 7.580363 16 3.763259 7.309804 17 3.525322 7.891359 18 7.437159 5.522026 19 5.673526 8.858292 20 5.310040 3.800228 Loading ggplot2 package and creating point chart between x and y − library(ggplot2) ggplot(df,aes(x,y))+geom_point() Creating the scatterplot by different shape of the points and the size = 3 − ggplot(df,aes(x,y))+geom_point(shape=x,color=x,size=3)
[ { "code": null, "e": 1497, "s": 1062, "text": "In general, the default shape of points in a scatterplot is circular but it can be changed to other shapes using integers or sequence or the variable. We just need to use the argument shape inside geom_point function and pass the variable name. For example, if we want to create the scatterplot with varying shapes of a variable x then we can use geom_point(shape=x). And if we want to change the size then integer values can be used." }, { "code": null, "e": 1529, "s": 1497, "text": "Consider the below data frame −" }, { "code": null, "e": 1540, "s": 1529, "text": " Live Demo" }, { "code": null, "e": 1611, "s": 1540, "text": "set.seed(151)\nx<-rnorm(20,5,1)\ny<-rnorm(20,5,2)\ndf<-data.frame(x,y)\ndf" }, { "code": null, "e": 2038, "s": 1611, "text": " x y\n1 4.948461 2.255857\n2 5.765737 1.726474\n3 4.853260 4.280697\n4 4.886814 7.402230\n5 4.604489 3.708252\n6 5.782276 3.978782\n7 3.602522 3.801754\n8 3.981162 6.091206\n9 5.229476 4.017412\n10 5.672173 5.383071\n11 4.515448 3.882945\n12 5.560609 6.845399\n13 5.066156 7.307996\n14 3.650124 2.255179\n15 4.757084 7.580363\n16 3.763259 7.309804\n17 3.525322 7.891359\n18 7.437159 5.522026\n19 5.673526 8.858292\n20 5.310040 3.800228" }, { "code": null, "e": 2105, "s": 2038, "text": "Loading ggplot2 package and creating point chart between x and y −" }, { "code": null, "e": 2155, "s": 2105, "text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_point()" }, { "code": null, "e": 2232, "s": 2155, "text": "Creating the scatterplot by different shape of the points and the size = 3 −" }, { "code": null, "e": 2287, "s": 2232, "text": "ggplot(df,aes(x,y))+geom_point(shape=x,color=x,size=3)" } ]
LocalDate plusDays() Method in Java with Examples
30 Apr, 2019 The plusDays() method of a LocalDate class in Java is used to add the number of specified day in this LocalDate and return a copy of LocalDate. For example, 2018-12-31 plus one day would result in 2019-01-01. This instance is immutable and unaffected by this method call. Syntax: public LocalDate plusDays(long daysToAdd) Parameters: This method accepts a single parameter daysToAdd which represents the days to add, may be negative. Return Value: This method returns a LocalDate based on this date with the days added, not null. Exception: This method throws DateTimeException if the result exceeds the supported date range. Below programs illustrate the plusDays() method: Program 1: // Java program to demonstrate// LocalDate.plusDays() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2018-11-13"); // print instance System.out.println("LocalDate before" + " adding days: " + date); // add 5 days LocalDate returnvalue = date.plusDays(5); // print result System.out.println("LocalDate after " + " adding days: " + returnvalue); }} LocalDate before adding days: 2018-11-13 LocalDate after adding days: 2018-11-18 Program 2: // Java program to demonstrate// LocalDate.plusDays() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2018-12-24"); // print instance System.out.println("LocalDate before" + " adding days: " + date); // add 15 days LocalDate returnvalue = date.plusDays(15); // print result System.out.println("LocalDate after " + " adding days: " + returnvalue); }} LocalDate before adding days: 2018-12-24 LocalDate after adding days: 2019-01-08 Reference:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#plusDays(long) Akanksha_Rai Java-Functions Java-LocalDate Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Apr, 2019" }, { "code": null, "e": 325, "s": 53, "text": "The plusDays() method of a LocalDate class in Java is used to add the number of specified day in this LocalDate and return a copy of LocalDate. For example, 2018-12-31 plus one day would result in 2019-01-01. This instance is immutable and unaffected by this method call." }, { "code": null, "e": 333, "s": 325, "text": "Syntax:" }, { "code": null, "e": 376, "s": 333, "text": "public LocalDate plusDays(long daysToAdd)\n" }, { "code": null, "e": 488, "s": 376, "text": "Parameters: This method accepts a single parameter daysToAdd which represents the days to add, may be negative." }, { "code": null, "e": 584, "s": 488, "text": "Return Value: This method returns a LocalDate based on this date with the days added, not null." }, { "code": null, "e": 680, "s": 584, "text": "Exception: This method throws DateTimeException if the result exceeds the supported date range." }, { "code": null, "e": 729, "s": 680, "text": "Below programs illustrate the plusDays() method:" }, { "code": null, "e": 740, "s": 729, "text": "Program 1:" }, { "code": "// Java program to demonstrate// LocalDate.plusDays() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2018-11-13\"); // print instance System.out.println(\"LocalDate before\" + \" adding days: \" + date); // add 5 days LocalDate returnvalue = date.plusDays(5); // print result System.out.println(\"LocalDate after \" + \" adding days: \" + returnvalue); }}", "e": 1339, "s": 740, "text": null }, { "code": null, "e": 1422, "s": 1339, "text": "LocalDate before adding days: 2018-11-13\nLocalDate after adding days: 2018-11-18\n" }, { "code": null, "e": 1433, "s": 1422, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalDate.plusDays() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2018-12-24\"); // print instance System.out.println(\"LocalDate before\" + \" adding days: \" + date); // add 15 days LocalDate returnvalue = date.plusDays(15); // print result System.out.println(\"LocalDate after \" + \" adding days: \" + returnvalue); }}", "e": 2034, "s": 1433, "text": null }, { "code": null, "e": 2117, "s": 2034, "text": "LocalDate before adding days: 2018-12-24\nLocalDate after adding days: 2019-01-08\n" }, { "code": null, "e": 2210, "s": 2117, "text": "Reference:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#plusDays(long)" }, { "code": null, "e": 2223, "s": 2210, "text": "Akanksha_Rai" }, { "code": null, "e": 2238, "s": 2223, "text": "Java-Functions" }, { "code": null, "e": 2253, "s": 2238, "text": "Java-LocalDate" }, { "code": null, "e": 2271, "s": 2253, "text": "Java-time package" }, { "code": null, "e": 2276, "s": 2271, "text": "Java" }, { "code": null, "e": 2281, "s": 2276, "text": "Java" } ]
Newspaper scraping using Python and News API
29 Dec, 2020 There are mainly two ways to extract data from a website: Use the API of the website (if it exists). For example, Facebook has the Facebook Graph API which allows retrieval of data posted on Facebook. Access the HTML of the webpage and extract useful information/data from it. This technique is called web scraping or web harvesting or web data extraction. In this article, we will be using the API of newsapi. You can create your own API key by clicking here. Examples: Let’s determine the concern of a personality like states president cited by newspapers, let’s take the case of MERKEL import pprintimport requests secret = "Your API" # Define the endpointurl = 'https://newsapi.org/v2/everything?' # Specify the query and# number of returnsparameters = { 'q': 'merkel', # query phrase 'pageSize': 100, # maximum is 100 'apiKey': secret # your own API key} # Make the requestresponse = requests.get(url, params = parameters) # Convert the response to # JSON format and pretty print itresponse_json = response.json()pprint.pprint(response_json) Output: Let’s combine all texts and sort the words from the greatest number to lower. from wordcloud import WordCloudimport matplotlib.pyplot as plt text_combined = '' for i in response_json['articles']: if i['description'] != None: text_combined += i['description'] + ' ' wordcount={}for word in text_combined.split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 for k,v, in sorted(wordcount.items(), key=lambda words: words[1], reverse = True): print(k,v) Output: This evaluation is ambiguous, we can make it more clear if we delete bad or usless words. Let’s define some of bad_words shown below bad_words = [“a”, “the”, “of”, “in”, “to”, “and”, “on”, “de”, “with”,“by”, “at”, “dans”, “ont”, “été”, “les”, “des”, “au”, “et”,“après”, “avec”, “qui”, “par”, “leurs”, “ils”, “a”, “pour”,“les”, “on”, “as”, “france”, “eux”, “où”, “son”, “le”, “la”,“en”, “with”, “is”, “has”, “for”, “that”, “an”, “but”, “be”,“are”, “du”, “it”, “à”, “had”, “ist”, “Der”, “um”, “zu”, “den”,“der”, “-“, “und”, “für”, “Die”, “von”, “als”,“sich”, “nicht”, “nach”, “auch” ] Now we can delete and format the text by deleting bad words # initializing bad_chars_list bad_words = ["a", "the" , "of", "in", "to", "and", "on", "de", "with", "by", "at", "dans", "ont", "été", "les", "des", "au", "et", "après", "avec", "qui", "par", "leurs", "ils", "a", "pour", "les", "on", "as", "france", "eux", "où", "son", "le", "la", "en", "with", "is", "has", "for", "that", "an", "but", "be", "are", "du", "it", "à", "had", "ist", "Der", "um", "zu", "den", "der", "-", "und", "für", "Die", "von", "als", "sich", "nicht", "nach", "auch" ] r = text_combined.replace('\s+', ' ').replace(',', ' ').replace('.', ' ')words = r.split()rst = [word for word in words if ( word.lower() not in bad_words and len(word) > 3) ] rst = ' '.join(rst) wordcount={} for word in rst.split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 for k,v, in sorted(wordcount.items(), key=lambda words: words[1], reverse = True): print(k,v) Output: Let’s plot the output word = WordCloud(max_font_size = 40).generate(rst)plt.figure()plt.imshow(word, interpolation ="bilinear")plt.axis("off")plt.show() Output: As you see in the descriptions of articles, the most dominant concern with Merkel is his defense minister Kramp-Karrenbauer, Kanzlerin just means female chancellor. We can do the same work using titles only title_combined = '' for i in response_json['articles']: title_combined += i['title'] + ' ' titles = title_combined.replace('\s+', ' ').replace(',', ' ').replace('.', ' ')words_t = titles.split()result = [word for word in words_t if ( word.lower() not in bad_words and len(word) > 3) ] result = ' '.join(result) wordcount={} for word in result.split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 word = WordCloud(max_font_size=40).generate(result)plt.figure()plt.imshow(word, interpolation="bilinear")plt.axis("off")plt.show() Output: From titles, we found out that the most concern with Merkel is Ardogan, turkey president. Python web-scraping-exercises Python-projects Python-requests python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Dec, 2020" }, { "code": null, "e": 112, "s": 54, "text": "There are mainly two ways to extract data from a website:" }, { "code": null, "e": 255, "s": 112, "text": "Use the API of the website (if it exists). For example, Facebook has the Facebook Graph API which allows retrieval of data posted on Facebook." }, { "code": null, "e": 411, "s": 255, "text": "Access the HTML of the webpage and extract useful information/data from it. This technique is called web scraping or web harvesting or web data extraction." }, { "code": null, "e": 515, "s": 411, "text": "In this article, we will be using the API of newsapi. You can create your own API key by clicking here." }, { "code": null, "e": 643, "s": 515, "text": "Examples: Let’s determine the concern of a personality like states president cited by newspapers, let’s take the case of MERKEL" }, { "code": "import pprintimport requests secret = \"Your API\" # Define the endpointurl = 'https://newsapi.org/v2/everything?' # Specify the query and# number of returnsparameters = { 'q': 'merkel', # query phrase 'pageSize': 100, # maximum is 100 'apiKey': secret # your own API key} # Make the requestresponse = requests.get(url, params = parameters) # Convert the response to # JSON format and pretty print itresponse_json = response.json()pprint.pprint(response_json)", "e": 1146, "s": 643, "text": null }, { "code": null, "e": 1154, "s": 1146, "text": "Output:" }, { "code": null, "e": 1232, "s": 1154, "text": "Let’s combine all texts and sort the words from the greatest number to lower." }, { "code": "from wordcloud import WordCloudimport matplotlib.pyplot as plt text_combined = '' for i in response_json['articles']: if i['description'] != None: text_combined += i['description'] + ' ' wordcount={}for word in text_combined.split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 for k,v, in sorted(wordcount.items(), key=lambda words: words[1], reverse = True): print(k,v)", "e": 1723, "s": 1232, "text": null }, { "code": null, "e": 1731, "s": 1723, "text": "Output:" }, { "code": null, "e": 1864, "s": 1731, "text": "This evaluation is ambiguous, we can make it more clear if we delete bad or usless words. Let’s define some of bad_words shown below" }, { "code": null, "e": 2320, "s": 1864, "text": "bad_words = [“a”, “the”, “of”, “in”, “to”, “and”, “on”, “de”, “with”,“by”, “at”, “dans”, “ont”, “été”, “les”, “des”, “au”, “et”,“après”, “avec”, “qui”, “par”, “leurs”, “ils”, “a”, “pour”,“les”, “on”, “as”, “france”, “eux”, “où”, “son”, “le”, “la”,“en”, “with”, “is”, “has”, “for”, “that”, “an”, “but”, “be”,“are”, “du”, “it”, “à”, “had”, “ist”, “Der”, “um”, “zu”, “den”,“der”, “-“, “und”, “für”, “Die”, “von”, “als”,“sich”, “nicht”, “nach”, “auch” ]" }, { "code": null, "e": 2380, "s": 2320, "text": "Now we can delete and format the text by deleting bad words" }, { "code": "# initializing bad_chars_list bad_words = [\"a\", \"the\" , \"of\", \"in\", \"to\", \"and\", \"on\", \"de\", \"with\", \"by\", \"at\", \"dans\", \"ont\", \"été\", \"les\", \"des\", \"au\", \"et\", \"après\", \"avec\", \"qui\", \"par\", \"leurs\", \"ils\", \"a\", \"pour\", \"les\", \"on\", \"as\", \"france\", \"eux\", \"où\", \"son\", \"le\", \"la\", \"en\", \"with\", \"is\", \"has\", \"for\", \"that\", \"an\", \"but\", \"be\", \"are\", \"du\", \"it\", \"à\", \"had\", \"ist\", \"Der\", \"um\", \"zu\", \"den\", \"der\", \"-\", \"und\", \"für\", \"Die\", \"von\", \"als\", \"sich\", \"nicht\", \"nach\", \"auch\" ] r = text_combined.replace('\\s+', ' ').replace(',', ' ').replace('.', ' ')words = r.split()rst = [word for word in words if ( word.lower() not in bad_words and len(word) > 3) ] rst = ' '.join(rst) wordcount={} for word in rst.split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 for k,v, in sorted(wordcount.items(), key=lambda words: words[1], reverse = True): print(k,v)", "e": 3570, "s": 2380, "text": null }, { "code": null, "e": 3578, "s": 3570, "text": "Output:" }, { "code": null, "e": 3600, "s": 3578, "text": "Let’s plot the output" }, { "code": "word = WordCloud(max_font_size = 40).generate(rst)plt.figure()plt.imshow(word, interpolation =\"bilinear\")plt.axis(\"off\")plt.show()", "e": 3731, "s": 3600, "text": null }, { "code": null, "e": 3739, "s": 3731, "text": "Output:" }, { "code": null, "e": 3946, "s": 3739, "text": "As you see in the descriptions of articles, the most dominant concern with Merkel is his defense minister Kramp-Karrenbauer, Kanzlerin just means female chancellor. We can do the same work using titles only" }, { "code": "title_combined = '' for i in response_json['articles']: title_combined += i['title'] + ' ' titles = title_combined.replace('\\s+', ' ').replace(',', ' ').replace('.', ' ')words_t = titles.split()result = [word for word in words_t if ( word.lower() not in bad_words and len(word) > 3) ] result = ' '.join(result) wordcount={} for word in result.split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 word = WordCloud(max_font_size=40).generate(result)plt.figure()plt.imshow(word, interpolation=\"bilinear\")plt.axis(\"off\")plt.show()", "e": 4693, "s": 3946, "text": null }, { "code": null, "e": 4701, "s": 4693, "text": "Output:" }, { "code": null, "e": 4791, "s": 4701, "text": "From titles, we found out that the most concern with Merkel is Ardogan, turkey president." }, { "code": null, "e": 4821, "s": 4791, "text": "Python web-scraping-exercises" }, { "code": null, "e": 4837, "s": 4821, "text": "Python-projects" }, { "code": null, "e": 4853, "s": 4837, "text": "Python-requests" }, { "code": null, "e": 4868, "s": 4853, "text": "python-utility" }, { "code": null, "e": 4875, "s": 4868, "text": "Python" }, { "code": null, "e": 4973, "s": 4875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4991, "s": 4973, "text": "Python Dictionary" }, { "code": null, "e": 5033, "s": 4991, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5055, "s": 5033, "text": "Enumerate() in Python" }, { "code": null, "e": 5090, "s": 5055, "text": "Read a file line by line in Python" }, { "code": null, "e": 5116, "s": 5090, "text": "Python String | replace()" }, { "code": null, "e": 5148, "s": 5116, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5177, "s": 5148, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5207, "s": 5177, "text": "Iterate over a list in Python" }, { "code": null, "e": 5234, "s": 5207, "text": "Python Classes and Objects" } ]
File.ReadAllLines(String) Method in C# with Examples
09 Mar, 2021 File.ReadAllLines(String) is an inbuilt File class method that is used to open a text file then reads all lines of the file into a string array and then closes the file.Syntax: public static string[] ReadAllLines (string path); Parameter: This function accepts a parameter which is illustrated below: path: This is the specified file to open for reading. Exceptions: ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars. ArgumentNullException: The path is null. PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length. DirectoryNotFoundException: The specified path is invalid. IOException: An I/O error occurred while opening the file. UnauthorizedAccessException: The path specified a file that is read-only. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission. FileNotFoundException: The file specified in the path was not found. NotSupportedException: The path is in an invalid format. SecurityException: The caller does not have the required permission. Return Value: Returns a string array containing all lines of the file.Below are the programs to illustrate the File.ReadAllLines(String) method.Program 1: Initially, a file file.txt is created with some contents shown below- C# // C# program to illustrate the usage// of File.ReadAllLines(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Calling the ReadAllLines() function string[] readText = File.ReadAllLines(path); foreach(string s in readText) { // Printing the string array containing // all lines of the file. Console.WriteLine(s); } }} Output: GFG Geeks GeeksforGeeks Program 2: Initially, no file was created. Below code itself create a file file.txt with some specified contents. C# // C# program to illustrate the usage// of File.ReadAllLines(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Adding below contents to the file string[] createText = { "GFG is a CS portal." }; File.WriteAllLines(path, createText); // Calling the ReadAllLines() function string[] readText = File.ReadAllLines(path); foreach(string s in readText) { // Printing the string array containing // all lines of the file. Console.WriteLine(s); } }} Output: GFG is a CS portal. arorakashish0911 CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | Method Overriding C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object C# | Constructors
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2021" }, { "code": null, "e": 207, "s": 28, "text": "File.ReadAllLines(String) is an inbuilt File class method that is used to open a text file then reads all lines of the file into a string array and then closes the file.Syntax: " }, { "code": null, "e": 258, "s": 207, "text": "public static string[] ReadAllLines (string path);" }, { "code": null, "e": 333, "s": 258, "text": "Parameter: This function accepts a parameter which is illustrated below: " }, { "code": null, "e": 387, "s": 333, "text": "path: This is the specified file to open for reading." }, { "code": null, "e": 400, "s": 387, "text": "Exceptions: " }, { "code": null, "e": 546, "s": 400, "text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars." }, { "code": null, "e": 587, "s": 546, "text": "ArgumentNullException: The path is null." }, { "code": null, "e": 690, "s": 587, "text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 749, "s": 690, "text": "DirectoryNotFoundException: The specified path is invalid." }, { "code": null, "e": 808, "s": 749, "text": "IOException: An I/O error occurred while opening the file." }, { "code": null, "e": 1030, "s": 808, "text": "UnauthorizedAccessException: The path specified a file that is read-only. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission." }, { "code": null, "e": 1099, "s": 1030, "text": "FileNotFoundException: The file specified in the path was not found." }, { "code": null, "e": 1156, "s": 1099, "text": "NotSupportedException: The path is in an invalid format." }, { "code": null, "e": 1225, "s": 1156, "text": "SecurityException: The caller does not have the required permission." }, { "code": null, "e": 1451, "s": 1225, "text": "Return Value: Returns a string array containing all lines of the file.Below are the programs to illustrate the File.ReadAllLines(String) method.Program 1: Initially, a file file.txt is created with some contents shown below- " }, { "code": null, "e": 1456, "s": 1453, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.ReadAllLines(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Calling the ReadAllLines() function string[] readText = File.ReadAllLines(path); foreach(string s in readText) { // Printing the string array containing // all lines of the file. Console.WriteLine(s); } }}", "e": 2027, "s": 1456, "text": null }, { "code": null, "e": 2037, "s": 2027, "text": "Output: " }, { "code": null, "e": 2061, "s": 2037, "text": "GFG\nGeeks\nGeeksforGeeks" }, { "code": null, "e": 2176, "s": 2061, "text": "Program 2: Initially, no file was created. Below code itself create a file file.txt with some specified contents. " }, { "code": null, "e": 2179, "s": 2176, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.ReadAllLines(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Adding below contents to the file string[] createText = { \"GFG is a CS portal.\" }; File.WriteAllLines(path, createText); // Calling the ReadAllLines() function string[] readText = File.ReadAllLines(path); foreach(string s in readText) { // Printing the string array containing // all lines of the file. Console.WriteLine(s); } }}", "e": 2897, "s": 2179, "text": null }, { "code": null, "e": 2907, "s": 2897, "text": "Output: " }, { "code": null, "e": 2927, "s": 2907, "text": "GFG is a CS portal." }, { "code": null, "e": 2944, "s": 2927, "text": "arorakashish0911" }, { "code": null, "e": 2965, "s": 2944, "text": "CSharp-File-Handling" }, { "code": null, "e": 2968, "s": 2965, "text": "C#" }, { "code": null, "e": 3066, "s": 2968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3094, "s": 3066, "text": "C# Dictionary with examples" }, { "code": null, "e": 3137, "s": 3094, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3168, "s": 3137, "text": "Introduction to .NET Framework" }, { "code": null, "e": 3183, "s": 3168, "text": "C# | Delegates" }, { "code": null, "e": 3232, "s": 3183, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3248, "s": 3232, "text": "C# | Data Types" }, { "code": null, "e": 3271, "s": 3248, "text": "C# | Method Overriding" }, { "code": null, "e": 3311, "s": 3271, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 3333, "s": 3311, "text": "C# | Class and Object" } ]
SQL | WHERE Clause
19 May, 2022 WHERE keyword is used for fetching filtered data in a result set. It is used to fetch data according to a particular criteria. WHERE keyword can also be used to filter data by matching patterns. Basic Syntax: SELECT column1,column2 FROM table_name WHERE column_name operator value; column1 , column2: fields int the table table_name: name of table column_name: name of field used for filtering the data operator: operation to be considered for filtering value: exact value or pattern to get related data in result List of operators that can be used with where clause: Queries To fetch record of students with age equal to 20 SELECT * FROM Student WHERE Age=20; Output: To fetch Name and Address of students with ROLL_NO greater than 3 SELECT ROLL_NO,NAME,ADDRESS FROM Student WHERE ROLL_NO > 3; Output: BETWEEN operator It is used to fetch filtered data in a given range inclusive of two values. Basic Syntax: SELECT column1,column2 FROM table_name WHERE column_name BETWEEN value1 AND value2; BETWEEN: operator name value1 AND value2: exact value from value1 to value2 to get related data in result set. Queries To fetch records of students where ROLL_NO is between 1 and 3 (inclusive) SELECT * FROM Student WHERE ROLL_NO BETWEEN 1 AND 3; Output: To fetch NAME,ADDRESS of students where Age is between 20 and 30 (inclusive) SELECT NAME,ADDRESS FROM Student WHERE Age BETWEEN 20 AND 30; Output: LIKE operator It is used to fetch filtered data by searching for a particular pattern in where clause. Basic Syntax: SELECT column1,column2 FROM table_name WHERE column_name LIKE pattern; LIKE: operator name pattern: exact value extracted from the pattern to get related data in result set. Note: The character(s) in pattern are case sensitive. Queries To fetch records of students where NAME starts with letter S. SELECT * FROM Student WHERE NAME LIKE 'S%'; The ‘%'(wildcard) signifies the later characters here which can be of any length and value.More about wildcards will be discussed in the later set. Output: To fetch records of students where NAME contains the pattern ‘AM’. SELECT * FROM Student WHERE NAME LIKE '%AM%'; Output: IN operator It is used to fetch filtered data same as fetched by ‘=’ operator just the difference is that here we can specify multiple values for which we can get the result set. Basic Syntax: SELECT column1,column2 FROM table_name WHERE column_name IN (value1,value2,..); IN: operator name value1,value2,..: exact value matching the values given and get related data in result set. Queries To fetch NAME and ADDRESS of students where Age is 18 or 20. SELECT NAME,ADDRESS FROM Student WHERE Age IN (18,20); Output: To fetch records of students where ROLL_NO is 1 or 4. SELECT * FROM Student WHERE ROLL_NO IN (1,4); Output: This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. aditimantri2196 kamaniashish17 sagartomar9927 SQL-Clauses-Operators Articles DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n19 May, 2022" }, { "code": null, "e": 119, "s": 53, "text": "WHERE keyword is used for fetching filtered data in a result set." }, { "code": null, "e": 180, "s": 119, "text": "It is used to fetch data according to a particular criteria." }, { "code": null, "e": 248, "s": 180, "text": "WHERE keyword can also be used to filter data by matching patterns." }, { "code": null, "e": 335, "s": 248, "text": "Basic Syntax: SELECT column1,column2 FROM table_name WHERE column_name operator value;" }, { "code": null, "e": 568, "s": 335, "text": "column1 , column2: fields int the table\ntable_name: name of table\ncolumn_name: name of field used for filtering the data\noperator: operation to be considered for filtering\nvalue: exact value or pattern to get related data in result " }, { "code": null, "e": 622, "s": 568, "text": "List of operators that can be used with where clause:" }, { "code": null, "e": 630, "s": 622, "text": "Queries" }, { "code": null, "e": 679, "s": 630, "text": "To fetch record of students with age equal to 20" }, { "code": null, "e": 715, "s": 679, "text": "SELECT * FROM Student WHERE Age=20;" }, { "code": null, "e": 723, "s": 715, "text": "Output:" }, { "code": null, "e": 789, "s": 723, "text": "To fetch Name and Address of students with ROLL_NO greater than 3" }, { "code": null, "e": 849, "s": 789, "text": "SELECT ROLL_NO,NAME,ADDRESS FROM Student WHERE ROLL_NO > 3;" }, { "code": null, "e": 857, "s": 849, "text": "Output:" }, { "code": null, "e": 874, "s": 857, "text": "BETWEEN operator" }, { "code": null, "e": 1048, "s": 874, "text": "It is used to fetch filtered data in a given range inclusive of two values. Basic Syntax: SELECT column1,column2 FROM table_name WHERE column_name BETWEEN value1 AND value2;" }, { "code": null, "e": 1072, "s": 1048, "text": "BETWEEN: operator name " }, { "code": null, "e": 1162, "s": 1072, "text": "value1 AND value2: exact value from value1 to value2 to get related data in result set. " }, { "code": null, "e": 1170, "s": 1162, "text": "Queries" }, { "code": null, "e": 1244, "s": 1170, "text": "To fetch records of students where ROLL_NO is between 1 and 3 (inclusive)" }, { "code": null, "e": 1297, "s": 1244, "text": "SELECT * FROM Student WHERE ROLL_NO BETWEEN 1 AND 3;" }, { "code": null, "e": 1305, "s": 1297, "text": "Output:" }, { "code": null, "e": 1382, "s": 1305, "text": "To fetch NAME,ADDRESS of students where Age is between 20 and 30 (inclusive)" }, { "code": null, "e": 1444, "s": 1382, "text": "SELECT NAME,ADDRESS FROM Student WHERE Age BETWEEN 20 AND 30;" }, { "code": null, "e": 1452, "s": 1444, "text": "Output:" }, { "code": null, "e": 1466, "s": 1452, "text": "LIKE operator" }, { "code": null, "e": 1640, "s": 1466, "text": "It is used to fetch filtered data by searching for a particular pattern in where clause. Basic Syntax: SELECT column1,column2 FROM table_name WHERE column_name LIKE pattern;" }, { "code": null, "e": 1661, "s": 1640, "text": "LIKE: operator name " }, { "code": null, "e": 1798, "s": 1661, "text": "pattern: exact value extracted from the pattern to get related data in result set. Note: The character(s) in pattern are case sensitive." }, { "code": null, "e": 1806, "s": 1798, "text": "Queries" }, { "code": null, "e": 1868, "s": 1806, "text": "To fetch records of students where NAME starts with letter S." }, { "code": null, "e": 1913, "s": 1868, "text": "SELECT * FROM Student WHERE NAME LIKE 'S%'; " }, { "code": null, "e": 2069, "s": 1913, "text": "The ‘%'(wildcard) signifies the later characters here which can be of any length and value.More about wildcards will be discussed in the later set. Output:" }, { "code": null, "e": 2136, "s": 2069, "text": "To fetch records of students where NAME contains the pattern ‘AM’." }, { "code": null, "e": 2182, "s": 2136, "text": "SELECT * FROM Student WHERE NAME LIKE '%AM%';" }, { "code": null, "e": 2190, "s": 2182, "text": "Output:" }, { "code": null, "e": 2202, "s": 2190, "text": "IN operator" }, { "code": null, "e": 2463, "s": 2202, "text": "It is used to fetch filtered data same as fetched by ‘=’ operator just the difference is that here we can specify multiple values for which we can get the result set. Basic Syntax: SELECT column1,column2 FROM table_name WHERE column_name IN (value1,value2,..);" }, { "code": null, "e": 2482, "s": 2463, "text": "IN: operator name " }, { "code": null, "e": 2574, "s": 2482, "text": "value1,value2,..: exact value matching the values given and get related data in result set." }, { "code": null, "e": 2582, "s": 2574, "text": "Queries" }, { "code": null, "e": 2643, "s": 2582, "text": "To fetch NAME and ADDRESS of students where Age is 18 or 20." }, { "code": null, "e": 2698, "s": 2643, "text": "SELECT NAME,ADDRESS FROM Student WHERE Age IN (18,20);" }, { "code": null, "e": 2706, "s": 2698, "text": "Output:" }, { "code": null, "e": 2760, "s": 2706, "text": "To fetch records of students where ROLL_NO is 1 or 4." }, { "code": null, "e": 2806, "s": 2760, "text": "SELECT * FROM Student WHERE ROLL_NO IN (1,4);" }, { "code": null, "e": 2814, "s": 2806, "text": "Output:" }, { "code": null, "e": 3236, "s": 2814, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3252, "s": 3236, "text": "aditimantri2196" }, { "code": null, "e": 3267, "s": 3252, "text": "kamaniashish17" }, { "code": null, "e": 3282, "s": 3267, "text": "sagartomar9927" }, { "code": null, "e": 3304, "s": 3282, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 3313, "s": 3304, "text": "Articles" }, { "code": null, "e": 3318, "s": 3313, "text": "DBMS" }, { "code": null, "e": 3322, "s": 3318, "text": "SQL" }, { "code": null, "e": 3327, "s": 3322, "text": "DBMS" }, { "code": null, "e": 3331, "s": 3327, "text": "SQL" } ]
How to use AppBar Component in ReactJS ?
12 Feb, 2021 The App Bar displays information and actions relating to the current screen. Material UI for React has this component available for us and it is very easy to integrate. We can use the AppBar Component in ReactJS using the following approach. Creating React Application And Installing Module: 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 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core npm install @material-ui/icons App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from "react";import Toolbar from "@material-ui/core/Toolbar";import AppBar from "@material-ui/core/AppBar";import Typography from "@material-ui/core/Typography";import IconButton from "@material-ui/core/IconButton";import Button from "@material-ui/core/Button";import MenuIcon from "@material-ui/icons/Menu"; const App = () => { return ( <div> <h2>How to use AppBar Component in ReactJS?</h2> <AppBar position="static"> <Toolbar> <IconButton edge="start" style={{ marginRight: 20, }} color="inherit" aria-label="menu" > <MenuIcon /> </IconButton> <Typography variant="h6" style={{ flexGrow: 1, }} > Dashboard </Typography> <Button color="inherit">Logout</Button> </Toolbar> </AppBar> </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. React-Questions JavaScript ReactJS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2021" }, { "code": null, "e": 270, "s": 28, "text": "The App Bar displays information and actions relating to the current screen. Material UI for React has this component available for us and it is very easy to integrate. We can use the AppBar Component in ReactJS using the following approach." }, { "code": null, "e": 320, "s": 270, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 384, "s": 320, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 416, "s": 384, "text": "npx create-react-app foldername" }, { "code": null, "e": 516, "s": 416, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 530, "s": 516, "text": "cd foldername" }, { "code": null, "e": 639, "s": 530, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 700, "s": 639, "text": "npm install @material-ui/core\nnpm install @material-ui/icons" }, { "code": null, "e": 829, "s": 700, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 840, "s": 829, "text": "Javascript" }, { "code": "import React from \"react\";import Toolbar from \"@material-ui/core/Toolbar\";import AppBar from \"@material-ui/core/AppBar\";import Typography from \"@material-ui/core/Typography\";import IconButton from \"@material-ui/core/IconButton\";import Button from \"@material-ui/core/Button\";import MenuIcon from \"@material-ui/icons/Menu\"; const App = () => { return ( <div> <h2>How to use AppBar Component in ReactJS?</h2> <AppBar position=\"static\"> <Toolbar> <IconButton edge=\"start\" style={{ marginRight: 20, }} color=\"inherit\" aria-label=\"menu\" > <MenuIcon /> </IconButton> <Typography variant=\"h6\" style={{ flexGrow: 1, }} > Dashboard </Typography> <Button color=\"inherit\">Logout</Button> </Toolbar> </AppBar> </div> );}; export default App;", "e": 1807, "s": 840, "text": null }, { "code": null, "e": 1920, "s": 1807, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 1930, "s": 1920, "text": "npm start" }, { "code": null, "e": 2029, "s": 1930, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 2045, "s": 2029, "text": "React-Questions" }, { "code": null, "e": 2056, "s": 2045, "text": "JavaScript" }, { "code": null, "e": 2064, "s": 2056, "text": "ReactJS" } ]